Copy code from the holdingarea into the target locations. bug235_bringup_0
authorMatt Plumtree <matt.plumtree@nokia.com>
Wed, 06 Oct 2010 17:59:01 +0100
branchbug235_bringup_0
changeset 53 c2ef9095503a
parent 52 39e5f73667ba
child 54 067180f57b12
Copy code from the holdingarea into the target locations. Some initial rework of CMakeLists.txt files, but not yet tested.
hostsupport/hostegl/CMakeLists.txt
hostsupport/hostegl/inc/EGLConfig.h
hostsupport/hostegl/inc/EGLContext.h
hostsupport/hostegl/inc/EGLDisplay.h
hostsupport/hostegl/inc/EGLExtension.h
hostsupport/hostegl/inc/EGLImage.h
hostsupport/hostegl/inc/EGLOs.h
hostsupport/hostegl/inc/EGLPbufferSurface.h
hostsupport/hostegl/inc/EGLProcess.h
hostsupport/hostegl/inc/EGLState.h
hostsupport/hostegl/inc/EGLStructs.h
hostsupport/hostegl/inc/EGLSurface.h
hostsupport/hostegl/inc/EGLThread.h
hostsupport/hostegl/inc/EGLUtils.h
hostsupport/hostegl/inc/EGLWindowSurface.h
hostsupport/hostegl/inc/TransparentColor.h
hostsupport/hostegl/inc/eglDefinitions.h
hostsupport/hostegl/inc/eglInternal.h
hostsupport/hostegl/src/ColorDescriptor.cpp
hostsupport/hostegl/src/EGLConfig.cpp
hostsupport/hostegl/src/EGLContext.cpp
hostsupport/hostegl/src/EGLDisplay.cpp
hostsupport/hostegl/src/EGLExtension.cpp
hostsupport/hostegl/src/EGLImage.cpp
hostsupport/hostegl/src/EGLPbufferSurface.cpp
hostsupport/hostegl/src/EGLProcess.cpp
hostsupport/hostegl/src/EGLState.cpp
hostsupport/hostegl/src/EGLSurface.cpp
hostsupport/hostegl/src/EGLThread.cpp
hostsupport/hostegl/src/EGLUtils.cpp
hostsupport/hostegl/src/EGLWindowSurface.cpp
hostsupport/hostegl/src/TransparentColor.cpp
hostsupport/hostegl/src/eglapi.cpp
hostsupport/hostegl/src/linux/EGLOs.cpp
hostsupport/hostegl/src/win32/EGLOs.cpp
hostsupport/hostopengles11/CMakeLists.txt
hostsupport/hostopengles11/inc/EGLInterface.h
hostsupport/hostopengles11/inc/GLESArray.h
hostsupport/hostopengles11/inc/GLESBuffer.h
hostsupport/hostopengles11/inc/GLESContext.h
hostsupport/hostopengles11/inc/GLESDesktopGL.h
hostsupport/hostopengles11/inc/GLESTexture.h
hostsupport/hostopengles11/inc/glDefinitions.h
hostsupport/hostopengles11/inc/glesGet.h
hostsupport/hostopengles11/inc/glesInternal.h
hostsupport/hostopengles11/inc/glesOS.h
hostsupport/hostopengles11/src/EGLInterface.cpp
hostsupport/hostopengles11/src/GLESArray.cpp
hostsupport/hostopengles11/src/GLESContext.cpp
hostsupport/hostopengles11/src/GLESDesktopGL.cpp
hostsupport/hostopengles11/src/GLESTexture.cpp
hostsupport/hostopengles11/src/glesGet.cpp
hostsupport/hostopengles11/src/glesOS.cpp
hostsupport/hostopengles11/src/glesapi.cpp
hostsupport/hostopengles20/CMakeLists.txt
hostsupport/hostopengles20/group/bld.inf
hostsupport/hostopengles20/src/GLES2/blend.c
hostsupport/hostopengles20/src/GLES2/buffer.c
hostsupport/hostopengles20/src/GLES2/buffer.h
hostsupport/hostopengles20/src/GLES2/clear.c
hostsupport/hostopengles20/src/GLES2/context.c
hostsupport/hostopengles20/src/GLES2/context.h
hostsupport/hostopengles20/src/GLES2/degl.cpp
hostsupport/hostopengles20/src/GLES2/degl.h
hostsupport/hostopengles20/src/GLES2/depth.c
hostsupport/hostopengles20/src/GLES2/draw.c
hostsupport/hostopengles20/src/GLES2/fbo.c
hostsupport/hostopengles20/src/GLES2/fbo.h
hostsupport/hostopengles20/src/GLES2/get.c
hostsupport/hostopengles20/src/GLES2/get.h
hostsupport/hostopengles20/src/GLES2/half.c
hostsupport/hostopengles20/src/GLES2/half.h
hostsupport/hostopengles20/src/GLES2/hgl.c
hostsupport/hostopengles20/src/GLES2/hgl.h
hostsupport/hostopengles20/src/GLES2/object.c
hostsupport/hostopengles20/src/GLES2/object.h
hostsupport/hostopengles20/src/GLES2/pixel.c
hostsupport/hostopengles20/src/GLES2/platform.c
hostsupport/hostopengles20/src/GLES2/platform.h
hostsupport/hostopengles20/src/GLES2/program.c
hostsupport/hostopengles20/src/GLES2/program.h
hostsupport/hostopengles20/src/GLES2/shader.c
hostsupport/hostopengles20/src/GLES2/shader.h
hostsupport/hostopengles20/src/GLES2/stencil.c
hostsupport/hostopengles20/src/GLES2/texture.c
hostsupport/hostopengles20/src/GLES2/texture.h
hostsupport/hostopengles20/src/GLES2/util.c
hostsupport/hostopengles20/src/GLES2/util.h
hostsupport/hostopengles20/src/GLES2/vertex.c
hostsupport/hostopengles20/src/GLES2/vertex.h
hostsupport/hostopengles20/src/include/common.h
hostsupport/hostopenvg/CMakeLists.txt
hostsupport/hostopenvg/genheader/bin2h.py
hostsupport/hostopenvg/genheader/c_utils.py
hostsupport/hostopenvg/genheader/make_alpha_rcp.py
hostsupport/hostopenvg/genheader/make_gamma_lut.py
hostsupport/hostopenvg/genheader/plot-edges.py
hostsupport/hostopenvg/src/riApi.cpp
hostsupport/hostopenvg/src/riArray.h
hostsupport/hostopenvg/src/riContext.cpp
hostsupport/hostopenvg/src/riContext.h
hostsupport/hostopenvg/src/riDefs.h
hostsupport/hostopenvg/src/riEGLOS.h
hostsupport/hostopenvg/src/riFont.cpp
hostsupport/hostopenvg/src/riFont.h
hostsupport/hostopenvg/src/riImage.cpp
hostsupport/hostopenvg/src/riImage.h
hostsupport/hostopenvg/src/riMath.cpp
hostsupport/hostopenvg/src/riMath.h
hostsupport/hostopenvg/src/riMiniEGL.cpp
hostsupport/hostopenvg/src/riPath.cpp
hostsupport/hostopenvg/src/riPath.h
hostsupport/hostopenvg/src/riPixelPipe.cpp
hostsupport/hostopenvg/src/riPixelPipe.h
hostsupport/hostopenvg/src/riRasterizer.cpp
hostsupport/hostopenvg/src/riRasterizer.h
hostsupport/hostopenvg/src/riUtils.cpp
hostsupport/hostopenvg/src/riUtils.h
hostsupport/hostopenvg/src/riVGU.cpp
hostsupport/hostopenvg/src/sfAlphaRcp.h
hostsupport/hostopenvg/src/sfBlitter.cpp
hostsupport/hostopenvg/src/sfBlitter.h
hostsupport/hostopenvg/src/sfCompiler.cpp
hostsupport/hostopenvg/src/sfCompiler.h
hostsupport/hostopenvg/src/sfDynamicBlitter.cpp
hostsupport/hostopenvg/src/sfDynamicBlitter.h
hostsupport/hostopenvg/src/sfDynamicPixelPipe.cpp
hostsupport/hostopenvg/src/sfDynamicPixelPipe.h
hostsupport/hostopenvg/src/sfEGLInterface.cpp
hostsupport/hostopenvg/src/sfEGLInterface.h
hostsupport/hostopenvg/src/sfFunctionCache.h
hostsupport/hostopenvg/src/sfGammaLUT.h
hostsupport/hostopenvg/src/sfMask.h
hostsupport/hostopenvg/src/src/linux/riEGLOS.cpp
hostsupport/hostopenvg/src/src/macosx/riEGLOS.cpp
hostsupport/hostopenvg/src/src/null/riEGLOS.cpp
hostsupport/hostopenvg/src/src/riApi.cpp
hostsupport/hostopenvg/src/src/riArray.h
hostsupport/hostopenvg/src/src/riContext.cpp
hostsupport/hostopenvg/src/src/riContext.h
hostsupport/hostopenvg/src/src/riDefs.h
hostsupport/hostopenvg/src/src/riEGLOS.h
hostsupport/hostopenvg/src/src/riFont.cpp
hostsupport/hostopenvg/src/src/riFont.h
hostsupport/hostopenvg/src/src/riImage.cpp
hostsupport/hostopenvg/src/src/riImage.h
hostsupport/hostopenvg/src/src/riMath.cpp
hostsupport/hostopenvg/src/src/riMath.h
hostsupport/hostopenvg/src/src/riMiniEGL.cpp
hostsupport/hostopenvg/src/src/riPath.cpp
hostsupport/hostopenvg/src/src/riPath.h
hostsupport/hostopenvg/src/src/riPixelPipe.cpp
hostsupport/hostopenvg/src/src/riPixelPipe.h
hostsupport/hostopenvg/src/src/riRasterizer.cpp
hostsupport/hostopenvg/src/src/riRasterizer.h
hostsupport/hostopenvg/src/src/riUtils.cpp
hostsupport/hostopenvg/src/src/riUtils.h
hostsupport/hostopenvg/src/src/riVGU.cpp
hostsupport/hostopenvg/src/src/sfAlphaRcp.h
hostsupport/hostopenvg/src/src/sfBlitter.cpp
hostsupport/hostopenvg/src/src/sfBlitter.h
hostsupport/hostopenvg/src/src/sfCompiler.cpp
hostsupport/hostopenvg/src/src/sfCompiler.h
hostsupport/hostopenvg/src/src/sfDynamicBlitter.cpp
hostsupport/hostopenvg/src/src/sfDynamicBlitter.h
hostsupport/hostopenvg/src/src/sfDynamicPixelPipe.cpp
hostsupport/hostopenvg/src/src/sfDynamicPixelPipe.h
hostsupport/hostopenvg/src/src/sfEGLInterface.cpp
hostsupport/hostopenvg/src/src/sfEGLInterface.h
hostsupport/hostopenvg/src/src/sfFunctionCache.h
hostsupport/hostopenvg/src/src/sfGammaLUT.h
hostsupport/hostopenvg/src/src/sfMask.h
hostsupport/hostopenvg/src/src/win32/riEGLOS.cpp
hostsupport/inc/BufferContainer.h
hostsupport/inc/ColorDescriptor.h
hostsupport/inc/EGL/egl.h
hostsupport/inc/EGL/eglext.h
hostsupport/inc/EGL/eglplatform.h
hostsupport/inc/GL/glext.h
hostsupport/inc/GL/glut.h
hostsupport/inc/GL/wglext.h
hostsupport/inc/GLES/egl.h
hostsupport/inc/GLES/gl.h
hostsupport/inc/GLES/glext.h
hostsupport/inc/GLES/glextplatform.h
hostsupport/inc/GLES/glplatform.h
hostsupport/inc/GLES2/gl2.h
hostsupport/inc/GLES2/gl2ext.h
hostsupport/inc/GLES2/gl2platform.h
hostsupport/inc/GLES2Interface.h
hostsupport/inc/GLESInterface.h
hostsupport/inc/ImageTarget.h
hostsupport/inc/KHR/khrplatform.h
hostsupport/inc/SurfaceDescriptor.h
hostsupport/inc/VG/openvg.h
hostsupport/inc/VG/vgext.h
hostsupport/inc/VG/vgplatform.h
hostsupport/inc/VG/vgu.h
hostsupport/inc/VGInterface.h
vghwinterface/inc/guestvideodriverinterfaceconstants.h
vghwinterface/vghwapiwrapper/CMakeLists.txt
vghwinterface/vghwapiwrapper/inc/KhronosAPIWrapper.h
vghwinterface/vghwapiwrapper/inc/apiwrapper.h
vghwinterface/vghwapiwrapper/inc/driverapiwrapper.h
vghwinterface/vghwapiwrapper/inc/eglapiwrapper.h
vghwinterface/vghwapiwrapper/inc/egltypes.h
vghwinterface/vghwapiwrapper/inc/graphicsvhwcallback.h
vghwinterface/vghwapiwrapper/inc/hostthreadadapter.h
vghwinterface/vghwapiwrapper/inc/khronosapiwrapperdefs.h
vghwinterface/vghwapiwrapper/inc/opengles11apiwrapper.h
vghwinterface/vghwapiwrapper/inc/openvgapiwrapper.h
vghwinterface/vghwapiwrapper/inc/platformthreading.h
vghwinterface/vghwapiwrapper/inc/platformtypes.h
vghwinterface/vghwapiwrapper/inc/syborg-graphicswrapper.h
vghwinterface/vghwapiwrapper/src/KhronosAPIWrapper.cpp
vghwinterface/vghwapiwrapper/src/apiwrapper.cpp
vghwinterface/vghwapiwrapper/src/driverapiwrapper.cpp
vghwinterface/vghwapiwrapper/src/eglapiwrapper.cpp
vghwinterface/vghwapiwrapper/src/opengles11apiwrapper.cpp
vghwinterface/vghwapiwrapper/src/openvgapiwrapper.cpp
vghwinterface/vghwapiwrapper/src/platformthreading.cpp
vghwinterface/vghwapiwrapper/src/syborg-graphicswrapper.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/CMakeLists.txt	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,111 @@
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+# CMake meta build file for host libEGL
+
+set(EGL_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)
+set(EGL_INC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/inc)
+
+find_package(OpenGL)
+
+if(WIN32)
+	message("*** EGL Win32")
+	set(EGL_SSE_FLAGS "/arch:SSE2")
+	set(EGL_PLATFORM_LINK_LIBRARIES "")
+	set(EGL_PLATFORM_SOURCE_DIR "win32")
+else(WIN32)
+	set(EGL_SSE_FLAGS "-msse2 -mfpmath=sse -march=pentium4")
+	set(EGL_PLATFORM_LINK_LIBRARIES m stdc++)
+	set(EGL_PLATFORM_SOURCE_DIR "linux")
+endif(WIN32)
+
+set(EGL_SRC_FILES
+    ${COMMON_INC_DIR}/SurfaceDescriptor.h
+    ${COMMON_INC_DIR}/ColorDescriptor.h
+    ${COMMON_INC_DIR}/GLESInterface.h
+    ${COMMON_INC_DIR}/GLES2Interface.h
+    ${COMMON_INC_DIR}/VGInterface.h
+    ${COMMON_INC_DIR}/BufferContainer.h
+    ${COMMON_INC_DIR}/ImageTarget.h
+    ${EGL_INC_DIR}/EGLConfig.h
+    ${EGL_INC_DIR}/EGLContext.h
+    ${EGL_INC_DIR}/eglDefinitions.h
+    ${EGL_INC_DIR}/EGLDisplay.h
+    ${EGL_INC_DIR}/eglInternal.h
+    ${EGL_INC_DIR}/EGLPbufferSurface.h
+    ${EGL_INC_DIR}/EGLProcess.h
+    ${EGL_INC_DIR}/EGLState.h
+    ${EGL_INC_DIR}/EGLSurface.h
+    ${EGL_INC_DIR}/EGLThread.h
+    ${EGL_INC_DIR}/EGLWindowSurface.h
+    ${EGL_INC_DIR}/TransparentColor.h
+    ${EGL_INC_DIR}/EGLUtils.h
+    ${EGL_INC_DIR}/EGLImage.h
+    ${EGL_INC_DIR}/EGLExtension.h
+    ${EGL_INC_DIR}/EGLOs.h
+    ${EGL_INC_DIR}/EGLStructs.h
+
+    ${EGL_SRC_DIR}/ColorDescriptor.cpp
+    ${EGL_SRC_DIR}/eglapi.cpp
+    ${EGL_SRC_DIR}/EGLConfig.cpp
+    ${EGL_SRC_DIR}/EGLContext.cpp
+    ${EGL_SRC_DIR}/EGLDisplay.cpp
+    ${EGL_SRC_DIR}/EGLPbufferSurface.cpp
+    ${EGL_SRC_DIR}/EGLProcess.cpp
+    ${EGL_SRC_DIR}/EGLState.cpp
+    ${EGL_SRC_DIR}/EGLSurface.cpp
+    ${EGL_SRC_DIR}/EGLThread.cpp
+    ${EGL_SRC_DIR}/EGLWindowSurface.cpp
+    ${EGL_SRC_DIR}/TransparentColor.cpp
+    ${EGL_SRC_DIR}/EGLUtils.cpp
+    ${EGL_SRC_DIR}/EGLImage.cpp
+    ${EGL_SRC_DIR}/EGLExtension.cpp
+    ${EGL_SRC_DIR}/${EGL_PLATFORM_SOURCE_DIR}/EGLOs.cpp
+  )
+
+include_directories(
+  ${EGL_SRC_DIR}
+  ${EGL_INC_DIR}
+  ${COMMON_INC_DIR}
+  )
+
+# \todo MSVC:
+# Probably not needed for EGL, but it might be a good idea to define these:
+# set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -msse2 -mfpmath=sse -march=pentium4")
+# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse2 -mfpmath=sse -march=pentium4")
+
+if(PLATSIM_EXTENSIONS)
+   add_definitions(-DKHRONOS_APICALL_EXPORT -DEGLI_USE_PLATSIM_EXTENSIONS)
+else(PLATSIM_EXNTENSIONS)
+   add_definitions(-DKHRONOS_APICALL_EXPORT)
+endif(PLATSIM_EXTENSIONS)
+
+add_library(${LIBRARY_NAME_PREFIX}EGL SHARED ${EGL_SRC_FILES})
+
+set_target_properties(${LIBRARY_NAME_PREFIX}EGL PROPERTIES LINK_INTERFACE_LIBRARIES "")
+
+target_link_libraries(${LIBRARY_NAME_PREFIX}EGL ${EGL_PLATFORM_LINK_LIBRARIES} ${OPENGL_LIBRARIES})
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLConfig.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,120 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLCONFIG_H_
+#define _EGLCONFIG_H_
+
+#include <EGL/egl.h>
+#include "ColorDescriptor.h"
+#include "TransparentColor.h"
+
+class CEGLConfig
+{
+public:
+	CEGLConfig(void);
+    CEGLConfig( CColorDescriptor&   colorDescriptor,
+                EGLBoolean          bindToTexRGB,           /* EGL_BIND_TO_TEXTURE_RGB*/
+                EGLBoolean          bindToTexRGBA,          /* EGL_BIND_TO_TEXTURE_RGBA */
+                EGLenum             configCaveat,           /* EGL_CONFIG_CAVEAT */
+                EGLint              configId,               /* EGL_CONFIG_ID */
+                EGLint              conformant,             /* EGL_CONFORMANT */
+                EGLint              depthSize,              /* EGL_DEPTH_SIZE */
+                EGLint              level,                  /* EGL_LEVEL */
+                EGLint              maxSwapInterval,        /* EGL_MAX_SWAP_INTERVAL */
+                EGLint              minSwapInterval,        /* EGL_MIN_SWAP_INTERVAL */
+                EGLBoolean          nativeRenderable,       /* EGL_NATIVE_RENDERABLE */
+                EGLint              nativeVisualType,       /* EGL_NATIVE_VIDUAL_TYPE */
+                EGLint              renderableType,         /* EGL_RENDERABLE_TYPE */
+                EGLint              sampleBuffers,          /* EGL_SAMPLE_BUFFERS */
+                EGLint              samples,                /* EGL_SAMPLES */
+                EGLint              stencilSize,            /* EGL_STENCIL_SIZE */
+                EGLint              surfaceType,
+                CTransparentColor*  transparentColor );
+
+	~CEGLConfig(void);
+
+    /*
+    Setting up config values. 
+    Return EGL_NO_ERROR if all ok and
+    EGL_BAD_PARAMETER if some conflict with parameters
+    */
+	EGLint SetUpConfig( EGLint red, EGLint green, EGLint blue, 
+                        EGLint luminance, EGLint alpha, 
+                        EGLint alphaMask, EGLint samples, EGLint bpp,
+                        EGLint id );
+                    
+public:
+    inline void SetId( int id ) { m_configId = id; }
+    inline EGLint Id() const { return m_configId; }
+    EGLBoolean SetAttribute( EGLint attribute, EGLint value );
+    EGLint GetAttribute( EGLint attribute ) const;
+    inline CColorDescriptor* GetDescriptor() { return &m_colorDescriptor; }
+
+    bool operator>( const CEGLConfig& rhs ) const;
+    bool operator<( const CEGLConfig& rhs ) const;
+    bool Match( const CEGLConfig& filter) const;
+    CEGLConfig& operator=( const CEGLConfig& rhs );
+    bool IsCompatible( const CEGLConfig& config, const EGLenum contextApi ) const;
+
+private:
+	EGLint              m_bufferSize;             /* EGL_BUFFER_SIZE */
+    CColorDescriptor    m_colorDescriptor;       
+    EGLBoolean          m_bindToTexRGB;           /* EGL_BIND_TO_TEXTURE_RGB*/
+    EGLBoolean          m_bindToTexRGBA;          /* EGL_BIND_TO_TEXTURE_RGBA */
+    EGLenum             m_configCaveat;           /* EGL_CONFIG_CAVEAT */
+    EGLint              m_configId;               /* EGL_CONFIG_ID */
+    EGLint              m_conformant;             /* EGL_CONFORMANT */
+    EGLint              m_depthSize;              /* EGL_DEPTH_SIZE */
+    EGLint              m_level;                  /* EGL_LEVEL */
+    EGLint              m_maxPbufferWidth;        /* EGL_MAX_PBUFFER_WIDTH */
+    EGLint              m_maxPbufferHeight;       /* EGL_MAX_PBUFFER_HEIGHT */
+    EGLint              m_maxPbufferPixels;       /* EGL_MAX_PBUFFER_PIXELS */
+    EGLint              m_maxSwapInterval;        /* EGL_MAX_SWAP_INTERVAL */
+    EGLint              m_minSwapInterval;        /* EGL_MIN_SWAP_INTERVAL */
+    EGLBoolean          m_nativeRenderable;       /* EGL_NATIVE_RENDERABLE */
+    EGLint              m_nativeVisualId;         /* EGL_NATIVE_VISUAL_ID */
+    EGLint              m_nativeVisualType;       /* EGL_NATIVE_VISUAL_TYPE */
+    EGLint              m_renderableType;         /* EGL_RENDERABLE_TYPE */
+    EGLint              m_sampleBuffers;          /* EGL_SAMPLE_BUFFERS */
+    EGLint              m_samples;                /* EGL_SAMPLES */
+    EGLint              m_stencilSize;            /* EGL_STENCIL_SIZE */
+
+    EGLint              m_surfaceType;            /* EGL_SURFACE_TYPE = 
+                                                     EGL_PBUFFER_BIT, 
+                                                     EGL_PIXMAP_BIT, 
+                                                     EGL_WINDOW_BIT, 
+                                                     EGL_VG_COLORSPACE_LINEAR_BIT, 
+                                                     EGL_VG_ALPHA_FORMAT_PRE_BIT,
+                                                     EGL_MULTISAMPLE_RESOLVE_BOX_BIT,
+                                                     EGL_SWAP_BEHAVIOR_PRESERVED_BIT */
+
+    CTransparentColor  m_transparentColor;
+};
+#endif //_EGLCONFIG_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLContext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,76 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLCONTEXT_H_
+#define _EGLCONTEXT_H_
+
+#include <EGL/egl.h>
+#include "eglInternal.h"
+#include <vector>
+
+class CEGLConfig;
+class CEGLThread;
+class CEGLDisplay;
+
+class CEGLContext : public RefCountingObject
+{
+public:
+	CEGLContext( EGLint processId, CEGLDisplay* display, CEGLConfig* config, EGLenum& clientApi, EGLint& clientVersion, void* clientContext );
+	~CEGLContext(void);
+
+public:
+    inline EGLint ProcessId() const { return m_processId; }
+    inline EGLenum ClientApi() const { return m_clientApi; }
+    inline EGLint ClientVersion() const { return m_clientVersion; }
+    inline void* ClientContext() const { return  m_clientContext; }
+    inline CEGLConfig* Config() const { return m_config; }
+    inline void SetThread( CEGLThread* thread ) { m_thread = thread; }
+    inline CEGLThread* Thread() const { return m_thread; }
+    inline CEGLDisplay* Display() const { return m_display; }
+
+    inline void SetNativeContext( EGLINativeContextType context ) { m_nativeContext = context; }
+    inline EGLINativeContextType NativeContext() const { return m_nativeContext; }
+    inline void SetNativeGLFucntions( struct EGLINativeGLFunctions* functions ) { m_nativeGLFunctions = functions; } 
+    inline struct EGLINativeGLFunctions* NativeGLFunctions() const { return m_nativeGLFunctions; }
+
+private:
+    EGLint                          m_processId;
+    CEGLThread*                     m_thread;
+    CEGLConfig*                     m_config;
+    EGLenum                         m_clientApi;
+    EGLint                          m_clientVersion;
+	void*                           m_clientContext;
+    std::vector<CEGLContext*>       m_sharedContexts;
+    CEGLDisplay*                    m_display;
+    EGLINativeContextType           m_nativeContext;
+    struct EGLINativeGLFunctions*   m_nativeGLFunctions;
+};
+
+#endif //_EGLCONTEXT_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLDisplay.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,82 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLDISPLAY_H_
+#define _EGLDISPLAY_H_
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include "eglInternal.h"
+#include "EGLSurface.h"
+
+
+//FORWARD DECLARATIONS
+class CEGLConfig;
+class CEGLContext;
+class CEGLImage;
+
+class CEGLDisplay : public RefCountingObject
+{
+public:
+	CEGLDisplay( EGLINativeDisplayType nativeType, EGLint processId );
+	~CEGLDisplay(void);
+
+public:
+    CEGLContext* AddContext( CEGLContext* context );
+    void RemoveContext( EGLContext context );
+    CEGLContext* GetContext( EGLContext context ) const;
+
+    CEGLSurface* AddSurface( CEGLSurface* surface );
+    void RemoveSurface( EGLSurface surfaceId );
+    CEGLSurface* GetSurface( EGLSurface surfaceId ) const;
+    CEGLSurface* GetSurfaceByNativeType( EGLINativeWindowType nativeType ) const;
+    CEGLSurface* FindSurfaceByClientSurface( void* clientSurface, EGLenum api, EGLint apiVersion  ) const;
+    CEGLSurface* FindSurfaceByClientBuffer( void* clientBuffer ) const;
+
+    inline EGLint ProcessId() const { return m_processId; }
+
+    EGLINativeDisplayType NativeType() const;
+
+    EGLBoolean Initialize();
+    bool TerminateDisplay();
+    inline EGLBoolean IsInitialized() const { return m_initialized; }
+    CEGLImage* AddEGLImage( CEGLImage* image );
+    void RemoveEGLImage( EGLImageKHR image );
+    CEGLImage* GetImage( EGLImageKHR image ) const;
+
+private:
+    EGLINativeDisplayType       m_nativeType;
+    EGLBoolean                  m_initialized;
+    std::vector<CEGLContext*>   m_contexts;
+    std::vector<CEGLSurface*>   m_surfaces;
+    std::vector<CEGLImage*>     m_images;
+    EGLint                      m_processId;
+};
+#endif //_EGLDISPLAY_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLExtension.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,55 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLEXTENSION_H_
+#define _EGLEXTENSION_H_
+
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+
+typedef void (*ProcPointer)(...);
+EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR( EGLDisplay dpy,
+												  EGLContext ctx,
+												  EGLenum target,
+												  EGLClientBuffer buffer,
+												  const EGLint *attrib_list );
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR( EGLDisplay dpy,
+												  EGLImageKHR image);
+
+class CEGLExtension
+    {
+    public:
+        CEGLExtension();
+        ~CEGLExtension(void);
+        static ProcPointer eglGetProcAddress(const char* aProcname);
+        
+    };
+#endif // _EGLEXTENSION_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLImage.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,76 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLIMAGE_H_
+#define _EGLIMAGE_H_
+
+#include <EGL/egl.h>
+#include <vector>
+#include "SurfaceDescriptor.h"
+
+// Forward declarations
+class CEGLState;
+
+class CEGLImage
+{
+public:
+    CEGLImage( EGLenum target, EGLClientBuffer buffer, SurfaceDescriptor desc, void* data );
+    virtual ~CEGLImage(void);
+    inline EGLenum Target() const { return m_target; }
+    EGLClientBuffer ClientBuffer() const { return m_buffer; }
+    inline EGLint DataStride() const { return m_SurfDesc.m_stride; }
+    inline EGLint Height() const { return m_SurfDesc.m_height; }
+    inline EGLint Width() const { return m_SurfDesc.m_width; }
+    inline EGLint DataSize() const { return (m_SurfDesc.m_height * m_SurfDesc.m_stride); }
+	inline const SurfaceDescriptor& SurfaceDesc() const { return m_SurfDesc; }
+    inline void* Data() const { return m_data; }
+    void AddSibling( EGLenum target, EGLClientBuffer buffer);
+    void UpdateData( CEGLState *state, void* data );
+    void DestroyAllSiblings();
+
+
+public:
+    struct EGLImageSibling
+        {
+        EGLenum target;
+        EGLClientBuffer buffer;
+        EGLImageSibling* next;
+        };
+    
+private:
+    
+    EGLenum m_target;
+    EGLClientBuffer m_buffer;
+    void* m_data;
+    SurfaceDescriptor m_SurfDesc;
+    EGLImageSibling* m_siblings;
+    
+};
+#endif // _EGLIMAGE_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLOs.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,80 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLOS_H_
+#define _EGLOS_H_
+
+#include "eglInternal.h"
+#include "EGLConfig.h"
+
+class CEGLDisplay;
+
+class CEGLOs
+{
+public:
+    static void InitializeLock( EGLI_LOCK *lock );
+    static void GetLock( EGLI_LOCK *lock );
+    static void ReleaseLock(EGLI_LOCK *lock );
+    static void DestroyLock( EGLI_LOCK *lock );
+
+    static void ConfigToNativePixelFormat( const CEGLConfig& config, EGLINativePixelFormatType* nativeFormat );
+    static EGLINativeContextType CreateNativeContext( const CEGLConfig& config, EGLINativeDisplayType display, EGLINativeContextType shareContext );
+    static EGLINativeContextType CurrentNativeContext();
+    static EGLINativeDisplayType CurrentNativeSurface();
+    static bool MakeNativeContextCurrent( struct EGLINativeGLFunctions* func, EGLINativeDisplayType draw, EGLINativeDisplayType read, EGLINativeContextType context );
+    static bool DestroyNativeContext( EGLINativeContextType context );
+    static bool InitializeNativeGLFunctions( struct EGLINativeGLFunctions* func, EGLINativeDisplayType display, EGLINativeContextType context );
+    static struct EGLINativePbufferContainer* CreateNativePbuffer( EGLINativeDisplayType display,
+            const CEGLConfig& config, EGLint width, EGLint height, EGLBoolean largestPbuffer, 
+            EGLint textureFormat, EGLint textureTarget );
+    static bool DestroyNativePbuffer( struct EGLINativePbufferContainer* container );
+
+    static EGLINativeDisplayType CreateDefaultDisplay();
+    static void DestroyDefaultDisplay( EGLINativeDisplayType display );
+    static EGLINativeWindowType CreateNativeWindow( int width, int height );
+    static void DestroyNativeWindow( EGLINativeWindowType wnd );
+
+    static bool IsValidNativeDisplay( EGLINativeDisplayType dsp );
+    static bool IsValidNativeWindow( EGLINativeWindowType wnd );
+    static bool GetNativeWindowSize( EGLINativeWindowType wnd, int& width, int& height );
+    static EGLIOsWindowContext* CreateOSWindowContext( EGLINativeWindowType wnd, const CEGLConfig& config );
+    static void DestroyOSWindowContext( EGLIOsWindowContext* context );
+    static void BlitToOSWindow( EGLenum api, CEGLDisplay* display, EGLIOsWindowContext* context, void* buf, int width, int height, int stride );
+
+    static EGLILibraryHandle LoadHostGL();
+    static void* GetGLProcAddress(EGLILibraryHandle& libraryHandle, const char* proc);
+    static bool FreeClientLibrary(EGLILibraryHandle& libraryHandle);
+
+    static IEGLtoVGInterface* LoadVGInterface( EGLILibraryHandle& libraryHandle );
+    static IEGLtoGLESInterface* LoadGLES1Interface( EGLILibraryHandle& libraryHandle );
+    static IEGLtoGLES2Interface* LoadGLES2Interface( EGLILibraryHandle& libraryHandle );
+};
+
+#endif //_EGLOS_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLPbufferSurface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,79 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLPBUFFERSURFACE_H_
+#define _EGLPBUFFERSURFACE_H_
+
+#include "EGLSurface.h"
+
+class CEGLPbufferSurface : public CEGLSurface
+{
+public:
+    CEGLPbufferSurface( EGLint colorSpace,
+                        EGLint alphaFormat,
+                        EGLint renderBuffer,
+                        CEGLConfig* config,
+                        EGLint largestPbuffer,
+                        EGLint textureFormat,
+						EGLint textureTarget,
+						EGLint mipmapTexture,
+                        EGLClientBuffer clientBuf = NULL );
+	~CEGLPbufferSurface(void);
+
+public:
+    inline EGLint IsLargestPbuffer() const { return m_largestPbuffer; }
+    inline EGLint TextureFormat() const { return m_textureFormat; }
+	inline EGLint TextureTarget() const { return m_textureTarget; }
+	inline EGLint MipmapTexture() const { return m_mipmapTexture; }
+    inline EGLClientBuffer ClientBuffer() const { return m_clientBuffer; }
+
+    void SetNativePbufferContainer( EGLINativePbufferContainer* container );
+    inline EGLINativePbufferType NativePbuffer() const { return (m_container ? m_container->pbuffer : NULL); }
+    inline EGLINativeContextType CopyContext() const { return (m_container ? m_container->copyContext : NULL); }
+    inline EGLINativeDisplayType NativeDisplay() const { return (m_container ? m_container->display : NULL); }
+    inline struct EGLINativeGLFunctions* NativeGLFunctions() const { if( m_container ) return &(m_container->functions); else return NULL; }
+
+    bool BindCopyContext();
+    bool ReleaseCopyContext();
+
+private:
+    CEGLPbufferSurface(void);
+
+private:
+    EGLint                              m_largestPbuffer;
+    EGLint                              m_textureFormat;
+	EGLint                              m_textureTarget;
+	EGLint								m_mipmapTexture;
+    EGLClientBuffer                     m_clientBuffer;
+    struct EGLINativePbufferContainer*  m_container;
+    EGLINativeContextType               m_tmpContext;
+    EGLINativeDisplayType               m_tmpDisplay;
+};
+#endif //_EGLPBUFFERSURFACE_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLProcess.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,62 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLPROCESS_H_
+#define _EGLPROCESS_H_
+
+#include <vector>
+#include "eglInternal.h"
+
+class CEGLThread;
+class CEGLContext;
+class CEGLSurface;
+
+class CEGLProcess
+{
+public:
+	CEGLProcess( EGLint processId );
+	~CEGLProcess(void);
+
+public:
+    inline EGLint Id() const { return m_id; }
+    CEGLThread* AddThread( EGLI_THREAD_ID threadId, bool setCurrent, EGLint supportedApis );
+    void RemoveThread( EGLI_THREAD_ID threadId );
+    CEGLThread* HasThread( EGLI_THREAD_ID threadId ) const;
+    inline EGLint ThreadCount() const { return m_threads.size(); }
+    void SetCurrentThread( EGLI_THREAD_ID threadId );
+    CEGLThread* CurrentThread() const;
+    CEGLSurface* FindBoundSurface( CEGLContext* context, bool readSurface ) const;
+
+private:
+    EGLint                      m_id;
+    std::vector<CEGLThread*>    m_threads;
+    CEGLThread*                 m_currentThread;
+};
+#endif //_EGLPROCESS_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLState.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,119 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLSTATE_H_
+#define _EGLSTATE_H_
+
+#include <EGL/egl.h>
+#include "eglInternal.h"
+#include <vector>
+
+class CEGLDisplay;
+class CEGLProcess;
+class CEGLConfig;
+class CEGLSurface;
+struct SurfaceDescriptor;
+
+class CEGLState : public RefCountingObject, public IVGtoEGLInterface, public IGLEStoEGLInterface
+{
+public:
+	CEGLState(void);
+	~CEGLState(void);
+
+public:
+    bool Initialize();
+    EGLint SupportedApis() const { return m_supportedApis; }
+    inline bool IsInitialized() const { return m_initialized; }
+    CEGLDisplay* AddDisplay( EGLINativeDisplayType nativeType, EGLint processId );
+    void RemoveDisplay( EGLDisplay displayId );
+    CEGLDisplay* GetDisplayByNativeType( EGLINativeDisplayType nativeType, EGLint processId ) const;
+    CEGLDisplay* GetDisplay( EGLDisplay displayId ) const;
+	EGLINativeDisplayType DefaultDisplay() const { return m_defaultDisplay; }
+
+    CEGLProcess* AddProcess( EGLint processId, bool setCurrent);
+    void RemoveProcess( EGLint processId );
+    CEGLProcess* GetProcess( EGLint processId ) const ;
+    inline CEGLProcess* GetCurrentProcess() const { return m_currentProcess; }
+    void SetCurrentProcessThread( EGLint processId, EGLI_THREAD_ID threadId );
+
+    inline EGLint ConfigCount() const { return m_configs.size(); }
+    void FillConfigs( EGLConfig* configs, EGLint size ) const;
+    CEGLConfig* FindConfigById( EGLint id ) const;
+    EGLint MatchConfigs( CEGLConfig* filter, EGLConfig* configs, EGLint maxCount ) const;
+    CEGLConfig* GetConfig( EGLConfig config ) const;
+    
+    inline IEGLtoVGInterface* VGInterface() const { return m_VGInterface; }
+	IEGLtoGLESInterface* GLESInterface( EGLint clientVersion ) const;
+
+	bool SyncSurface( EGLenum api, EGLint apiVersion, CEGLSurface* surface, CEGLSurface* currentGLESReadSurface );
+
+public: // from IVGtoEGLInterface and IGLEStoEGLInterface
+	void GetDescForImage( void* image, SurfaceDescriptor& ImageDesc );
+    void* GetDataForImage( void* image );
+	void RegisterImageTarget( void* image, EImageTarget target, void* buffer );
+	void UnregisterImageTarget( void* image, EImageTarget target, void* buffer );
+	void UpdateImageSiblings( void* image, EImageTarget target, void* buffer );
+
+public: // from IVGtoEGLInterface
+    void* GetVGContext();
+    bool IsImageInUse( void* image );
+    bool LockVGSurface( bool read, bool write );
+    bool UnlockVGSurface();
+
+public: // from IGLEStoEGLInterface
+	void* GetGLESContext();
+	void* GetHostProcAddress(const char* proc);
+    bool LockGLESSurface( bool read, bool write );
+    bool UnlockGLESSurface();
+	void ReleaseTexImage(void* surface, int name, int level);
+
+private:
+    bool CreateConfigs();
+    bool LockSurface( EGLenum api, bool read, bool write );
+    bool UnlockSurface( EGLenum api );
+
+private:
+    bool                        m_initialized;
+    std::vector<CEGLDisplay*>   m_displays;
+    std::vector<CEGLProcess*>   m_processes;
+    std::vector<CEGLConfig*>    m_configs;
+    CEGLProcess*                m_currentProcess;
+    EGLILibraryHandle           m_VGLib;
+    IEGLtoVGInterface*          m_VGInterface;
+    EGLILibraryHandle           m_GLES1Lib;
+    IEGLtoGLESInterface*        m_GLES1Interface;
+    EGLILibraryHandle           m_GLES2Lib;
+    IEGLtoGLES2Interface*       m_GLES2Interface;
+	EGLILibraryHandle			m_hostGL;
+    EGLint                      m_supportedApis;
+	EGLINativeDisplayType       m_defaultDisplay;
+    EGLINativeWindowType        m_dummyWindow;
+};
+#endif //_EGLSTATE_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLStructs.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,79 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLSTRUCTS_H_
+#define _EGLSTRUCTS_H_
+
+struct EGLIOsWindowContext
+    {
+    EGLINativeWindowType    window;
+	EGLINativeDisplayType   vgDisplay;
+    EGLINativeDisplayType   glesDisplay;
+	EGLINativePixmapType 	pixmap;
+    unsigned int*           osBuffer;
+    int                     width;
+    int                     height;
+    void*                   colorBuf;
+    };
+
+struct EGLINativeGLFunctions 
+    {
+#if defined(_WIN32)
+    // PBuffer
+    PFNWGLMAKECONTEXTCURRENTARBPROC wglMakeContextCurrentARB;
+    PFNWGLGETCURRENTREADDCARBPROC wglGetCurrentReadDCARB;
+    PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
+    PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB;
+    PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB;
+    PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB;
+    PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB;
+    PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB;
+#else // Linux
+    // \todo
+#endif
+    };
+
+struct EGLINativePbufferContainer
+    {
+    EGLINativeContextType   copyContext;
+    EGLINativePbufferType   pbuffer;
+    EGLINativeDisplayType   display;
+    EGLINativeGLFunctions   functions;
+    };
+
+struct EGLITextureBinding
+	{
+	EGLint		name;
+	EGLint		level;
+	EGLint		clientVersion;
+	EGLContext	context;
+	};
+
+#endif // _EGLSTRUCTS_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLSurface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,131 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLSURFACE_H_
+#define _EGLSURFACE_H_
+
+#include <EGL/egl.h>
+#include "eglInternal.h"
+#include "EGLStructs.h"
+#include "BufferContainer.h"
+#include "SurfaceDescriptor.h"
+
+class CEGLContext;
+class CEGLConfig;
+class CEGLThread;
+
+class CEGLSurface : public RefCountingObject
+{
+public:
+    enum SurfaceType
+        {
+        WINDOW_SURFACE = 1,
+        PBUFFER_SURFACE,
+        PIXMAP_SURFACE
+        };
+
+protected:
+    CEGLSurface( CEGLSurface::SurfaceType type, EGLint colorSpace, EGLint alphaFormat, EGLint renderBuffer, CEGLConfig* config );
+
+public:
+	virtual ~CEGLSurface(void);
+
+public:
+    void BindToContext( CEGLContext* context );
+    inline CEGLContext* BoundContext() const { return m_boundContext; }
+    inline void SetThread( CEGLThread* thread ) { m_thread = thread; }
+    inline CEGLThread* Thread() const { return m_thread; }
+    inline CEGLConfig* Config() const { return m_config; }
+    inline CEGLSurface::SurfaceType Type() const { return m_type; }
+    inline EGLint RenderBuffer() const { return m_renderBuffer; }
+    inline EGLint AlphaFormat() const { return m_alphaFormat; }
+    inline EGLint ColorSpace() const { return m_colorSpace; }
+    inline EGLint MipmapLevel() const { return m_mipmapLevel; }
+    inline EGLint MultisampleResolve() const { return m_multisampleResolve; };
+    inline EGLint SwapBehavior() const { return m_swapBehavior; }
+	inline EGLITextureBinding& TextureBinding() { return m_textureBinding; }
+    
+    EGLint Width() const { return m_width; }
+    EGLint Height() const { return m_height; }
+    void SetStride( EGLint stride ) { m_stride = stride; }
+    EGLint Stride() const { return m_stride; }
+    bool Resize( EGLint width, EGLint height );
+    void Size( int& width, int& height ) { width = m_width; height = m_height; }
+
+    BufferContainer* VGBuffers() { return &m_vgBuffers; }
+    BufferContainer* GLESBuffers() { return &m_glesBuffers; }
+    void* VGColorBuffer() const { return m_vgBuffers.m_colorBuffer; }
+    void* GLESColorBuffer() const { return m_glesBuffers.m_colorBuffer; }
+    void* VGClientSurface() const { return m_vgBuffers.m_clientSurface; }
+    void* GLESClientSurface() const { return m_glesBuffers.m_clientSurface; }
+
+    SurfaceDescriptor* Descriptor();
+
+    void SetAttribute( EGLint attrib, EGLint value );
+    EGLint Attribute( EGLint attrib ) const;
+
+    void Lock();
+    void Unlock();
+    bool IsLocked() const { return m_isLocked; }
+    void SetVGDirty( bool dirty ) { m_vgDirty = dirty; }
+    bool IsVGDirty() const { return m_vgDirty; }
+    void SetGLES1Dirty( bool dirty ) { m_gles1Dirty = dirty; }
+    bool IsGLES1Dirty() const { return m_gles1Dirty; }
+    void SetGLES2Dirty( bool dirty ) { m_gles2Dirty = dirty; }
+    bool IsGLES2Dirty() const { return m_gles2Dirty; }
+
+private:
+	SurfaceType     m_type;
+    EGLint          m_colorSpace;
+    EGLint          m_alphaFormat;
+    EGLint          m_renderBuffer;
+    CEGLConfig*     m_config; // not owned
+    CEGLContext*    m_boundContext; // not owned
+    CEGLThread*     m_thread; // not owned
+
+protected:
+    EGLint              m_width;
+    EGLint              m_height;
+    EGLint              m_stride;
+    BufferContainer     m_vgBuffers;
+    BufferContainer     m_glesBuffers;
+    SurfaceDescriptor   m_surfaceDescriptor;
+    EGLint              m_mipmapLevel;
+    EGLint              m_multisampleResolve;
+    EGLint              m_swapBehavior;
+	EGLITextureBinding	m_textureBinding;
+    EGLI_LOCK           m_lock;
+    bool                m_vgDirty;
+    bool                m_gles1Dirty;
+    bool                m_gles2Dirty;
+    bool                m_isLocked;
+};
+
+#endif //_EGLSURFACE_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLThread.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,78 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLTHREAD_H_
+#define _EGLTHREAD_H_
+
+#include <EGL/egl.h>
+#include "eglInternal.h"
+
+class CEGLSurface;
+class CEGLContext;
+
+class CEGLThread
+{
+public:
+	CEGLThread( EGLI_THREAD_ID threadId, EGLint supportedApis );
+	~CEGLThread(void);
+
+public:
+    inline EGLI_THREAD_ID Id() const { return m_id; }
+    void SetError( EGLint error ) { m_lastError = error; }
+    inline EGLint Error() const { return m_lastError; }
+
+    inline void SetApi( EGLint api ) { m_currentApi = api; }
+    inline EGLenum CurrentApi() const { return m_currentApi; }
+    bool IsSupportedApi( EGLenum api ) const;
+
+    CEGLContext* SwitchVGContext( CEGLContext* vgContext );
+    inline CEGLContext* CurrentVGContext() const { return m_currentVGContext; }
+    CEGLSurface* SwitchVGSurface( CEGLSurface* vgSurface );
+    inline CEGLSurface* CurrentVGSurface() const { return m_currentVGSurface; }
+
+	CEGLContext* SwitchGLESContext( CEGLContext* glesContext );
+	inline CEGLContext* CurrentGLESContext() const { return m_currentGLESContext; }
+	void SwitchGLESSurfaces( CEGLSurface* read, CEGLSurface* draw, CEGLSurface*& previousRead, CEGLSurface*& previousDraw );
+    void CurrentGLESSurfaces( CEGLSurface** read, CEGLSurface** draw ) const;
+
+private:
+    EGLI_THREAD_ID  m_id;
+	CEGLContext*    m_currentVGContext;
+    CEGLSurface*    m_currentVGSurface;
+    CEGLContext*    m_currentGLESContext;
+	CEGLSurface*    m_currentGLESReadSurface;
+    CEGLSurface*    m_currentGLESDrawSurface;
+    EGLenum         m_currentApi;
+    EGLint          m_lastError;
+    // Copy of CEGLState::m_supportedApis so we don't need to access state
+    // on thread specific API calls.
+    EGLint          m_supportedApis; 
+};
+#endif //_EGLTHREAD_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLUtils.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,76 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLUTILS_H_
+#define _EGLUTILS_H_
+
+#include <vector>
+#include <EGL/egl.h>
+#include "eglDefinitions.h"
+
+class RefCountingObject
+    {
+public:
+    RefCountingObject() : m_refCount( 0 ), m_terminated( false ) {}
+    virtual ~RefCountingObject() { EGLI_ASSERT( m_refCount == 0); }
+
+public:
+    virtual void AddRef() { m_refCount++; }
+    virtual int RefCount() const { return m_refCount; }
+    //returns true if object should be destroyed
+    virtual bool RemoveRef() { m_refCount--; EGLI_ASSERT(m_refCount >= 0); return (m_refCount == 0); }
+    virtual void Terminate() { m_terminated = true; }
+    virtual bool IsTerminated() const { return m_terminated; }
+
+protected:
+    int     m_refCount;
+    bool    m_terminated;
+    };
+
+template<class T> 
+extern void AddObject( std::vector<T*>& vector, T*& object );
+
+template<class T>
+extern T* FindObjectByPointer( const std::vector<T*>& vector, void* id, int* index );
+
+template<class T>
+extern  T* FindObjectById( const std::vector<T*>& vector, EGLint id, int* index );
+
+template<class T>
+extern  void DeleteObjectByPointer( std::vector<T*>& vector, void* item );
+
+template<class T>
+extern  void DeleteObjectById( std::vector<T*>& vector, EGLint id );
+
+template<class T>
+extern  void DestroyPointerVector( std::vector<T*>& vector );
+
+
+#endif //_EGLUTILS_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/EGLWindowSurface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,62 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLWINDOWSURFACE_H_
+#define _EGLWINDOWSURFACE_H_
+
+#include "EGLSurface.h"
+
+class CEGLWindowSurface :
+	public CEGLSurface
+{
+public:
+	CEGLWindowSurface( CEGLConfig* config, EGLint colorSpace, EGLint alphaFormat, EGLint renderBuffer, EGLIOsWindowContext* osContext );
+	~CEGLWindowSurface(void);
+
+public:
+    inline EGLINativeWindowType NativeType() const { EGLI_ASSERT( m_osContext != NULL); if( m_osContext ) return m_osContext->window; else return NULL; }
+    inline void SetWindowBuffers( void* buffer0, void* buffer1 ) { m_buffer0 = buffer0; m_buffer1 = buffer1; }
+    void* CurrentBuffer();
+    void SetSwapInterval( EGLint interval );
+    inline EGLint SwapInterval() const { return m_swapInterval; }
+    void SetOsContext( EGLIOsWindowContext* osContext );
+    inline EGLIOsWindowContext* OsContext() const { return m_osContext; }
+
+private:
+    CEGLWindowSurface();
+
+private:
+    void*               m_buffer0;
+    void*               m_buffer1;
+    void*               m_currentBuffer;
+    EGLint              m_swapInterval;
+    EGLIOsWindowContext* m_osContext;
+};
+#endif //_EGLWINDOWSURFACE_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/TransparentColor.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,62 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _TRANSPARENTCOLOR_H_
+#define _TRANSPARENTCOLOR_H_
+
+#include "eglInternal.h"
+
+class CTransparentColor
+{
+public:
+    CTransparentColor(void) :
+        m_transparentType( EGL_NONE ),
+        m_redValue( 0 ),
+        m_greenValue( 0 ),
+        m_blueValue( 0 )
+        {
+        }
+	~CTransparentColor(void);
+    CTransparentColor( EGLint type, EGLint redValue, EGLint greenValue, EGLint blueValue );
+
+public:
+    void SetAttribute( EGLint attribute, EGLint value );
+    inline EGLint Type() const { return m_transparentType; }
+    inline EGLint RedValue() const { return m_redValue; }
+    inline EGLint GreenValue() const { return m_greenValue; }
+    inline EGLint BlueValue() const { return m_blueValue; }
+
+private:
+    EGLint  m_transparentType;
+    EGLint  m_redValue;
+    EGLint  m_greenValue;
+    EGLint  m_blueValue;
+};
+#endif // _TRANSPARENTCOLOR_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/eglDefinitions.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,114 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLDEFINITIONS_H_
+#define _EGLDEFINITIONS_H_
+
+#if defined(_WIN32)
+#include <windows.h>
+#include <GL\gl.h>
+#include <GL\wglext.h>
+#else // Linux
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+#include <GL/glx.h>
+#include <GL/glxext.h>
+#include <assert.h>
+#endif
+
+#define EGL_VERSION_MAJOR 1
+#define EGL_VERSION_MINOR 4
+
+#define EGLI_NEW new(std::nothrow)
+
+#define EGLI_NO_RET
+
+// \note PlatSim specific hack
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    typedef int     EGLINativeDisplayType;
+    typedef void*   EGLINativePixmapType;
+    typedef void*   EGLINativeWindowType;
+#else
+    typedef EGLNativeDisplayType    EGLINativeDisplayType;
+    typedef EGLNativePixmapType     EGLINativePixmapType;
+    typedef EGLNativeWindowType     EGLINativeWindowType;
+#endif
+
+#if !defined(EGLI_MIN)
+#   define EGLI_MIN(a,b) ((a)<(b)?(a):(b))
+#endif
+
+#if !defined(EGLI_MAX)
+#   define EGLI_MAX(a,b) ((a)>(b)?(a):(b))
+#endif
+
+#if defined(_WIN32)
+#   if defined(_DEBUG)
+#       define EGLI_ASSERT assert
+#   else
+#      define EGLI_ASSERT
+#   endif //_DEBUG
+#else
+#   if !defined(NDEBUG)
+#       define EGLI_ASSERT assert
+#   else
+#       define EGLI_ASSERT
+#   endif
+#endif
+
+#if defined(_WIN32)
+
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+#   define EGLI_THREAD_ID EGLint
+#else
+#   define EGLI_THREAD_ID DWORD
+#endif // EGLI_USE_PLATSIM_EXTENSIONS
+    typedef CRITICAL_SECTION        EGLI_LOCK;
+    typedef HGLRC                   EGLINativeContextType;
+    typedef HPBUFFERARB             EGLINativePbufferType;
+    typedef PIXELFORMATDESCRIPTOR   EGLINativePixelFormatType;
+    typedef HMODULE                 EGLILibraryHandle;
+#else // Linux
+
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+#   define EGLI_THREAD_ID EGLint
+#else
+#   define EGLI_THREAD_ID pid_t
+#endif // EGLI_USE_PLATSIM_EXTENSIONS
+    typedef pthread_mutex_t EGLI_LOCK;
+    typedef GLXContext      EGLINativeContextType;
+    typedef GLXPbuffer      EGLINativePbufferType;
+    typedef XVisualInfo     EGLINativePixelFormatType;
+    typedef void*           EGLILibraryHandle;
+
+#endif
+
+
+#endif // _EGLDEFINITIONS_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/inc/eglInternal.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,67 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLINTERNAL_H_
+#define _EGLINTERNAL_H_
+
+#include <EGL/egl.h>
+#include <vector>
+#include "VGInterface.h"
+#include "GLESInterface.h"
+#include "GLES2Interface.h"
+#include "eglDefinitions.h"
+#include "EGLStructs.h"
+#include "EGLUtils.h"
+
+class CEGLState;
+class CEGLThread;
+extern CEGLState* getState();
+extern CEGLThread* getThread();
+extern void setEGLError( EGLint error );
+
+// Global EGL lock
+extern EGLI_LOCK g_eglLock;  
+
+#define EGLI_ENTER_RET(ret)\
+    CEGLOs::GetLock( &g_eglLock );\
+    CEGLState* state = getState();\
+    if( !state )\
+        {\
+        CEGLOs::ReleaseLock( &g_eglLock );\
+        return ret;\
+        }\
+    CEGLProcess* process = state->GetCurrentProcess(); \
+    (void)process;
+
+#define EGLI_LEAVE_RET(ret, error)\
+    setEGLError( error );\
+    CEGLOs::ReleaseLock( &g_eglLock );\
+    return ret
+#endif // _EGLINTERNAL_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/ColorDescriptor.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,312 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "ColorDescriptor.h"
+#include "eglInternal.h"
+
+CColorDescriptor::CColorDescriptor(EGLint red, EGLint green, EGLint blue, 
+                             EGLint luminance, bool nonlinear, EGLint alpha, bool premultiplied,
+                             EGLint alphaMask, EGLint bpp) :
+    m_bpp( bpp ),
+    m_redSize( red ),
+    m_greenSize( green ),
+    m_blueSize( blue ),
+    m_luminanceSize( luminance ),
+    m_alphaSize( alpha ),
+    m_alphaMaskSize( alphaMask )
+    {
+    unsigned int f  = 0;
+
+    if (nonlinear)
+        f |= NONLINEAR;
+   
+    if (premultiplied)
+        f |= PREMULTIPLIED;
+   
+    if ( luminance )
+        f |= LUMINANCE;
+
+    m_format = (ColorFormat)f;
+
+    }
+
+void CColorDescriptor::Set( int red, int green, int blue, int luminance,
+                           bool nonlinear, int alpha, bool premultiplied, int alphaMask, int bpp)
+    {
+    m_bpp = bpp;
+    m_redSize = red;
+    m_greenSize = green;
+    m_blueSize = blue;
+    m_luminanceSize = luminance;
+    m_alphaSize = alpha;
+    m_alphaMaskSize = alphaMask;
+
+    unsigned int f  = 0;
+    if (nonlinear)
+        f |= NONLINEAR;
+   
+    if (premultiplied)
+        f |= PREMULTIPLIED;
+   
+    if ( luminance )
+        f |= LUMINANCE;
+
+    m_format = (ColorFormat)f;
+    }
+
+void CColorDescriptor::SetAttribute( EGLint attribute, EGLint value )
+    {
+    switch( attribute )
+        {
+        case EGL_BUFFER_SIZE:
+            {
+            m_bpp = value;
+            break;
+            }
+        case EGL_RED_SIZE:
+            {
+            m_redSize = value;
+            break;
+            }
+        case EGL_GREEN_SIZE:
+            {
+            m_greenSize = value;
+            break;
+            }
+        case EGL_BLUE_SIZE:
+            {
+            m_blueSize = value;
+            break;
+            }
+        case EGL_LUMINANCE_SIZE:
+            {
+            m_luminanceSize = value;
+            break;
+            }
+        case EGL_ALPHA_SIZE:
+            {
+            m_alphaSize = value;
+            break;
+            }
+        case EGL_ALPHA_MASK_SIZE:
+            {
+            m_alphaMaskSize = value;
+            break;
+            }
+        case EGL_COLOR_BUFFER_TYPE:
+            {
+            SetColorBufferType(value);
+            break;
+            }
+        case EGL_SURFACE_TYPE:
+            SetSurfaceType(value);
+            break;
+        default:
+            EGLI_ASSERT( false );
+        }
+    }
+
+EGLint CColorDescriptor::GetAttribute( EGLint attribute ) const
+    {
+    switch( attribute )
+        {
+        case EGL_RED_SIZE:
+            {
+            return m_redSize;
+            }
+        case EGL_GREEN_SIZE:
+            {
+            return m_greenSize;
+            }
+        case EGL_BLUE_SIZE:
+            {
+            return m_blueSize;
+            }
+        case EGL_LUMINANCE_SIZE:
+            {
+            return m_luminanceSize;
+            }
+        case EGL_ALPHA_SIZE:
+            {
+            return m_alphaSize;
+            }
+        case EGL_ALPHA_MASK_SIZE:
+            {
+            return m_alphaMaskSize;
+            }
+        case EGL_COLOR_BUFFER_TYPE:
+            {
+            if( isLuminance() )
+                return EGL_LUMINANCE_BUFFER;
+            else
+                return EGL_RGB_BUFFER;
+            }
+        case EGL_SURFACE_TYPE:
+            return GetSurfaceType();
+            break;
+        default:
+            EGLI_ASSERT( false );
+            return 0;
+        }
+    }
+
+/**
+ * \brief Set alpha type and color space using bits
+ * \note  Be careful not to mix with enumerations. Use the two-parameter version
+ *        to set from enums.
+ */
+void CColorDescriptor::SetSurfaceType(EGLint surfaceType)
+{
+    unsigned int f = m_format;
+
+    f &= ~PREMULTIPLIED;
+
+    if (surfaceType & EGL_VG_ALPHA_FORMAT_PRE_BIT)
+        f |= PREMULTIPLIED;     
+
+    f &= ~NONLINEAR;
+    if (!(surfaceType & EGL_VG_COLORSPACE_LINEAR_BIT))
+        f |= NONLINEAR;
+
+    m_format = (ColorFormat)f;    
+}
+
+/**
+ * \brief Set alpha type and color space using enumerations.
+ */
+void CColorDescriptor::SetSurfaceType(EGLint colorSpace, EGLint alphaType)
+{
+    unsigned int f = m_format;
+
+    f &= ~PREMULTIPLIED;
+
+    if (alphaType == EGL_VG_ALPHA_FORMAT_PRE)
+        f |= PREMULTIPLIED;     
+
+    f &= ~NONLINEAR;
+    if (colorSpace == EGL_VG_COLORSPACE_sRGB)
+        f |= NONLINEAR;
+
+    m_format = (ColorFormat)f;    
+}
+
+
+EGLint CColorDescriptor::GetSurfaceType() const
+{
+    EGLint ret = 0;
+
+    if (!(m_format & NONLINEAR))
+        ret |= EGL_VG_COLORSPACE_LINEAR_BIT;
+
+    if (m_format & PREMULTIPLIED)
+        ret |= EGL_VG_ALPHA_FORMAT_PRE_BIT;
+
+    return ret;
+}
+
+void CColorDescriptor::SetColorBufferType( EGLint colorBufferType )
+{
+    unsigned int f = m_format & (~LUMINANCE);
+
+    switch(colorBufferType)
+    {
+    case EGL_LUMINANCE_BUFFER:
+        f |= LUMINANCE;
+        break;
+    default:
+        EGLI_ASSERT(colorBufferType == EGL_RGB_BUFFER);
+        break;
+    }
+
+    m_format = (ColorFormat)f;
+}
+
+CColorDescriptor& CColorDescriptor::operator=( const CColorDescriptor& rhs )
+    {
+    if( this == &rhs ) return *this;
+    m_bpp = rhs.m_bpp;
+    m_redSize = rhs.m_redSize;
+    m_greenSize = rhs.m_greenSize;
+    m_blueSize = rhs.m_blueSize;
+    m_luminanceSize = rhs.m_luminanceSize;
+    m_alphaSize = rhs.m_alphaSize;
+    m_alphaMaskSize = rhs.m_alphaMaskSize;
+    m_format = rhs.m_format;
+    return *this;
+    }
+
+bool CColorDescriptor::operator==( const CColorDescriptor& rhs ) const
+    {
+    if( this == &rhs ) return true;
+    
+    if( isNonlinear() != rhs.isNonlinear() ) return false;
+    if( isPremultiplied() != rhs.isPremultiplied() ) return false;
+
+    if( m_alphaSize != rhs.m_alphaSize ) return false;
+    if( m_alphaMaskSize != rhs.m_alphaMaskSize ) return false;
+    
+    if( isLuminance() && rhs.isLuminance()  )
+        {
+        if( m_luminanceSize != rhs.m_luminanceSize ) return false;        
+        }
+    else
+        {
+        if( m_bpp != rhs.m_bpp ) return false;
+        if( m_redSize != rhs.m_redSize ) return false;
+        if( m_greenSize != rhs.m_greenSize ) return false;
+        if( m_blueSize != rhs.m_blueSize ) return false;
+        }
+    return true;
+    }
+
+bool CColorDescriptor::operator!=( const CColorDescriptor& rhs ) const
+    {
+    return !(operator==(rhs));
+    }
+
+bool CColorDescriptor::MatchBitDepth( const CColorDescriptor& desc ) const
+    {
+    if( m_alphaSize != desc.m_alphaSize ) return false;
+    if( isPremultiplied() != desc.isPremultiplied() ) return false;
+    if( isLuminance() )
+        {
+        if( !desc.isLuminance() || (m_luminanceSize != desc.m_luminanceSize ) ) return false;
+        }
+    else
+        {
+        if( m_redSize != desc.m_redSize ) return false;
+        if( m_greenSize != desc.m_greenSize ) return false;
+        if( m_blueSize != desc.m_blueSize ) return false;
+        if( isNonlinear() != desc.isNonlinear() ) return false;
+        }
+    return true;
+    }
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLConfig.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,929 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLConfig.h"
+#include "ColorDescriptor.h"
+#include "TransparentColor.h"
+
+const int KPbufferHeight = 16384;       
+const int KPbufferWidth = 16384;
+const int KPbufferPixels = KPbufferHeight * KPbufferWidth;
+
+CEGLConfig::CEGLConfig(void) :
+    m_nativeVisualId( NULL )
+    {
+    }
+
+CEGLConfig::CEGLConfig( CColorDescriptor&   colorDescriptor,        
+                        EGLBoolean          bindToTexRGB,           /* EGL_BIND_TO_TEXTURE_RGB*/
+                        EGLBoolean          bindToTexRGBA,          /* EGL_BIND_TO_TEXTURE_RGBA */
+                        EGLenum             configCaveat,           /* EGL_CONFIG_CAVEAT */
+                        EGLint              configId,               /* EGL_CONFIG_ID */
+                        EGLint              conformant,             /* EGL_CONFORMANT */
+                        EGLint              depthSize,              /* EGL_DEPTH_SIZE */
+                        EGLint              level,                  /* EGL_LEVEL */
+                        EGLint              maxSwapInterval,        /* EGL_MAX_SWAP_INTERVAL */
+                        EGLint              minSwapInterval,        /* EGL_MIN_SWAP_INTERVAL */
+                        EGLBoolean          nativeRenderable,       /* EGL_NATIVE_RENDERABLE */
+                        EGLint              nativeVisualType,       /* EGL_NATIVE_VIDUAL_TYPE */
+                        EGLint              renderableType,         /* EGL_RENDERABLE_TYPE */
+                        EGLint              sampleBuffers,          /* EGL_SAMPLE_BUFFERS */
+                        EGLint              samples,                /* EGL_SAMPLES */
+                        EGLint              stencilSize,            /* EGL_STENCIL_SIZE */
+                        EGLint              surfaceType,
+                        CTransparentColor*  transparentColor) :
+    m_bindToTexRGB( bindToTexRGB ),
+    m_bindToTexRGBA( bindToTexRGBA ),
+    m_configCaveat( configCaveat ),
+    m_configId( configId ),
+    m_conformant( conformant ),
+    m_depthSize( depthSize ),
+    m_level( level ),
+    m_maxPbufferWidth( KPbufferWidth ),
+    m_maxPbufferHeight( KPbufferHeight ),
+    m_maxPbufferPixels( KPbufferPixels ),
+    m_maxSwapInterval( maxSwapInterval ),
+    m_minSwapInterval( minSwapInterval ),
+    m_nativeRenderable( nativeRenderable ),
+    m_nativeVisualId( NULL ),
+    m_nativeVisualType( nativeVisualType ),
+    m_renderableType( renderableType ),
+    m_sampleBuffers( samples > 1 ? 1 : 0 ),
+    m_samples( samples ),
+    m_stencilSize( stencilSize ),
+    m_surfaceType( surfaceType )
+    {
+    m_colorDescriptor = colorDescriptor;
+    if( m_colorDescriptor.isLuminance() )
+        {
+        m_bufferSize = m_colorDescriptor.LuminanceSize() + m_colorDescriptor.AlphaSize();
+        }
+    else
+        {
+        m_bufferSize = m_colorDescriptor.RedSize() +
+            m_colorDescriptor.GreenSize() +
+            m_colorDescriptor.BlueSize() +
+            m_colorDescriptor.AlphaSize();
+        }
+    if( transparentColor )
+        {
+        m_transparentColor = *transparentColor;
+        }
+    }
+    
+CEGLConfig::~CEGLConfig(void)
+    {
+    }
+
+EGLint CEGLConfig::SetUpConfig( EGLint red, EGLint green, EGLint blue, 
+                                EGLint luminance, EGLint alpha, 
+                                EGLint alphaMask, EGLint samples, EGLint bpp, EGLint id )
+    {
+    int ret = EGL_SUCCESS;
+    int rgb = red + green + blue;
+    if( luminance && rgb )
+        {
+        return EGL_BAD_PARAMETER;
+        }
+    m_colorDescriptor.Set( red, green, blue, luminance, false, alpha, true, alphaMask, bpp );
+    //m_colorDescriptor = EGLI_NEW CColorDescriptor( red, green, blue, luminance, false, alpha, true, alphaMask, bpp );
+
+    m_configId = id;
+    
+    if( m_colorDescriptor.isLuminance() )
+        {
+        m_bufferSize = luminance + alpha;
+        }
+    else
+        {
+        m_bufferSize = red + green + blue + alpha;  
+        }
+
+    if( rgb )
+        {
+        m_bindToTexRGB = EGL_TRUE;
+        m_bindToTexRGBA = EGL_TRUE;
+        }
+    else
+        {
+        m_bindToTexRGB = EGL_FALSE;
+        m_bindToTexRGBA = EGL_FALSE;
+        }
+    
+    /*
+    The EGL_CONFIG_CAVEAT attribute may be set to one of the following values:
+    EGL_NONE, EGL_SLOW_CONFIG or EGL_NON_CONFORMANT_CONFIG. If the
+    attribute is set to EGL_NONE then the configuration has no caveats; if it is set to
+    EGL_SLOW_CONFIG then rendering to a surface with this configuration may run at
+    reduced performance (for example, the hardware may not support the color buffer
+    depths described by the configuration); if it is set to EGL_NON_CONFORMANT_-
+    CONFIG then rendering to a surface with this configuration will not pass the required
+    OpenGL ES conformance tests (note that EGL_NON_CONFORMANT_CONFIG
+    is obsolete, and the same information can be obtained from the EGL_CONFORMANT
+    attribute on a per-client-API basis, not just for OpenGL ES ).
+    */
+    m_configCaveat = EGL_NONE;
+
+    /*
+    Same as EGL_RENDERABLE_TYPE:
+    EGL_OPENGL_ES_BIT,
+    EGL_OPENVG_BIT,
+    EGL_OPENGL_ES2_BIT,
+    EGL_OPENGL_BIT
+    */
+    m_conformant = EGL_OPENGL_ES2_BIT;//0;
+    m_renderableType = EGL_OPENVG_BIT | EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT;
+    
+    /*
+    The Depth Buffer
+    The depth buffer is shared by OpenGL and OpenGL ES . It contains fragment
+    depth (Z) information generated during rasterization. EGL_DEPTH_SIZE indicates
+    the depth of this buffer in bits.
+    */
+    m_depthSize = 0;
+    
+    /*
+     EGL_LEVEL is the framebuffer overlay or underlay level in which an
+     EGLSurface created with eglCreateWindowSurface will be placed. Level zero
+     indicates the default layer. The behavior of windows placed in overlay and under-
+     lay levels depends on the underlying native window system.
+    */
+    m_level = 0;
+    
+    /*
+    EGL_MAX_PBUFFER_WIDTH and EGL_MAX_PBUFFER_HEIGHT indicate the
+    maximum width and height that can be passed into eglCreatePbufferSurface,
+    and EGL_MAX_PBUFFER_PIXELS indicates the maximum number of pixels (width
+    times height) for a pbuffer surface. Note that an implementation may return a value
+    for EGL_MAX_PBUFFER_PIXELS that is less than the maximum width times the
+    maximum height. The value for EGL_MAX_PBUFFER_PIXELS is static and assumes
+    that no other pbuffers or native resources are contending for the framebuffer
+    memory. Thus it may not be possible to allocate a pbuffer of the size given by
+    EGL_MAX_PBUFFER_PIXELS.
+    */
+    m_maxPbufferHeight = KPbufferHeight;       
+    m_maxPbufferWidth = KPbufferWidth;
+    m_maxPbufferPixels = KPbufferPixels;   
+    
+    /*
+    EGL_MAX_SWAP_INTERVAL is the maximum value that can be passed to
+    eglSwapInterval, and indicates the number of swap intervals that will elapse before
+    a buffer swap takes place after calling eglSwapBuffers. Larger values will be
+    silently clamped to this value.
+    */
+    m_maxSwapInterval = 1;
+    
+    /*
+    EGL_MIN_SWAP_INTERVAL is the minimum value that can be passed to
+    eglSwapInterval, and indicates the number of swap intervals that will elapse before
+    a buffer swap takes place after calling eglSwapBuffers. Smaller values will
+    be silently clamped to this value.
+    */
+    m_minSwapInterval = 1;
+    
+    /*
+    EGL_NATIVE_RENDERABLE is an EGLBoolean indicating whether the native
+    window system can be used to render into a surface created with the EGLConfig.
+    */
+    m_nativeRenderable = EGL_FALSE;
+    
+    /*
+    If an EGLConfig supports windows then it may have an associated native visual.
+    EGL_NATIVE_VISUAL_ID specifies an identifier for this visual, and EGL_-
+    NATIVE_VISUAL_TYPE specifies its type. If an EGLConfig does not support
+    windows, or if there is no associated native visual type, then querying EGL_-
+    NATIVE_VISUAL_ID will return 0 and querying EGL_NATIVE_VISUAL_TYPE
+    will return EGL_NONE.
+    The interpretation of the native visual identifier and type is platform-dependent.
+    For example, if the native window system is X, then the identifier will be the XID
+    of an X Visual.
+    */
+    m_nativeVisualId = 0;
+    
+    m_nativeVisualType = EGL_NONE;    
+    
+    /*
+    EGL_SAMPLE_BUFFERS indicates the number of multisample buffers, which
+    must be zero or one. EGL_SAMPLES gives the number of samples per pixel; if
+    EGL_SAMPLE_BUFFERS is zero, then EGL_SAMPLES will also be zero. If EGL_-
+    SAMPLE_BUFFERS is one, then the number of color, depth, and stencil bits for each
+    sample in the multisample buffer are as specified by the EGL_*_SIZE attributes.
+    There are no single-sample depth or stencil buffers for a multisample
+    EGLConfig; the only depth and stencil buffers are those in the multisample
+    buffer. If the color samples in the multisample buffer store fewer bits than are
+    stored in the color buffers, this fact will not be reported accurately. Presumably a
+    compression scheme is being employed, and is expected to maintain an aggregate
+    resolution equal to that of the color buffers.
+    */
+    m_samples = samples; 
+    m_sampleBuffers = samples > 1 ? 1 : 0;   
+    
+    /*
+    The stencil buffer is shared by OpenGL and OpenGL ES . It contains fragment
+    stencil information generated during rasterization. EGL_STENCIL_SIZE indicates
+    the depth of this buffer in bits.
+    */
+    m_stencilSize = 0;
+    
+    /*
+    EGL_SURFACE_TYPE is a mask indicating capabilities of surfaces that can be
+    created with the corresponding EGLConfig (the config is said to support these
+    surface types).
+
+    EGL_SURFACE_TYPE is a mask indicating capabilities of surfaces that can be
+    created with the corresponding EGLConfig (the config is said to support these
+    surface types). The valid bit settings are shown in Table 3.2.
+    For example, an EGLConfig for which the value of the EGL_SURFACE_TYPE
+    attribute is
+    EGL_WINDOW_BIT j EGL_PIXMAP_BIT j EGL_PBUFFER_BIT
+    can be used to create any type of EGL surface, while an EGLConfig for which this
+    attribute value is EGL_WINDOW_BIT cannot be used to create a pbuffer or pixmap.
+    If EGL_MULTISAMPLE_RESOLVE_BOX_BIT is set in EGL_SURFACE_TYPE,
+    then the EGL_MULTISAMPLE_RESOLVE attribute of a surface can be specified as a
+    box filter with eglSurfaceAttrib (see section 3.5.6).
+    If EGL_SWAP_BEHAVIOR_PRESERVED_BIT is set in EGL_SURFACE_TYPE,
+    then the EGL_SWAP_BEHAVIOR attribute of a surface can be specified to preserve
+    color buffer contents using eglSurfaceAttrib (see section 3.5.6).
+    If EGL_VG_COLORSPACE_LINEAR_BIT is set in EGL_SURFACE_TYPE, then
+    the EGL_VG_COLORSPACE attribute may be set to EGL_VG_COLORSPACE_-
+    LINEAR when creating a window, pixmap, or pbuffer surface (see section 3.5).
+    If EGL_VG_ALPHA_FORMAT_PRE_BIT is set in EGL_SURFACE_TYPE, then the
+    EGL_VG_ALPHA_FORMAT attribute may be set to EGL_VG_ALPHA_FORMAT_PRE
+    when creating a window, pixmap, or pbuffer surface (see section 3.5).
+    
+    */
+    m_surfaceType = EGL_WINDOW_BIT |
+                    EGL_PBUFFER_BIT | 
+                    //EGL_VG_COLORSPACE_LINEAR_BIT |
+                    EGL_VG_ALPHA_FORMAT_PRE_BIT |
+                    EGL_SWAP_BEHAVIOR_PRESERVED_BIT;
+    m_colorDescriptor.SetSurfaceType( m_surfaceType );
+    m_surfaceType |= EGL_VG_COLORSPACE_LINEAR_BIT;
+    
+    /*
+    If EGL_TRANSPARENT_TYPE is EGL_NONE, then the values for EGL_-
+    TRANSPARENT_RED_VALUE, EGL_TRANSPARENT_GREEN_VALUE, and EGL_-
+    TRANSPARENT_BLUE_VALUE are undefined. Otherwise, they are interpreted as
+    integer framebuffer values between 0 and the maximum framebuffer value for the
+    component. For example, EGL_TRANSPARENT_RED_VALUE will range between 0
+    and 2EGL_RED_SIZE 1.
+    */
+
+    return ret;
+    }
+
+EGLBoolean CEGLConfig::SetAttribute( EGLint attribute, EGLint value )
+    {
+    EGLBoolean ret = EGL_FALSE;
+    switch( attribute )
+        {
+        case EGL_BUFFER_SIZE:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                m_bufferSize = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+
+        case EGL_BLUE_SIZE:
+        case EGL_GREEN_SIZE:
+        case EGL_RED_SIZE:
+        case EGL_LUMINANCE_SIZE:
+        case EGL_ALPHA_SIZE:
+        case EGL_ALPHA_MASK_SIZE:
+            {
+            if( (value == EGL_DONT_CARE ||
+                 value >= 0) )
+                {
+                m_colorDescriptor.SetAttribute( attribute, value );
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+
+        case EGL_COLOR_BUFFER_TYPE:
+            {
+            if( (value == EGL_DONT_CARE ||
+                 value == EGL_RGB_BUFFER ||
+                 value == EGL_LUMINANCE_BUFFER) )
+                {
+                m_colorDescriptor.SetAttribute( attribute, value );
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+
+        case EGL_DEPTH_SIZE:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                m_depthSize = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_STENCIL_SIZE:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                m_stencilSize = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_CONFIG_CAVEAT:
+            {
+            if( value == EGL_DONT_CARE ||
+                value == EGL_NONE ||
+                value == EGL_SLOW_CONFIG ||
+                value == EGL_NON_CONFORMANT_CONFIG )
+                {
+                m_configCaveat = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_CONFIG_ID:
+            {
+            if( value == EGL_DONT_CARE ||
+                value > 0 )
+                {
+                m_configId = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_LEVEL:
+            {
+            // \todo validate value
+            m_level = value;
+            ret = EGL_TRUE;
+            break;
+            }
+
+        case EGL_NATIVE_VISUAL_ID:
+        case EGL_MAX_PBUFFER_HEIGHT:
+        case EGL_MAX_PBUFFER_PIXELS:
+        case EGL_MAX_PBUFFER_WIDTH:
+            {
+            // \todo?
+            break;
+            }
+
+        case EGL_NATIVE_RENDERABLE:
+            {
+            if( value == EGL_DONT_CARE ||
+                value == EGL_TRUE ||
+                value == EGL_FALSE )
+                {
+                m_nativeRenderable = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+
+        case EGL_NATIVE_VISUAL_TYPE:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                m_nativeVisualType = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_SAMPLES:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                m_samples = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_SAMPLE_BUFFERS:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                m_sampleBuffers = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_SURFACE_TYPE:
+            {
+            if( (value == EGL_DONT_CARE ||
+                !(value & ~(EGL_WINDOW_BIT |
+                            EGL_PIXMAP_BIT |
+                            EGL_PBUFFER_BIT |
+                            EGL_MULTISAMPLE_RESOLVE_BOX_BIT |
+                            EGL_SWAP_BEHAVIOR_PRESERVED_BIT |
+                            EGL_VG_COLORSPACE_LINEAR_BIT |
+                            EGL_VG_ALPHA_FORMAT_PRE_BIT))) )
+                {
+                m_colorDescriptor.SetSurfaceType(value);
+                m_surfaceType = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_TRANSPARENT_TYPE:
+            {
+            if( (value == EGL_DONT_CARE ||
+                 value == EGL_NONE ||
+                 value == EGL_TRANSPARENT_RGB) )
+                {
+                m_transparentColor.SetAttribute( attribute, value );
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_TRANSPARENT_BLUE_VALUE:
+        case EGL_TRANSPARENT_GREEN_VALUE:
+        case EGL_TRANSPARENT_RED_VALUE:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                // \todo If EGL_TRANSPARENT_TYPE is EGL_NONE, then the values for EGL_-
+                //       TRANSPARENT_RED_VALUE, EGL_TRANSPARENT_GREEN_VALUE, and EGL_-
+                //       TRANSPARENT_BLUE_VALUE are undefined. Otherwise, they are interpreted as
+                //       integer framebuffer values between 0 and the maximum framebuffer value for the
+                //       component. For example, EGL_TRANSPARENT_RED_VALUE will range between 0
+                //       and 2^EGL_RED_SIZE - 1.
+                m_transparentColor.SetAttribute( attribute, value );
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_BIND_TO_TEXTURE_RGB:
+            {
+            if( value == EGL_DONT_CARE ||
+                value == EGL_TRUE ||
+                value == EGL_FALSE )
+                {
+                m_bindToTexRGB = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_BIND_TO_TEXTURE_RGBA:
+            {
+            if( value == EGL_DONT_CARE ||
+                value == EGL_TRUE ||
+                value == EGL_FALSE )
+                {
+                m_bindToTexRGBA = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_MIN_SWAP_INTERVAL:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                m_minSwapInterval = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_MAX_SWAP_INTERVAL:
+            {
+            if( value == EGL_DONT_CARE ||
+                value >= 0 )
+                {
+                m_maxSwapInterval = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_RENDERABLE_TYPE:
+            {
+            if( value == EGL_DONT_CARE ||
+                !(value & ~(EGL_OPENGL_BIT |
+                            EGL_OPENGL_ES_BIT |
+                            EGL_OPENGL_ES2_BIT |
+                            EGL_OPENVG_BIT)) )
+                {
+                m_renderableType = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+        case EGL_CONFORMANT:
+            {
+            if( value == EGL_DONT_CARE ||
+                !(value & ~(EGL_OPENGL_BIT |
+                            EGL_OPENGL_ES_BIT |
+                            EGL_OPENGL_ES2_BIT |
+                            EGL_OPENVG_BIT)) )
+                {
+                m_conformant = value;
+                ret = EGL_TRUE;
+                }
+            break;
+            }
+
+        default:
+            {
+            // Unknown attribute
+            EGLI_ASSERT( false );
+            }
+        }
+    return ret;
+    }
+	
+EGLint CEGLConfig::GetAttribute( EGLint attribute ) const
+    {
+    EGLint ret = 0;
+    switch( attribute )
+        {
+        case EGL_BUFFER_SIZE:
+            {
+            ret = m_bufferSize;
+            break;
+            }
+        case EGL_BLUE_SIZE:
+        case EGL_GREEN_SIZE:
+        case EGL_RED_SIZE:
+        case EGL_LUMINANCE_SIZE:
+        case EGL_ALPHA_SIZE:
+        case EGL_ALPHA_MASK_SIZE:
+        case EGL_COLOR_BUFFER_TYPE:
+            {
+            ret = m_colorDescriptor.GetAttribute( attribute );
+            break;
+            }
+
+        case EGL_DEPTH_SIZE:
+            {
+            ret = m_depthSize;
+            break;
+            }
+        case EGL_STENCIL_SIZE:
+            {
+            ret = m_stencilSize;
+            break;
+            }
+        case EGL_CONFIG_CAVEAT:
+            {
+            ret = m_configCaveat;
+            break;
+            }
+        case EGL_CONFIG_ID:
+            {
+            ret = m_configId;
+            break;
+            }
+        case EGL_LEVEL:
+            {
+            ret = m_level;
+            break;
+            }
+
+        case EGL_NATIVE_VISUAL_ID:
+            {
+            ret = m_nativeVisualId;
+            break;
+            }
+        case EGL_MAX_PBUFFER_HEIGHT:
+            {
+            ret = m_maxPbufferHeight;
+            break;
+            }
+        case EGL_MAX_PBUFFER_PIXELS:
+            {
+            ret = m_maxPbufferPixels;
+            break;
+            }
+        case EGL_MAX_PBUFFER_WIDTH:
+            {
+            ret = m_maxPbufferWidth;
+            break;
+            }
+        case EGL_NATIVE_RENDERABLE:
+            {
+            ret = m_nativeRenderable;
+            break;
+            }
+        case EGL_NATIVE_VISUAL_TYPE:
+            {
+            ret = m_nativeVisualType;
+            break;
+            }
+        case EGL_SAMPLES:
+            {
+            ret = m_samples;
+            break;
+            }
+        case EGL_SAMPLE_BUFFERS:
+            {
+            ret = m_sampleBuffers;
+            break;
+            }
+        case EGL_SURFACE_TYPE:
+            {
+            ret = m_surfaceType;
+            break;
+            }
+        case EGL_TRANSPARENT_TYPE:
+            {
+            ret = m_transparentColor.Type();
+            break;
+            }
+        case EGL_TRANSPARENT_BLUE_VALUE:
+            {
+            ret = m_transparentColor.BlueValue();
+            break;
+            }
+        case EGL_TRANSPARENT_GREEN_VALUE:
+            {
+            ret = m_transparentColor.GreenValue();
+            break;
+            }
+        case EGL_TRANSPARENT_RED_VALUE:
+            {
+            ret = m_transparentColor.RedValue();
+            break;
+            }
+        case EGL_BIND_TO_TEXTURE_RGB:
+            {
+            ret = m_bindToTexRGB;
+            break;
+            }
+        case EGL_BIND_TO_TEXTURE_RGBA:
+            {
+            ret = m_bindToTexRGBA;
+            break;
+            }
+        case EGL_MIN_SWAP_INTERVAL:
+            {
+            ret = m_minSwapInterval;
+            break;
+            }
+        case EGL_MAX_SWAP_INTERVAL:
+            {
+            ret = m_maxSwapInterval;
+            break;
+            }
+        case EGL_RENDERABLE_TYPE:
+            {
+            ret = m_renderableType;
+            break;
+            }
+        case EGL_CONFORMANT:
+            {
+            ret = m_conformant;
+            break;
+            }
+
+        default:
+            {
+            ret = EGL_BAD_ATTRIBUTE;
+            }
+        }
+    return ret;
+    }
+
+bool CEGLConfig::operator<( const CEGLConfig& rhs ) const
+    {
+    if( this == &rhs ) return false;
+
+    return !(operator>(rhs));
+    }
+
+bool CEGLConfig::operator>( const CEGLConfig& rhs ) const
+    {
+    if( this == &rhs ) return false;
+    
+    // 1 Special: by EGL_CONFIG_CAVEAT where the precedence is EGL_NONE,
+    //   EGL_SLOW_CONFIG, EGL_NON_CONFORMANT_CONFIG.    
+    if( m_configCaveat != rhs.m_configCaveat )
+        {
+        // \note depends on EGL_NON_CONFORMANT_CONFIG > EGL_SLOW_CONFIG       
+        if( rhs.m_configCaveat < m_configCaveat )
+            return false;
+        if( m_configCaveat > rhs.m_configCaveat )
+            return true;
+        }
+
+    // 2 Special: by EGL_COLOR_BUFFER_TYPE where the precedence is EGL_-
+    //   RGB_BUFFER, EGL_LUMINANCE_BUFFER.
+    if( !(m_colorDescriptor.isLuminance()) && rhs.m_colorDescriptor.isLuminance() )
+        return true;
+    if( m_colorDescriptor.isLuminance() && !(rhs.m_colorDescriptor.isLuminance()) )
+        return false;
+
+    // 3 Special: by larger total number of color bits (for an RGB color buffer,
+    //   this is the sum of EGL_RED_SIZE, EGL_GREEN_SIZE, EGL_BLUE_SIZE,
+    //   and EGL_ALPHA_SIZE; for a luminance color buffer, the sum of EGL_-
+    //   LUMINANCE_SIZE and EGL_ALPHA_SIZE)
+    
+    // \todo If the requested number of bits in attrib list for a particular color
+    //       component is 0 or EGL_DONT_CARE, then the number of bits for that component
+    //       is not considered.
+    
+    if( m_bufferSize > rhs.m_bufferSize )
+        return true;
+    if( rhs.m_bufferSize > m_bufferSize )
+        return false;
+    
+    if( m_sampleBuffers > rhs.m_sampleBuffers )
+        return true;
+    if( rhs.m_sampleBuffers > m_sampleBuffers )
+        return false;
+    
+    if( m_samples > rhs.m_samples )
+        return true;
+    if( rhs.m_samples > m_samples )
+        return false;
+
+    if( m_depthSize > rhs.m_depthSize )
+        return true;
+    if( rhs.m_depthSize > m_depthSize )
+        return false;
+
+    if( m_stencilSize > rhs.m_stencilSize )
+        return true;
+    if( rhs.m_stencilSize > m_stencilSize )
+        return false;
+
+    if( m_colorDescriptor.AlphaMaskSize() > rhs.m_colorDescriptor.AlphaMaskSize() )
+        return true;
+    if( rhs.m_colorDescriptor.AlphaMaskSize() > m_colorDescriptor.AlphaMaskSize() )
+        return false;
+
+    // \todo Special: by EGL_NATIVE_VISUAL_TYPE (the actual sort order is
+    //       implementation-defined, depending on the meaning of native visual types).
+
+    if( m_configId > rhs.m_configId )
+        return true;
+    if( rhs.m_configId > m_configId )
+        return false;
+
+    // Shouldn't reach this point.
+    EGLI_ASSERT( false );
+    return false;
+    }
+
+bool CEGLConfig::Match( const CEGLConfig& filter ) const
+    {
+    if( this == &filter ) return true;
+
+    if( m_bufferSize < filter.m_bufferSize ) return false;
+
+    if( m_colorDescriptor.RedSize() < filter.m_colorDescriptor.RedSize() ||
+        m_colorDescriptor.GreenSize() < filter.m_colorDescriptor.GreenSize() ||
+        m_colorDescriptor.BlueSize() < filter.m_colorDescriptor.BlueSize() ||
+        m_colorDescriptor.AlphaSize() < filter.m_colorDescriptor.AlphaSize() ) return false;
+    
+    if( m_colorDescriptor.AlphaMaskSize() < filter.m_colorDescriptor.AlphaMaskSize() ) return false;
+    
+    if( filter.m_bindToTexRGB != EGL_DONT_CARE && (m_bindToTexRGB != filter.m_bindToTexRGB) ) return false;
+    
+    if( filter.m_bindToTexRGBA != EGL_DONT_CARE && (m_bindToTexRGBA != filter.m_bindToTexRGBA) ) return false;
+    
+    if( filter.m_colorDescriptor.Format() != EGL_DONT_CARE )
+        {
+        EGLint thisBufType = m_colorDescriptor.isLuminance() ? EGL_LUMINANCE_BUFFER : EGL_RGB_BUFFER;
+        EGLint filterBufType = filter.m_colorDescriptor.isLuminance() ? EGL_LUMINANCE_BUFFER : EGL_RGB_BUFFER;
+        if( thisBufType != filterBufType ) return false;
+        }
+
+    if( filter.m_configCaveat != EGL_DONT_CARE && (m_configCaveat != filter.m_configCaveat) ) return false;
+
+    if( m_configId == filter.m_configId ) return false;
+    
+    if( (filter.m_conformant & m_conformant) != filter.m_conformant ) return false;
+
+    if( m_depthSize < filter.m_depthSize ) return false;
+    
+    if( m_level != filter.m_level ) return false;
+    
+    if( filter.m_maxSwapInterval != EGL_DONT_CARE && (m_maxSwapInterval != filter.m_maxSwapInterval) ) return false;
+
+    if( filter.m_minSwapInterval != EGL_DONT_CARE && (m_minSwapInterval != filter.m_minSwapInterval) ) return false;
+
+    if( filter.m_nativeRenderable != EGL_DONT_CARE && (m_nativeRenderable != filter.m_nativeRenderable) ) return false;
+
+    if( filter.m_nativeVisualType != EGL_DONT_CARE && (m_nativeVisualType != filter.m_nativeVisualType) ) return false;
+
+    if( (filter.m_renderableType & m_renderableType) != filter.m_renderableType ) return false;
+
+    if( m_sampleBuffers < filter.m_sampleBuffers ) return false;
+
+    if( m_samples < filter.m_samples ) return false;
+
+    if( m_stencilSize < filter.m_stencilSize ) return false;
+
+    if( (filter.m_surfaceType & m_surfaceType) != filter.m_surfaceType ) return false;
+    
+    if( filter.m_transparentColor.Type() != m_transparentColor.Type() ) return false;
+    
+    return true;
+    }
+
+CEGLConfig& CEGLConfig::operator=( const CEGLConfig& rhs )
+    {
+    if( this == &rhs ) return *this;
+
+    m_bufferSize        = rhs.m_bufferSize;
+    m_colorDescriptor   = rhs.m_colorDescriptor;
+    m_bindToTexRGB      = rhs.m_bindToTexRGB;
+    m_bindToTexRGBA     = rhs.m_bindToTexRGBA;
+    m_configCaveat      = rhs.m_configCaveat;
+    m_configId          = rhs.m_configId;
+    m_conformant        = rhs.m_conformant;
+    m_depthSize         = rhs.m_depthSize;
+    m_level             = rhs.m_level;
+    m_maxPbufferWidth   = rhs.m_maxPbufferWidth;
+    m_maxPbufferHeight  = rhs.m_maxPbufferHeight;
+    m_maxPbufferPixels  = rhs.m_maxPbufferPixels;
+    m_maxSwapInterval   = rhs.m_maxSwapInterval;
+    m_minSwapInterval   = rhs.m_minSwapInterval;
+    m_nativeRenderable  = rhs.m_nativeRenderable;
+    m_nativeVisualId    = rhs.m_nativeVisualId;
+    m_nativeVisualType  = rhs.m_nativeVisualType;
+    m_renderableType    = rhs.m_renderableType;
+    m_sampleBuffers     = rhs.m_sampleBuffers;
+    m_samples           = rhs.m_samples;
+    m_stencilSize       = rhs.m_stencilSize;
+    m_surfaceType       = rhs.m_surfaceType;    
+    m_transparentColor  = rhs.m_transparentColor;
+    return *this;
+    }
+
+bool CEGLConfig::IsCompatible( const CEGLConfig& config, const EGLenum contextApi ) const
+    {
+    if( m_colorDescriptor.isLuminance() != config.m_colorDescriptor.isLuminance() )
+        return false;
+
+    if( m_colorDescriptor.isLuminance() &&
+        (m_colorDescriptor.m_luminanceSize != config.m_colorDescriptor.m_luminanceSize ||
+         m_colorDescriptor.m_alphaSize != config.m_colorDescriptor.m_alphaSize) )
+        return false;
+    else if ( m_colorDescriptor.m_redSize != config.m_colorDescriptor.m_redSize ||
+              m_colorDescriptor.m_greenSize != config.m_colorDescriptor.m_greenSize ||
+              m_colorDescriptor.m_blueSize != config.m_colorDescriptor.m_blueSize ||
+              m_colorDescriptor.m_alphaSize != config.m_colorDescriptor.m_alphaSize )
+        return false;
+
+    if( m_samples != config.m_samples )
+        return false;
+    
+    switch( contextApi )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( m_colorDescriptor.m_alphaMaskSize != config.m_colorDescriptor.m_alphaMaskSize )
+                return false;
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            if( m_stencilSize != config.m_stencilSize )
+                return false;
+            if( m_depthSize != config.m_depthSize )
+                return false;
+
+            break;
+            }
+        }
+    return true;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLContext.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,56 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+
+#include "EGLContext.h"
+#include "EGLOs.h"
+
+CEGLContext::CEGLContext( EGLint processId, CEGLDisplay* display,
+                         CEGLConfig* config, EGLenum& clientApi,
+                         EGLint& clientVersion, void* clientContext ) :
+    m_processId( processId ),
+    m_thread( NULL ),
+    m_config( config ),
+    m_clientApi( clientApi ),
+    m_clientVersion( clientVersion ),
+    m_clientContext( clientContext ),
+    m_display( display ),
+    m_nativeContext( NULL ),
+    m_nativeGLFunctions(NULL)
+    {
+    }
+
+CEGLContext::~CEGLContext(void)
+    {
+    // objects not owned
+    m_sharedContexts.clear();
+    if( m_nativeContext ) CEGLOs::DestroyNativeContext( m_nativeContext );
+    delete m_nativeGLFunctions;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLDisplay.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,250 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLDisplay.h"
+#include "EGLContext.h"
+#include "EGLConfig.h"
+#include "EGLSurface.h"
+#include "EGLImage.h"
+#include "EGLWindowSurface.h"
+#include "EGLPbufferSurface.h"
+#include "ColorDescriptor.h"
+#include "EGLOs.h"
+#include "EGLUtils.h"
+#include "EGLState.h"
+#include "EGLProcess.h"
+#include "EGLThread.h"
+
+
+CEGLDisplay::CEGLDisplay( EGLINativeDisplayType nativeType, EGLint processId ) :
+    m_nativeType( nativeType ),
+    m_initialized( EGL_FALSE ),
+    m_processId( processId )
+    {
+    }
+
+CEGLDisplay::~CEGLDisplay(void)
+    {
+    DestroyPointerVector<CEGLContext>( m_contexts );
+    DestroyPointerVector<CEGLSurface>( m_surfaces );
+    DestroyPointerVector<CEGLImage>( m_images );
+    }
+
+CEGLContext* CEGLDisplay::AddContext( CEGLContext* context )
+    {
+    if( context )
+        {
+        AddObject<CEGLContext>( m_contexts, context );
+        }
+    return context;
+    }
+
+void CEGLDisplay::RemoveContext( EGLContext context )
+    {
+    DeleteObjectByPointer<CEGLContext>( m_contexts, context );
+    }
+
+CEGLContext* CEGLDisplay::GetContext( EGLContext context ) const
+    {
+    CEGLContext* ret = FindObjectByPointer<CEGLContext>( m_contexts, context, NULL );
+    if( ret && ret->IsTerminated() ) ret = NULL;
+    return ret;
+    }
+
+CEGLSurface* CEGLDisplay::AddSurface( CEGLSurface* surface )
+    {
+    if( surface )
+        {
+        AddObject<CEGLSurface>( m_surfaces, surface );
+        }
+    return surface;
+    }
+
+void CEGLDisplay::RemoveSurface( EGLSurface surfaceId )
+    {
+    DeleteObjectByPointer<CEGLSurface>( m_surfaces, surfaceId );
+    }
+
+CEGLSurface* CEGLDisplay::GetSurface( EGLSurface surfaceId ) const
+    {
+    CEGLSurface* ret = FindObjectByPointer<CEGLSurface>( m_surfaces, surfaceId, NULL );
+    if( ret && ret->IsTerminated() ) ret = NULL;
+    return ret;
+    }
+
+CEGLSurface* CEGLDisplay::GetSurfaceByNativeType( EGLINativeWindowType nativeType ) const
+    {
+    CEGLSurface* ret = NULL;
+    std::vector<CEGLSurface*>::const_iterator iter = m_surfaces.begin();
+    while( iter != m_surfaces.end() )
+        {
+        if( (*iter)->Type() == CEGLSurface::WINDOW_SURFACE )
+            {
+            if( ((CEGLWindowSurface*)(*iter))->NativeType() == nativeType  && !((*iter)->IsTerminated()) )
+                {
+                ret = (*iter);
+                break;
+                }
+            }
+        iter++;
+        }
+    return ret;
+    }
+
+CEGLSurface* CEGLDisplay::FindSurfaceByClientSurface( void* clientSurface, EGLenum api, EGLint apiVersion ) const
+    {
+    CEGLSurface* ret = NULL;
+    std::vector<CEGLSurface*>::const_iterator iter = m_surfaces.begin();
+    while( iter != m_surfaces.end() )
+        {
+        switch( api )
+            {
+            case EGL_OPENVG_API:
+                {
+                if( (*iter)->VGClientSurface() == clientSurface )
+                    {
+                    ret = (*iter);
+                    break;
+                    }
+                }
+            case EGL_OPENGL_ES_API:
+                {
+                if( (*iter)->GLESClientSurface() == clientSurface )
+                    {
+                    ret = (*iter);
+                    break;
+                    }
+                }
+            }
+        iter++;
+        }
+    return ret;
+    }
+
+CEGLSurface* CEGLDisplay::FindSurfaceByClientBuffer( void* clientBuffer ) const
+    {
+    CEGLSurface* ret = NULL;
+    std::vector<CEGLSurface*>::const_iterator iter = m_surfaces.begin();
+    while( iter != m_surfaces.end() )
+        {
+        if( (*iter)->Type() == CEGLSurface::PBUFFER_SURFACE &&
+            ((CEGLPbufferSurface*)(*iter))->ClientBuffer() == clientBuffer )
+            {
+            ret = (*iter);
+            break;
+            }
+        iter++;
+        }
+    return ret;
+    }
+
+EGLINativeDisplayType CEGLDisplay::NativeType() const
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    return m_nativeType; 
+#else
+    return m_nativeType; 
+#endif
+    }
+
+EGLBoolean CEGLDisplay::Initialize()
+    {
+    m_initialized = EGL_TRUE;
+    return m_initialized;
+    }
+	
+bool CEGLDisplay::TerminateDisplay()
+    {
+    //m_initialized = EGL_FALSE;
+    bool ret = true;
+    std::vector<CEGLSurface*> boundSurfaces;
+    std::vector<CEGLSurface*>::iterator sIter = m_surfaces.begin();
+    CEGLState* state = getState();
+    CEGLThread* thread = state->GetCurrentProcess()->CurrentThread();
+    while( sIter != m_surfaces.end() )
+        {
+        if( (*sIter)->IsTerminated() || !((*sIter)->RemoveRef()) )
+            {
+            (*sIter)->Terminate();
+            boundSurfaces.push_back( (*sIter) );
+            sIter = m_surfaces.erase( sIter );
+            }
+        else
+            {
+            sIter++;
+            }
+        }
+    DestroyPointerVector<CEGLSurface>(m_surfaces);
+    m_surfaces.swap( boundSurfaces );
+    boundSurfaces.clear();
+
+    std::vector<CEGLContext*> boundContexts;
+    std::vector<CEGLContext*>::iterator cIter = m_contexts.begin();
+    while( cIter != m_contexts.end() )
+        {
+        if( (*cIter)->IsTerminated() || !((*cIter)->RemoveRef()) )
+            {
+            (*cIter)->Terminate();
+            boundContexts.push_back( (*cIter) );
+            cIter = m_contexts.erase( cIter );
+            }
+        else
+            {
+            cIter++;
+            }
+        }
+    DestroyPointerVector<CEGLContext>(m_contexts);
+    m_contexts.swap( boundContexts );
+    ret = (m_contexts.size() <= 0 && m_surfaces.size() <= 0);
+    Terminate();
+    return ret;
+    //TODO
+    //EGLI_ASSERT( false );
+    }
+
+CEGLImage* CEGLDisplay::AddEGLImage( CEGLImage* image )
+    {
+    if( image )
+        {
+        AddObject<CEGLImage>( m_images, image );
+        }
+    return image;
+    }
+
+void CEGLDisplay::RemoveEGLImage( EGLImageKHR image )
+    {
+    DeleteObjectByPointer<CEGLImage>( m_images, image );
+    }
+
+CEGLImage* CEGLDisplay::GetImage( EGLImageKHR image ) const
+    {
+    CEGLImage* ret = FindObjectByPointer<CEGLImage>( m_images, image, NULL );
+    return ret;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLExtension.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,360 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLExtension.h"
+#include "EGLState.h"
+#include "EGLImage.h"
+#include "EGLContext.h"
+#include "EGLDisplay.h"
+#include "eglInternal.h"
+#include "EGLProcess.h"
+#include "EGLThread.h"
+#include "EGLOs.h"
+#include "ImageTarget.h"
+
+#include <string.h>
+
+typedef struct
+	{
+	const char*      extnName;		// procedure or extension name
+	ProcPointer      procAddr;      // address
+	} TExtnInfo;
+
+static const TExtnInfo eglProcedures[] =
+    { // list of EGL extension name strings, followed by any EGLI_NEW function names
+        {"eglCreateImageKHR", (ProcPointer)eglCreateImageKHR},
+        {"eglDestroyImageKHR", (ProcPointer)eglDestroyImageKHR}
+    };
+
+const EGLint KEglProcCount = sizeof(eglProcedures) / sizeof(TExtnInfo); 
+
+CEGLExtension::CEGLExtension()
+    {
+    }
+
+CEGLExtension::~CEGLExtension(void)
+    {
+    }
+
+ProcPointer CEGLExtension::eglGetProcAddress(const char* aProcname)
+    {
+    EGLint nameLength =  strlen(aProcname);
+	if ((nameLength > 3) && !strncmp(aProcname, "egl", 3))
+		{ // EGL extensions - exhaustive search 
+		for (EGLint idx = 0; idx < KEglProcCount; idx++)
+			{
+			if ( strcmp( aProcname, eglProcedures[idx].extnName ) == 0 )
+				return eglProcedures[idx].procAddr;
+			}
+		}	
+	return NULL;
+    }
+
+static EImageTarget mapImageTarget( EGLenum target )
+	{
+	switch(target)
+		{
+		case EGL_GL_TEXTURE_2D_KHR:
+			return IMAGE_TARGET_TEXTURE_2D;
+		case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_X;
+        case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_X;
+        case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Y;
+        case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Y;
+        case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Z;
+        case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Z;
+		case EGL_GL_RENDERBUFFER_KHR:
+			return IMAGE_TARGET_RENDERBUFFER;
+		default:
+			EGLI_ASSERT(false);
+		}
+
+	// Not reached.
+	return (EImageTarget)-1;
+	}
+
+EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR( EGLDisplay dpy,
+												  EGLContext ctx,
+												  EGLenum target,
+												  EGLClientBuffer buffer,
+												  const EGLint *attrib_list )
+    {
+    EGLI_ENTER_RET( EGL_NO_IMAGE_KHR );
+
+    CEGLImage *image = NULL;
+    CEGLDisplay *display = NULL;
+    CEGLContext *context = NULL;
+
+    display = state->GetDisplay( dpy );
+    // Check display
+    //<dpy> must be a valid EGLDisplay
+    if( !display )
+       {                   
+       EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_DISPLAY );
+       }
+
+    context = display->GetContext( ctx ); 
+    // Check context
+    //<ctx> must be a valid OpenVG API context on that display
+    if( !context )
+       {                    
+       EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_CONTEXT );
+       }
+    
+    // Display and context ok, continue...
+    switch( target )
+        {
+        case EGL_NATIVE_PIXMAP_KHR:
+            {
+            // Not supported
+            // 1) set error code to EGL_BAD_PARAMETER
+            // 2) release lock
+            // 3) return no image
+            EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_PARAMETER );
+            break;
+            }
+        case EGL_VG_PARENT_IMAGE_KHR:
+            {            
+            // Context must be client context and api must be openVG
+            if( context->ClientContext() && EGL_OPENVG_API == context->ClientApi() )                    
+                {                        
+                EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_CONTEXT );
+                }
+
+            //<buffer>
+            //must be a handle of a VGImage object valid in the specified context, cast
+            //into the type EGLClientBuffer
+            //Furthermore, the specified VGImage
+            //<buffer> must not be a child image
+            if ( !state->VGInterface()->IsRootImage( buffer ) )
+                {
+                EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_ACCESS );
+                }
+            
+            // TODO:
+            /*
+            1) We also need to check that VGImage is not bound 
+            to a Pbuffer surface
+            
+            2) VGimage has not been already used to create EGLImage. 
+            
+            3) VGImage itself is not created from EGLImage.            
+            */
+            //state->VGInterface()-
+            // 1)
+            if( EGL_PBUFFER_BIT == context->Config()->GetAttribute( EGL_SURFACE_TYPE ) )
+                {
+                // If VGImage is bound to a Pbuffer no EGLImage
+                EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_ACCESS );
+                }
+
+            // Descriptor for pixeldata data values
+            SurfaceDescriptor desc; 
+            // data is actual pixeldata
+            void* data = NULL;
+
+            //Any values
+            //specified in <attr_list> are ignored.
+     
+            // GetImageData will allocate memory for data
+            // data must be deleted in CEGLImage destructor
+            state->VGInterface()->GetImageData( buffer, desc, data );
+            if ( !data )
+                {
+                EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_ACCESS );
+                }
+
+            // Create CEGLImage.
+            image = EGLI_NEW CEGLImage( target, buffer, desc, data );
+            
+            // If EGLImage creation fail then return error code.
+            if( !image )
+                {
+                EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_ALLOC );
+                }
+            // Add refcount to VGImage
+            state->VGInterface()->AddRef( buffer );
+            // Add image in array
+            image = display->AddEGLImage( image );
+            break;
+            }   
+
+        case EGL_GL_TEXTURE_2D_KHR:
+		case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
+        case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
+        case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
+        case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
+        case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
+        case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
+            {
+            // From RFP document
+            // EGL_KHR_gl_image (not required for OpenGL ES 1.1) [R12]
+            /*<ctx> must be a valid OpenGL ES API context on that display.*/
+			if( context->ClientContext() && (EGL_OPENGL_ES_API != context->ClientApi() || 2 != context->ClientVersion()) )
+                {                        
+                EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_CONTEXT );
+                }
+
+            
+            // From spec.
+            /*KHR_gl_texture_2D_image requires the presence of an OpenGL ES
+            implementation (1.0 or later and/or 2.0 or later).*/
+            
+            /*Accepted as an attribute in the <attr_list> parameter of
+            eglCreateImageKHR: EGL_GL_TEXTURE_LEVEL_KHR 0x30BC*/
+
+            //EGL_GL_TEXTURE_LEVEL_KHR  
+
+            /*If <target> is EGL_GL_TEXTURE_2D_KHR, 
+            <buffer> must be the name of a nonzero, EGL_GL_TEXTURE_2D target texture object, 
+            cast into the type EGLClientBuffer.  
+
+            <attr_list> should specify the mipmap level
+            which will be used as the EGLImage source (EGL_GL_TEXTURE_LEVEL_KHR); the
+            specified mipmap level must be part of <buffer>.  If not specified, the
+            default value listed in Table bbb will be used, instead.  Additional
+            values specified in <attr_list> are ignored.  The texture must be complete
+            unless the mipmap level to be used is 0, the texture has mipmap level 0
+            specified, and no other mipmap levels are specified. */
+            
+            SurfaceDescriptor surfDesc;
+            EGLint textureLevel = 0;
+            EGLint dataSize;
+
+            if( attrib_list && attrib_list[0] != EGL_NONE )
+	            {
+                  for(int i=0; attrib_list[i] != EGL_NONE ; i+=2)
+                    {
+                    if( attrib_list[i] == EGL_GL_TEXTURE_LEVEL_KHR )
+                        {
+                        textureLevel = attrib_list[i+1];
+                        }
+                    }
+	            }
+
+			EImageTarget textureTarget = mapImageTarget(target);
+
+			IEGLtoGLES2Interface* iFace = (IEGLtoGLES2Interface*)state->GLESInterface(2);
+			EStatus status = iFace->GetTextureInfo( context->ClientContext(), textureTarget, buffer, textureLevel, surfDesc );
+			if ( status != DGLES2_SUCCESS )
+				{
+				switch( status )
+					{
+					case DGLES2_BAD_PARAMETER:
+					case DGLES2_BAD_MATCH:
+						EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_PARAMETER );
+						break;
+
+					default:
+						EGLI_ASSERT(false);
+					}
+                EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_ALLOC );
+                }
+			dataSize = surfDesc.m_stride * surfDesc.m_height;
+			unsigned char* data = new unsigned char [ dataSize ];
+
+            iFace->GetTextureData( context->ClientContext(), textureTarget, buffer, textureLevel, data );
+            
+            // Create CEGLImage.
+            image = EGLI_NEW CEGLImage( target, buffer, surfDesc, data );
+            
+            // If EGLImage creation fail then return error code.
+            if( !image )
+                {
+                EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_ALLOC );
+                }
+            // Add image in array
+            // That array is in display side.
+            image = display->AddEGLImage( image );
+            break;
+            }
+        case EGL_GL_TEXTURE_3D_KHR:
+            {
+            /*<ctx> must be a valid OpenGL ES API context on that display.*/
+			//EGL_BAD_PARAMETER 
+            // NOT SUPPORTED 
+            EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_PARAMETER );
+            }
+        case EGL_GL_RENDERBUFFER_KHR:
+            {
+            //EGL_BAD_PARAMETER 
+            // NOT SUPPORTED 
+            EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_PARAMETER );
+            }
+
+        default:
+            {
+            //EGL_BAD_PARAMETER 
+            EGLI_LEAVE_RET( EGL_NO_IMAGE_KHR, EGL_BAD_PARAMETER );
+            }
+        }
+    EGLI_LEAVE_RET( image, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR( EGLDisplay dpy,
+												  EGLImageKHR image)
+    {
+    // TODO:
+    /* Check display
+       Delete image from display array*/ 
+    EGLI_ENTER_RET( EGL_FALSE );
+
+    CEGLDisplay *display = NULL;
+    CEGLImage *tempImage = NULL;
+
+    display = state->GetDisplay( dpy );
+    // Check display
+    //<dpy> must be a valid EGLDisplay
+    if( !display )
+       {                   
+       EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_DISPLAY );
+       }
+
+    tempImage = display->GetImage( image );
+    if( !tempImage )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_PARAMETER );
+        }
+
+    // Display and image are both ok...
+    // Let siblings know that image is destroyed...
+    // Delete mother of image...
+    // Remove image...
+    //tempImage
+    display->RemoveEGLImage( image );
+
+    return EGL_TRUE;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLImage.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,140 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLImage.h"
+#include "EGLUtils.h"
+#include "EGLState.h"
+#include <EGL/eglext.h>
+#include <VG/openvg.h>
+
+#include <stdlib.h>
+
+CEGLImage::CEGLImage( EGLenum target, EGLClientBuffer buffer, 
+                      SurfaceDescriptor desc, void* data) :
+    m_buffer( buffer ),
+    m_target( target ),
+	m_data(data)
+    {
+    m_siblings = EGLI_NEW EGLImageSibling;
+    m_siblings->buffer = buffer;
+    m_siblings->target = target;
+    m_siblings->next   = NULL;
+    m_SurfDesc.m_alphaShift     = desc.m_alphaShift;
+    m_SurfDesc.m_blueShift      = desc.m_blueShift;
+    m_SurfDesc.m_depthSize      = desc.m_depthSize;
+    m_SurfDesc.m_greenShift     = desc.m_greenShift;
+    m_SurfDesc.m_height         = desc.m_height;
+    m_SurfDesc.m_luminanceShift = desc.m_luminanceShift;
+    m_SurfDesc.m_maskSize       = desc.m_maskSize;
+    m_SurfDesc.m_redShift       = desc.m_redShift;
+    m_SurfDesc.m_stencilSize    = desc.m_stencilSize;
+    m_SurfDesc.m_stride         = desc.m_stride;
+    m_SurfDesc.m_width          = desc.m_width;
+
+    m_SurfDesc.m_colorDescriptor.m_alphaMaskSize = desc.m_colorDescriptor.m_alphaMaskSize;
+    m_SurfDesc.m_colorDescriptor.m_alphaSize     = desc.m_colorDescriptor.m_alphaSize;
+    m_SurfDesc.m_colorDescriptor.m_blueSize      = desc.m_colorDescriptor.m_blueSize;
+    m_SurfDesc.m_colorDescriptor.m_bpp           = desc.m_colorDescriptor.m_bpp;
+    m_SurfDesc.m_colorDescriptor.m_format        = desc.m_colorDescriptor.m_format;
+    m_SurfDesc.m_colorDescriptor.m_greenSize     = desc.m_colorDescriptor.m_greenSize;
+    m_SurfDesc.m_colorDescriptor.m_luminanceSize = desc.m_colorDescriptor.m_luminanceSize;
+    m_SurfDesc.m_colorDescriptor.m_redSize       = desc.m_colorDescriptor.m_redSize;
+    }
+
+CEGLImage::~CEGLImage(void)
+    {
+    // tero 2010-08-02, changed to free, since delete is _certainly_ incorrect.
+    if( m_data )
+    free(m_data);
+    m_data = NULL;
+    DestroyAllSiblings();
+    }
+
+void CEGLImage::AddSibling( EGLenum target, EGLClientBuffer buffer )
+    {
+    EGLImageSibling* newp;
+    EGLImageSibling* curr = m_siblings;
+    newp = EGLI_NEW EGLImageSibling;
+    newp->buffer = buffer;
+    newp->target = target;
+    newp->next   = NULL;
+
+    while( curr->next )
+        {
+        curr = curr->next;
+        }      
+    curr->next = newp;
+    }
+
+void CEGLImage::UpdateData( CEGLState *state, void* data )
+    {
+    EGLImageSibling* curr = m_siblings;
+    while( curr )
+        {
+        switch ( curr->target )
+            {
+            case EGL_VG_PARENT_IMAGE_KHR:
+                {
+                // OpenVG
+
+                }
+                break;
+            case EGL_GL_TEXTURE_2D_KHR:
+		    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
+            case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
+            case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
+            case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
+            case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
+            case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
+                {
+                // GLES
+                IEGLtoGLES2Interface* iFace = (IEGLtoGLES2Interface*)state->GLESInterface(2);
+                //iFace->UpdateBuffers(
+                }
+                break;
+            default:
+                break;
+            }
+        curr = curr->next;
+        }
+    }
+
+void CEGLImage::DestroyAllSiblings()
+    {
+    EGLImageSibling* curr = m_siblings;
+    EGLImageSibling* next = curr->next;
+
+    while( curr )
+        {
+        next = curr->next;
+        free( curr );
+        curr = next;
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLPbufferSurface.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,102 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLPbufferSurface.h"
+#include "EGLOs.h"
+
+CEGLPbufferSurface::CEGLPbufferSurface(void) :
+    CEGLSurface( CEGLSurface::PBUFFER_SURFACE,
+                 0,
+                 0,
+                 0,
+                 NULL ),
+    m_clientBuffer( NULL ),
+    m_container( NULL )
+    {
+    }
+
+CEGLPbufferSurface::CEGLPbufferSurface( EGLint colorSpace, EGLint alphaFormat, EGLint renderBuffer, CEGLConfig* config, EGLint largestPbuffer, EGLint textureFormat, EGLint textureTarget, EGLint mipmapTexture, EGLClientBuffer clientBuf ) :
+    CEGLSurface( CEGLSurface::PBUFFER_SURFACE,
+                 colorSpace,
+                 alphaFormat,
+                 renderBuffer,
+                 config ),
+    m_largestPbuffer( largestPbuffer ),
+    m_textureFormat( textureFormat ),
+	m_textureTarget( textureTarget ),
+	m_mipmapTexture( mipmapTexture ),
+    m_clientBuffer( clientBuf ),
+    m_container( NULL )
+    {
+
+    }
+
+CEGLPbufferSurface::~CEGLPbufferSurface(void)
+    {
+    if( m_container )
+        {
+        // \todo errors
+        CEGLOs::DestroyNativePbuffer( m_container );
+        delete m_container;
+        m_container = NULL;
+        }
+    }
+
+void CEGLPbufferSurface::SetNativePbufferContainer( EGLINativePbufferContainer* container )
+    {
+    if( m_container )
+        {
+        // \todo errors
+        CEGLOs::DestroyNativePbuffer( m_container );
+        delete m_container;
+        m_container = NULL;
+        }
+    m_container = container;
+    }
+
+bool CEGLPbufferSurface::BindCopyContext()
+    {
+    m_tmpContext = CEGLOs::CurrentNativeContext();
+    // \todo read/draw?
+    m_tmpDisplay = CEGLOs::CurrentNativeSurface();
+
+    if( !m_container )
+        {
+        return false;
+        }
+    
+    return CEGLOs::MakeNativeContextCurrent( NativeGLFunctions(), NativeDisplay(), NativeDisplay(), CopyContext() );
+    }
+
+bool CEGLPbufferSurface::ReleaseCopyContext()
+    {
+    // \todo read/draw?
+    return CEGLOs::MakeNativeContextCurrent( NativeGLFunctions(), m_tmpDisplay, m_tmpDisplay, m_tmpContext );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLProcess.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,128 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLProcess.h"
+#include "EGLThread.h"
+#include "eglInternal.h"
+
+CEGLProcess::CEGLProcess( EGLint processId ) :
+    m_id( processId ),
+    m_currentThread( NULL )
+    {
+    }
+
+CEGLProcess::~CEGLProcess(void)
+    {
+    DestroyPointerVector<CEGLThread>(m_threads);
+    }
+
+CEGLThread* CEGLProcess::AddThread( EGLI_THREAD_ID threadId, bool setCurrent, EGLint supportedApis )
+    {
+    CEGLThread* thread = HasThread( threadId );
+    if( !thread )
+        {
+        thread = EGLI_NEW CEGLThread( threadId, supportedApis );
+        if( thread )
+            {
+            AddObject<CEGLThread>( m_threads, thread );
+            }
+        }    
+    if( setCurrent && thread )
+        {
+        m_currentThread = thread;
+        }
+    return thread;
+    }
+
+void CEGLProcess::RemoveThread( EGLI_THREAD_ID threadId )
+    {
+    if( m_currentThread && m_currentThread->Id() == threadId )
+        {
+        m_currentThread = NULL;
+        }
+    DeleteObjectById<CEGLThread>( m_threads, threadId );
+    }
+
+CEGLThread* CEGLProcess::HasThread( EGLI_THREAD_ID threadId ) const
+    {
+    return FindObjectById<CEGLThread>( m_threads, threadId, NULL );
+    }
+
+void CEGLProcess::SetCurrentThread( EGLI_THREAD_ID threadId )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    EGLI_ASSERT(m_currentThread != NULL);
+    if( m_currentThread->Id() != threadId )
+        {
+        m_currentThread = FindObjectById<CEGLThread>( m_threads, threadId, NULL );
+        EGLI_ASSERT( m_currentThread != NULL );
+        }
+#else
+    EGLI_ASSERT( false );
+#endif
+    }
+
+CEGLThread* CEGLProcess::CurrentThread() const
+    { 
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    EGLI_ASSERT( m_currentThread != NULL );
+    return m_currentThread;
+#elif defined(_WIN32)
+    EGLI_THREAD_ID threadId = GetCurrentThreadId();
+    CEGLThread* thread = FindObjectById( m_threads, threadId, NULL );
+    //EGLI_ASSERT( thread != NULL );
+    return thread;
+#else // Linux
+    // \todo
+#endif
+    }
+
+CEGLSurface* CEGLProcess::FindBoundSurface( CEGLContext* context, bool readSurface ) const
+     {
+     EGLI_ASSERT( context != NULL );
+     CEGLSurface* ret = NULL;         
+     std::vector<CEGLThread*>::const_iterator iter = m_threads.begin();
+     while( iter != m_threads.end() )
+         {
+         if( (*iter)->CurrentVGContext() == context )
+             {
+             ret = (*iter)->CurrentVGSurface();
+             break;
+             }
+         else if( (*iter)->CurrentGLESContext() == context )
+             {
+             //TODO
+             EGLI_ASSERT( false );
+             }
+         }
+     return ret;
+     }
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLState.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,800 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLState.h"
+#include "EGLDisplay.h"
+#include "EGLProcess.h"
+#include "EGLThread.h"
+#include "EGLContext.h"
+#include "EGLConfig.h"
+#include "EGLOs.h"
+#include "EGLImage.h"
+#include "EGLPbufferSurface.h"
+#include "EGLWindowSurface.h"
+#include <EGL/eglext.h>
+
+#include <string.h>
+
+CEGLState::CEGLState(void) :
+    m_initialized( false ),
+    m_currentProcess( NULL ),
+    m_VGLib( NULL ),
+    m_VGInterface( NULL ),
+    m_GLES1Lib( NULL ),
+    m_GLES1Interface( NULL ),
+    m_GLES2Lib( NULL ),
+    m_GLES2Interface( NULL ),
+	m_hostGL( NULL ),
+    m_supportedApis( 0 ),
+	m_defaultDisplay( NULL ),
+	m_dummyWindow( NULL )
+    {
+
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    CEGLProcess* p = EGLI_NEW CEGLProcess(0);
+    EGLI_ASSERT( p != NULL );
+    AddObject<CEGLProcess>( m_processes, p );
+    m_currentProcess = p;
+#endif
+    }
+
+CEGLState::~CEGLState(void)
+    {
+    DestroyPointerVector<CEGLProcess>( m_processes );
+    DestroyPointerVector<CEGLDisplay>( m_displays );
+    DestroyPointerVector<CEGLConfig>( m_configs );
+    if( m_VGLib ) EGLI_ASSERT( CEGLOs::FreeClientLibrary(m_VGLib) );
+    if( m_GLES1Lib ) EGLI_ASSERT( CEGLOs::FreeClientLibrary(m_GLES1Lib) );
+    if( m_GLES2Lib ) EGLI_ASSERT( CEGLOs::FreeClientLibrary(m_GLES2Lib) );
+#if defined(_WIN32)
+#   if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( m_defaultDisplay )
+        {
+        // \todo If at some point EGL_DEFAULT_DISPLAY is created
+        //       with CreateDC() the DC needs to be released by
+        //       calling DeleteDC().
+        //CEGLOs::DestroyDefaultDisplay( m_defaultDisplay );
+        ReleaseDC( m_dummyWindow, m_defaultDisplay );
+        }
+    // \note Dummy window created in CEGLDisplay::Initialize(). See comment
+    //       in CEGLOs::CreateDefaultDisplay().
+    if( m_dummyWindow )
+        {
+        CEGLOs::DestroyNativeWindow( m_dummyWindow );
+        }
+#   endif
+#endif
+    }
+
+bool CEGLState::Initialize()
+    {
+    if( !m_initialized )
+        {
+        if( !(CreateConfigs()) ) return false;
+        m_initialized = true;
+        m_VGInterface = CEGLOs::LoadVGInterface( m_VGLib );
+        if( m_VGInterface ) 
+            {
+            m_VGInterface->SetEGLInterface( this );
+            m_supportedApis |= EGL_OPENVG_BIT;
+            }
+
+        m_GLES1Interface = CEGLOs::LoadGLES1Interface( m_GLES1Lib );
+        if( m_GLES1Interface ) 
+            {
+            m_GLES1Interface->SetEGLInterface( this );
+            m_supportedApis |= EGL_OPENGL_ES_BIT;
+            }
+
+	    m_GLES2Interface = CEGLOs::LoadGLES2Interface( m_GLES2Lib );
+        if( m_GLES2Interface ) 
+            {
+            m_GLES2Interface->SetEGLInterface( this );
+            m_supportedApis |= EGL_OPENGL_ES2_BIT;
+            }
+
+        if( m_supportedApis & EGL_OPENGL_ES_BIT || (m_supportedApis & EGL_OPENGL_ES2_BIT) )
+            {
+            m_hostGL = CEGLOs::LoadHostGL();
+            if( !m_hostGL ) m_initialized = false;
+            }
+        if( !m_supportedApis )
+            {
+            m_initialized = false;
+            }
+
+		//m_defaultDisplay = CEGLOs::CreateDefaultDisplay();
+        // \note Creating a dummy window to get DC from. See comment
+        //       in CEGLOs::CreateDefaultDisplay().
+		m_dummyWindow = CEGLOs::CreateNativeWindow(0, 0);
+        if( m_dummyWindow )
+			{
+#if defined(_WIN32)
+			m_defaultDisplay = (EGLINativeDisplayType)GetDC( (HWND)m_dummyWindow );
+#else // Linux
+			EGLI_ASSERT( false );
+#endif
+			if( !m_defaultDisplay )
+				{
+				CEGLOs::DestroyNativeWindow( m_dummyWindow );
+				m_initialized = false;
+				}
+			}
+        }
+    return m_initialized;
+    }
+
+CEGLDisplay* CEGLState::AddDisplay( EGLINativeDisplayType nativeType, EGLint processId )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    CEGLDisplay* display = EGLI_NEW CEGLDisplay( nativeType, processId );
+#else
+    CEGLDisplay* display = EGLI_NEW CEGLDisplay( nativeType, m_currentProcess->Id() );
+#endif
+    if( display )
+        {
+        AddObject<CEGLDisplay>( m_displays, display );
+        }
+    return display;
+    }
+
+void CEGLState::RemoveDisplay( EGLDisplay display )
+    {
+    DeleteObjectByPointer<CEGLDisplay>( m_displays, display );
+    }
+
+CEGLDisplay* CEGLState::GetDisplayByNativeType( EGLINativeDisplayType nativeType, EGLint processId ) const
+    {
+    CEGLDisplay* ret = NULL;
+    for( std::vector<CEGLDisplay*>::const_iterator iter = m_displays.begin();
+        iter != m_displays.end();
+        iter++)
+        {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+        if( (*iter)->NativeType() == nativeType && (*iter)->ProcessId() == processId )
+#else
+        if( (*iter)->NativeType() == nativeType )
+#endif
+            {
+            ret = (*iter);
+            break;
+            }
+        }
+    return ret;
+    }
+
+CEGLDisplay* CEGLState::GetDisplay( EGLDisplay display ) const
+    {
+    return FindObjectByPointer<CEGLDisplay>( m_displays, display, NULL);
+    }
+
+CEGLProcess* CEGLState::AddProcess( EGLint processId, bool setCurrent )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    CEGLProcess* process = EGLI_NEW CEGLProcess( processId );
+    if( process )
+        {
+        AddObject<CEGLProcess>( m_processes, process );
+        if( setCurrent && process )
+            {
+            m_currentProcess = process;
+            }
+        }
+    return process;
+#else
+    EGLI_ASSERT( false );
+    return NULL;
+#endif
+    }
+
+void CEGLState::RemoveProcess( EGLint processId )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( m_currentProcess && m_currentProcess->Id() == processId )
+        {
+        m_currentProcess = NULL;
+        }
+    DeleteObjectById<CEGLProcess>( m_processes, processId );
+#else
+    EGLI_ASSERT( false );
+#endif
+    }
+
+CEGLProcess* CEGLState::GetProcess( EGLint processId ) const
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    return FindObjectById<CEGLProcess>( m_processes, processId, NULL );
+#else
+    return m_currentProcess;
+#endif
+    }
+
+void CEGLState::SetCurrentProcessThread( EGLint processId, EGLI_THREAD_ID threadId )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( m_currentProcess && m_currentProcess->Id() == processId )
+        {
+        m_currentProcess->SetCurrentThread( threadId );
+        }
+    else
+        {
+        CEGLProcess* process = FindObjectById<CEGLProcess>( m_processes, processId, NULL);
+        // processes are created in eglPlatsimSetProcessInformation()
+        EGLI_ASSERT( process != NULL );
+        process->SetCurrentThread( threadId );
+        m_currentProcess = process;
+        }
+#else
+    EGLI_ASSERT( false );
+#endif
+    }
+
+void CEGLState::FillConfigs( EGLConfig* configs, EGLint size ) const
+    {
+    EGLI_ASSERT( size <= ConfigCount() );
+    for( EGLint i=0; i < size; i++ )
+        {
+        configs[i] = (EGLConfig)m_configs[i];
+        }
+    }
+
+CEGLConfig* CEGLState::FindConfigById( EGLint id ) const
+    {
+    return FindObjectById<CEGLConfig>( m_configs, id, NULL );
+    }
+
+EGLint CEGLState::MatchConfigs( CEGLConfig* filter, EGLConfig* configs, EGLint maxCount ) const
+    {
+    maxCount = EGLI_MIN( m_configs.size(), (unsigned int)maxCount );
+    EGLint count = 0;
+    std::vector<CEGLConfig*>::const_iterator iter = m_configs.begin();
+    while( iter != m_configs.end() )
+        {
+        if( (*iter)->Match( *filter ) )
+            {
+            if( configs && count < maxCount )
+                configs[count++] = (EGLConfig)(*iter);
+            else if( configs )
+                break;
+            else
+                count++;
+            }
+        iter++;
+        }
+    if( configs && count > 1 )
+        {
+        for( int i=0; i < count-1; i++ )
+            for( int j=i+1; j < count; j++ )
+                {
+                if( *((CEGLConfig*)configs[j]) > *((CEGLConfig*)configs[i]) )
+                    {
+                    EGLConfig tmp = configs[i];
+                    configs[i] = configs[j];
+                    configs[j] = tmp;
+                    }
+                }
+        }
+    return count;
+    }
+
+CEGLConfig* CEGLState::GetConfig( EGLConfig config ) const
+    {
+    return FindObjectByPointer<CEGLConfig>( m_configs, config, NULL );
+    }
+
+void* CEGLState::GetVGContext()
+    {
+    CEGLOs::GetLock( &g_eglLock );
+    void* ret = NULL;
+    if( m_currentProcess &&
+        m_currentProcess->CurrentThread() &&
+        m_currentProcess->CurrentThread()->CurrentVGContext() )
+        {
+        ret = m_currentProcess->CurrentThread()->CurrentVGContext()->ClientContext();
+        }
+    CEGLOs::ReleaseLock( &g_eglLock );
+    return ret;
+    }
+
+void* CEGLState::GetHostProcAddress(const char* proc)
+	{
+    return CEGLOs::GetGLProcAddress(m_hostGL, proc);
+	}
+
+void* CEGLState::GetGLESContext()
+    {
+    CEGLOs::GetLock( &g_eglLock );
+    void* ret = NULL;
+    if( m_currentProcess &&
+        m_currentProcess->CurrentThread() &&
+        m_currentProcess->CurrentThread()->CurrentGLESContext() )
+        {
+        ret = m_currentProcess->CurrentThread()->CurrentGLESContext()->ClientContext();
+        }
+    CEGLOs::ReleaseLock( &g_eglLock );
+    return ret;
+    }
+
+bool CEGLState::IsImageInUse( void* image )
+    {
+    //TODO
+    return false;
+    }
+
+bool CEGLState::LockVGSurface( bool read, bool write )
+    {
+    return LockSurface( EGL_OPENVG_API, read, write );
+    }
+
+bool CEGLState::UnlockVGSurface()
+    {
+    return UnlockSurface( EGL_OPENVG_API );
+    }
+
+void CEGLState::GetDescForImage( void* image, SurfaceDescriptor& ImageDesc )
+    {
+    CEGLImage* eglImage = (CEGLImage*)image;
+    ImageDesc.m_stride = -1;
+    ImageDesc.m_height = -1;
+    ImageDesc.m_width  = -1;
+    // Check that image is not null.
+    if( !eglImage )
+        {        
+        return;
+        }
+
+    // Check that image is not from VGImage target. -> EGL_VG_PARENT_IMAGE_KHR
+    if( eglImage->Target() == EGL_VG_PARENT_IMAGE_KHR )
+        {
+        return;
+        }
+
+	memcpy(&ImageDesc, &eglImage->SurfaceDesc(), sizeof(ImageDesc));
+    }
+
+
+void* CEGLState::GetDataForImage( void* image )
+    {
+    CEGLImage* eglImage = (CEGLImage*)image;
+    // Check that image is not null.
+    if( !eglImage )
+        {
+        // if null then error
+        return NULL;
+        }
+	return eglImage->Data();
+    }
+
+void CEGLState::RegisterImageTarget( void* image, EImageTarget target, void* buffer )
+	{
+	// \todo Implement
+	}
+
+void CEGLState::UnregisterImageTarget( void* image, EImageTarget target, void* buffer )
+	{
+	// \todo Implement
+	}
+
+void CEGLState::UpdateImageSiblings( void* image, EImageTarget target, void* buffer )
+	{
+	// \todo Implement
+	}
+
+void CEGLState::ReleaseTexImage(void* surface, int name, int level)
+{
+	CEGLSurface* eglSurface = (CEGLSurface*)surface;
+	EGLITextureBinding& binding = eglSurface->TextureBinding();
+	if(binding.name == name && binding.level == level)
+	{
+		eglSurface->Unlock();
+		binding.name = 0;
+	}
+}
+
+bool CEGLState::LockGLESSurface( bool read, bool write )
+    {
+    return LockSurface( EGL_OPENGL_ES_API, read, write );
+    }
+bool CEGLState::UnlockGLESSurface()
+    {
+    return UnlockSurface( EGL_OPENGL_ES_API );
+    }
+
+bool CEGLState::SyncSurface( EGLenum api, EGLint apiVersion, CEGLSurface* surface, CEGLSurface* currentGLESReadSurface )
+	{
+	switch( api )
+		{
+		case EGL_OPENVG_API:
+			{
+			EGLint glesVersion = 0;
+			if( surface->IsGLES1Dirty() )
+				{
+				glesVersion = 1;
+				}
+			else if( surface->IsGLES2Dirty() )
+				{
+				glesVersion = 2;
+				}
+			if( glesVersion )
+				{
+				if( surface != currentGLESReadSurface )
+					{
+					EGLINativeContextType glesCopyContext = NULL;
+                    EGLINativeDisplayType glesCopyDisplay = NULL;
+                    EGLINativeGLFunctions* funcs = NULL;
+					bool pbuffer = ( surface->Type() == CEGLSurface::PBUFFER_SURFACE );
+					if( pbuffer )
+						{
+						if( !(((CEGLPbufferSurface*)surface)->BindCopyContext()) )
+							{
+							((CEGLPbufferSurface*)surface)->ReleaseCopyContext();
+							
+							return false;
+							}
+						}
+					else if( surface->Type() == CEGLSurface::WINDOW_SURFACE )
+						{
+						// \todo Remove this or handle window surface sync properly
+						/*
+						funcs = thread->CurrentGLESContext()->NativeGLFunctions();
+						glesCopyContext = thread->CurrentGLESContext()->NativeContext();
+						glesCopyDisplay = ((CEGLWindowSurface*)surface)->OsContext()->glesDisplay;
+						*/
+						}
+					if( !(GLESInterface(glesVersion)->CopyBuffers(surface->GLESColorBuffer(), surface->Descriptor())) )
+						{
+						if( pbuffer )
+							{
+							((CEGLPbufferSurface*)surface)->ReleaseCopyContext();
+							}
+						return false;
+						}
+					if( pbuffer )
+						{
+						((CEGLPbufferSurface*)surface)->ReleaseCopyContext();
+						}
+					else if( surface->Type() == CEGLSurface::WINDOW_SURFACE )
+						{
+						// \todo Remove this or handle window surface sync properly
+						//EGLI_ASSERT( false );
+						}
+					}
+				else
+					{
+					if( !(GLESInterface(glesVersion)->CopyBuffers(surface->GLESColorBuffer(), surface->Descriptor())) )
+						return false;
+					}
+
+				if( VGInterface() )
+                    {
+                    VGInterface()->UpdateBuffers(surface->GLESColorBuffer(), surface->Stride(), surface->Descriptor());
+                    }
+                surface->SetGLES1Dirty( false );
+				surface->SetGLES2Dirty( false );
+				}
+			break;
+			}
+
+		case EGL_OPENGL_ES_API:
+			{
+			if( surface->IsVGDirty() )
+                {
+				if( !(GLESInterface(apiVersion)->UpdateBuffers(surface->VGColorBuffer(), surface->Descriptor())) )
+                    {
+                    return false;
+                    }
+                surface->SetVGDirty( false );
+                }
+			break;
+			}
+		}
+
+	return true;
+	}
+
+bool CEGLState::LockSurface( EGLenum api, bool read, bool write )
+    {
+    CEGLOs::GetLock( &g_eglLock );
+    CEGLSurface* readSurface = NULL;
+    CEGLSurface* drawSurface = NULL;
+	CEGLSurface* glesReadSurface = NULL;
+	EGLint apiVersion;
+    CEGLThread* thread = m_currentProcess->CurrentThread();
+    if( !thread )
+        {
+        CEGLOs::ReleaseLock( &g_eglLock );
+        return false;
+        }
+    switch( api )
+        {
+        case EGL_OPENVG_API:
+            {
+            drawSurface = thread->CurrentVGSurface();
+            readSurface = drawSurface;
+			apiVersion = 0;
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            thread->CurrentGLESSurfaces( &readSurface, &drawSurface );
+			apiVersion = thread->CurrentGLESContext()->ClientVersion();
+            break;
+            }
+        }
+    if( !readSurface && !drawSurface )
+        {
+        CEGLOs::ReleaseLock( &g_eglLock );
+        return false;
+        }
+
+	if( api == EGL_OPENVG_API )
+		{
+		thread->CurrentGLESSurfaces( &readSurface, NULL );
+		}
+    
+    if( read && readSurface )
+        {
+        readSurface->Lock();
+		if( !SyncSurface( api, apiVersion, readSurface, glesReadSurface ) )
+			{
+			CEGLOs::ReleaseLock( &g_eglLock );
+			return false;
+			}
+        }
+    if( write && drawSurface && (!read || drawSurface != readSurface) )
+        {
+        drawSurface->Lock();
+		if( !SyncSurface( api, apiVersion, drawSurface, glesReadSurface ) )
+			{
+			CEGLOs::ReleaseLock( &g_eglLock );
+			return false;
+			}
+        }
+    CEGLOs::ReleaseLock( &g_eglLock );
+    return true;
+    }
+
+bool CEGLState::UnlockSurface( EGLenum api )
+    {
+    CEGLOs::GetLock( &g_eglLock );
+    CEGLSurface* drawSurface = NULL;
+	CEGLSurface* readSurface = NULL;
+    CEGLThread* thread = m_currentProcess->CurrentThread();
+    if( !thread )
+        {
+        CEGLOs::ReleaseLock( &g_eglLock );
+        return false;
+        }
+    switch( api )
+        {
+        case EGL_OPENVG_API:
+            {
+            drawSurface = thread->CurrentVGSurface();
+			readSurface = drawSurface;
+			if( drawSurface && drawSurface->IsLocked() )
+                drawSurface->SetVGDirty( true );
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            thread->CurrentGLESSurfaces( &readSurface, &drawSurface );
+			if( drawSurface && drawSurface->IsLocked() )
+				{
+				EGLint glesVersion = thread->CurrentGLESContext()->ClientVersion();
+				if(glesVersion == 1)
+					{
+					drawSurface->SetGLES1Dirty( true );
+					}
+				else
+					{
+					EGLI_ASSERT(glesVersion == 2);
+					drawSurface->SetGLES2Dirty( true );
+					}
+				}
+            break;
+            }
+        }
+    if( drawSurface && drawSurface->IsLocked() )
+        {
+        drawSurface->Unlock();
+        }
+    if( readSurface && readSurface->IsLocked() )
+        {
+        readSurface->Unlock();
+        }
+
+    CEGLOs::ReleaseLock( &g_eglLock );
+    return true;
+    }
+
+bool CEGLState::CreateConfigs()
+    {    
+    // ** Config list START **
+    // Initial config count. If adding configs to the list below
+    // remember to add this count too.
+    int count = 21;
+    for( int i=0; i < count; i++ )
+        {        
+        CEGLConfig* config = EGLI_NEW CEGLConfig();
+        // \note AddObject destroys the object if fails to take ownership 
+        AddObject<CEGLConfig>( m_configs, config );
+        if( !config )
+            {
+            DestroyPointerVector<CEGLConfig>( m_configs );
+            return false;
+            }
+        }
+    int configId = 0;
+    CEGLConfig* config = m_configs[configId];
+    //                                                 r, g, b, l, a, am, s, bpp, id
+    // XRGB_8888 and ARGB_8888
+                                  config->SetUpConfig( 8, 8, 8, 0, 8, 0,  0, 32,  ++configId ); //  1
+    config = m_configs[configId]; config->SetUpConfig( 8, 8, 8, 0, 8, 1,  0, 32,  ++configId ); //  2
+    config = m_configs[configId]; config->SetUpConfig( 8, 8, 8, 0, 8, 4,  0, 32,  ++configId ); //  3
+    config = m_configs[configId]; config->SetUpConfig( 8, 8, 8, 0, 8, 8,  0, 32,  ++configId ); //  4    
+    config = m_configs[configId]; config->SetUpConfig( 8, 8, 8, 0, 0, 0,  0, 32,  ++configId ); //  5
+    config = m_configs[configId]; config->SetUpConfig( 8, 8, 8, 0, 0, 1,  0, 32,  ++configId ); //  6
+    config = m_configs[configId]; config->SetUpConfig( 8, 8, 8, 0, 0, 4,  0, 32,  ++configId ); //  7
+    config = m_configs[configId]; config->SetUpConfig( 8, 8, 8, 0, 0, 8,  0, 32,  ++configId ); //  8
+    // RGB_565
+    config = m_configs[configId]; config->SetUpConfig( 5, 6, 5, 0, 0, 0,  0, 16,  ++configId ); //  9
+    config = m_configs[configId]; config->SetUpConfig( 5, 6, 5, 0, 0, 1,  0, 16,  ++configId ); // 10
+    config = m_configs[configId]; config->SetUpConfig( 5, 6, 5, 0, 0, 4,  0, 16,  ++configId ); // 11
+    config = m_configs[configId]; config->SetUpConfig( 5, 6, 5, 0, 0, 8,  0, 16,  ++configId ); // 12
+    // LA_88
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 8, 8, 0,  0, 16,  ++configId ); // 13
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 8, 8, 1,  0, 16,  ++configId ); // 14
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 8, 8, 4,  0, 16,  ++configId ); // 15
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 8, 8, 8,  0, 16,  ++configId ); // 16
+    // L_8
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 8, 0, 0,  0,  8,  ++configId ); // 17
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 8, 0, 1,  0,  8,  ++configId ); // 18
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 8, 0, 4,  0,  8,  ++configId ); // 19
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 8, 0, 8,  0,  8,  ++configId ); // 20
+    // A_8
+    config = m_configs[configId]; config->SetUpConfig( 0, 0, 0, 0, 8, 0,  0,  8,  ++configId ); // 21
+    // ** Config list END **
+    
+    std::vector<CEGLConfig*> newConfigs;
+
+    // stencil buffers
+    std::vector<CEGLConfig*>::const_iterator iter = m_configs.begin();
+    while( iter != m_configs.end() )
+        {
+        config = EGLI_NEW CEGLConfig();
+        if( config )
+            {
+            *config = *(*iter);
+            config->SetId( ++configId );
+            config->SetAttribute( EGL_STENCIL_SIZE, 8 );
+            }
+        // \note AddObject destroys the object if fails to take ownership 
+        AddObject<CEGLConfig>( newConfigs, config );
+        if( !config )
+            {
+            DestroyPointerVector<CEGLConfig>( newConfigs );
+            DestroyPointerVector<CEGLConfig>( m_configs );
+            return false;
+            }
+        iter++;
+        }
+    try
+        {
+        m_configs.insert( m_configs.end(), newConfigs.begin(), newConfigs.end() );
+        }
+    catch( std::exception )
+        {
+        DestroyPointerVector<CEGLConfig>( newConfigs );
+        DestroyPointerVector<CEGLConfig>( m_configs );
+        return false;
+        }
+    newConfigs.clear();
+
+    // depth buffers
+    // 32bpp, 24bpp and 16bpp support
+    for(int depthSize = 32; depthSize >= 16; depthSize -= 8 )
+        {
+        iter = m_configs.begin();
+        while( iter != m_configs.end() )
+            {
+            config = EGLI_NEW CEGLConfig();
+            if( config )
+                {
+                *config = *(*iter);
+                config->SetId( ++configId );
+                config->SetAttribute( EGL_DEPTH_SIZE, depthSize );
+                }            
+            // \note AddObject destroys the object if fails to take ownership    
+            AddObject<CEGLConfig>( newConfigs, config );
+            if( !config )
+                {
+                DestroyPointerVector<CEGLConfig>( newConfigs );
+                DestroyPointerVector<CEGLConfig>( m_configs );
+                return false;
+                }
+            iter++;
+            }
+        }
+    try
+        {
+        m_configs.insert( m_configs.end(), newConfigs.begin(), newConfigs.end() );
+        }
+    catch( std::exception )
+        {
+        DestroyPointerVector<CEGLConfig>( newConfigs );
+        DestroyPointerVector<CEGLConfig>( m_configs );
+        return false;
+        }
+    newConfigs.clear();
+
+    // multi sampling
+    for( int samples = 16; samples >= 4; samples -= 12 )
+        {
+        iter = m_configs.begin();
+        while( iter != m_configs.end() )
+            {
+            config = EGLI_NEW CEGLConfig();
+            if( config )
+                {
+                *config = *(*iter);
+                config->SetId( ++configId );
+                config->SetAttribute( EGL_SAMPLES, samples );
+                config->SetAttribute( EGL_SAMPLE_BUFFERS, 1 );
+                }
+            // \note AddObject destroys the object if fails to take ownership
+            AddObject<CEGLConfig>( newConfigs, config );
+            if( !config )
+                {
+                DestroyPointerVector<CEGLConfig>( newConfigs );
+                DestroyPointerVector<CEGLConfig>( m_configs );
+                return false;
+                }
+            iter++;
+            }
+        }
+    try
+        {
+        m_configs.insert( m_configs.end(), newConfigs.begin(), newConfigs.end() );
+        }
+    catch( std::exception )
+        {
+        DestroyPointerVector<CEGLConfig>( newConfigs );
+        DestroyPointerVector<CEGLConfig>( m_configs );
+        return false;
+        }
+    newConfigs.clear();  
+    return true;
+    }
+
+IEGLtoGLESInterface* CEGLState::GLESInterface( EGLint clientVersion ) const
+	{
+	EGLI_ASSERT(clientVersion == 1 || clientVersion == 2);
+	return clientVersion == 1 ? m_GLES1Interface : m_GLES2Interface;
+	}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLSurface.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,224 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLSurface.h"
+#include "SurfaceDescriptor.h"
+#include "EGLConfig.h"
+#include "EGLContext.h"
+#include "EGLOs.h"
+
+#include <string.h>
+// Required for free. \todo Shouldn't this use C++ new[]/delete[] instead?
+#include <stdlib.h>
+
+CEGLSurface::CEGLSurface( CEGLSurface::SurfaceType type, EGLint colorSpace, EGLint alphaFormat, EGLint renderBuffer, CEGLConfig* config ) :
+    m_type( type ),
+    m_colorSpace( colorSpace ),
+    m_alphaFormat( alphaFormat ),
+    m_renderBuffer( renderBuffer ),
+    m_config( config ),
+    m_boundContext( NULL ),
+    m_thread( NULL ),
+    m_mipmapLevel( 0 ),
+    m_multisampleResolve( EGL_MULTISAMPLE_RESOLVE_DEFAULT ),
+    m_swapBehavior( /*EGL_BUFFER_DESTROYED*/EGL_BUFFER_PRESERVED ),
+    m_vgDirty(false),
+    m_gles1Dirty(false),
+    m_gles2Dirty(false),
+    m_isLocked(false)
+    {
+    EGLI_ASSERT( m_config != NULL );
+	memset( &m_textureBinding, 0, sizeof(struct EGLITextureBinding) );
+    memset( &m_vgBuffers, 0, sizeof(struct BufferContainer) );
+    memset( &m_glesBuffers, 0, sizeof(struct BufferContainer) );
+    CEGLOs::InitializeLock( &m_lock );
+    }
+
+CEGLSurface::~CEGLSurface(void)
+    {
+    if( m_glesBuffers.m_colorBuffer )
+        free (m_glesBuffers.m_colorBuffer );
+    CEGLOs::DestroyLock( &m_lock );
+    }
+
+void CEGLSurface::BindToContext( CEGLContext* context ) 
+    { 
+    m_boundContext = context;
+    }
+
+bool CEGLSurface::Resize( EGLint width, EGLint height )
+    {
+    if( width == m_width && height == m_height && m_glesBuffers.m_colorBuffer )
+        {
+        // Size didn't change and we have gles color buffer already
+        return true;
+        }
+        
+    if( width != m_width )
+        {
+        SetStride( (width * m_config->GetDescriptor()->Bpp() + 7)/8 );
+        }
+    m_width = width;
+    m_height = height;
+    if( m_glesBuffers.m_colorBuffer )
+        free( m_glesBuffers.m_colorBuffer );
+    m_glesBuffers.m_colorBuffer = malloc( height * m_stride );
+    if( !(m_glesBuffers.m_colorBuffer) ) return false;
+    return true;
+    }
+
+SurfaceDescriptor* CEGLSurface::Descriptor()
+    {
+    CColorDescriptor* colorDesc = m_config->GetDescriptor();
+    EGLI_ASSERT( colorDesc != NULL );
+    m_surfaceDescriptor.m_width = Width();
+    m_surfaceDescriptor.m_height = Height();
+    m_surfaceDescriptor.m_stride = Stride();
+    m_surfaceDescriptor.m_colorDescriptor = *colorDesc;
+    m_surfaceDescriptor.m_colorDescriptor.SetSurfaceType(m_colorSpace, m_alphaFormat);
+
+    EGLint alphaSize = colorDesc->AlphaSize();
+    EGLint blueSize = colorDesc->BlueSize();
+    EGLint greenSize = colorDesc->GreenSize();
+    EGLint redSize = colorDesc->RedSize();
+    EGLint luminanceSize = colorDesc->LuminanceSize();
+
+    if( colorDesc->isLuminance() )
+        {
+        // \todo LA AL?
+        m_surfaceDescriptor.m_redShift = 0;
+        m_surfaceDescriptor.m_greenShift = 0;
+        m_surfaceDescriptor.m_blueShift = 0;
+        m_surfaceDescriptor.m_alphaShift = 0;
+        m_surfaceDescriptor.m_luminanceShift = alphaSize;
+        }
+    else
+        {
+        m_surfaceDescriptor.m_luminanceShift = 0;
+        /*  Found these from CPlatsimEGL::egliGetSymbianPixelFormat()
+            in platsim_graphics/platsimegl/src/platsimegl.cpp. Pixel format
+            should be transfered through serialization.
+
+            EUidPixelFormatARGB_8888
+            EUidPixelFormatARGB_8888_PRE
+            EUidPixelFormatXRGB_8888
+
+            EUidPixelFormatARGB_4444
+            EUidPixelFormatXRGB_4444
+
+            EUidPixelFormatRGB_565
+            EUidPixelFormatARGB_1555
+            
+            -- 
+            Harri
+        */
+        // \todo We need pixel format through serialization.
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+        m_surfaceDescriptor.m_blueShift = 0;
+        m_surfaceDescriptor.m_greenShift = blueSize;
+        m_surfaceDescriptor.m_redShift = blueSize + greenSize;
+        m_surfaceDescriptor.m_alphaShift = blueSize + greenSize + redSize;
+#else
+        // \note TeroP, changing these to match OpenVG color formats. This should make blitting
+        // to _win32_ window fast, but a solution for Symbian vs. Win32 native build should be
+        // defined.
+        // That is: This has to match the EGLtoVGInterface::CopyBuffers VGImageFormat somehow.
+        // Currently: VG_sARGB_8888_PRE;
+
+        m_surfaceDescriptor.m_blueShift = 0;
+        m_surfaceDescriptor.m_greenShift = blueSize;
+        m_surfaceDescriptor.m_redShift = blueSize + greenSize;
+        m_surfaceDescriptor.m_alphaShift = redSize + greenSize + blueSize;
+#endif //EGLI_USE_PLATSIM_EXTENSIONS
+        }
+    
+    m_surfaceDescriptor.m_maskSize = m_surfaceDescriptor.m_colorDescriptor.AlphaMaskSize();
+    m_surfaceDescriptor.m_stencilSize = m_config->GetAttribute( EGL_STENCIL_SIZE );
+    m_surfaceDescriptor.m_depthSize = m_config->GetAttribute( EGL_DEPTH_SIZE );
+    return &m_surfaceDescriptor;
+    }
+
+void CEGLSurface::SetAttribute( EGLint attrib, EGLint value )
+    {
+    switch( attrib )
+        {
+        case EGL_MIPMAP_LEVEL:
+            {
+            m_mipmapLevel = value;
+            break;
+            }
+        case EGL_MULTISAMPLE_RESOLVE:
+            {
+            m_multisampleResolve = value;
+            break;
+            }
+        case EGL_SWAP_BEHAVIOR:
+            {
+            m_swapBehavior = value;
+            break;
+            }
+        }
+    }
+
+EGLint CEGLSurface::Attribute( EGLint attrib ) const
+    {
+    EGLint ret = EGL_BAD_ATTRIBUTE;
+    switch( attrib )
+        {
+        case EGL_MIPMAP_LEVEL:
+            {
+            ret = m_mipmapLevel;
+            break;
+            }
+        case EGL_MULTISAMPLE_RESOLVE:
+            {
+            ret = m_multisampleResolve;
+            break;
+            }
+        case EGL_SWAP_BEHAVIOR:
+            {
+            ret = m_swapBehavior;
+            break;
+            }
+        }
+    return ret;
+    }
+
+void CEGLSurface::Lock()
+    {
+    CEGLOs::GetLock( &m_lock );
+    m_isLocked = true;
+    }
+void CEGLSurface::Unlock()
+    {
+    CEGLOs::ReleaseLock( &m_lock );
+    m_isLocked = false;
+    }
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLThread.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,126 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLThread.h"
+#include "EGLContext.h"
+#include "EGLSurface.h"
+
+CEGLThread::CEGLThread( EGLI_THREAD_ID threadId, EGLint supportedApis ) :
+    m_id( threadId ),
+    m_currentVGContext( NULL ),
+    m_currentVGSurface( NULL ),
+    m_currentGLESContext( NULL ),
+	m_currentGLESReadSurface( NULL ),
+    m_currentGLESDrawSurface( NULL ),
+    m_currentApi( EGL_OPENGL_ES_API ),
+    m_lastError( EGL_SUCCESS ),
+    m_supportedApis( supportedApis )
+    {
+    }
+
+CEGLThread::~CEGLThread(void)
+    {
+    }
+
+bool CEGLThread::IsSupportedApi( EGLenum api ) const
+    {
+    bool ret = false;
+    switch( api )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( m_supportedApis & EGL_OPENVG_BIT )
+                ret = true;
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            if( m_supportedApis & EGL_OPENGL_ES_BIT ||
+                m_supportedApis & EGL_OPENGL_ES2_BIT )
+                ret = true;
+            break;
+            }
+        }
+    return ret;
+    }
+
+CEGLContext* CEGLThread::SwitchVGContext( CEGLContext* vgContext )
+    {
+    CEGLContext* ret = m_currentVGContext;
+    if( vgContext != m_currentVGContext )
+        {
+        m_currentVGContext = vgContext;
+        if( vgContext ) vgContext->SetThread( this );
+        if( ret ) ret->SetThread( NULL );
+        }
+    return ret;
+    }
+
+CEGLSurface* CEGLThread::SwitchVGSurface( CEGLSurface* vgSurface )
+    {
+    CEGLSurface* ret = m_currentVGSurface;
+    if( vgSurface != m_currentVGSurface )
+        {
+        m_currentVGSurface = vgSurface;
+        if( vgSurface ) vgSurface->SetThread( this );
+        if( ret ) ret->SetThread( NULL );
+        }
+    return ret;
+    }
+
+CEGLContext* CEGLThread::SwitchGLESContext( CEGLContext* glesContext )
+    {
+    CEGLContext* ret = m_currentGLESContext;
+    if( glesContext != m_currentGLESContext )
+        {
+        m_currentGLESContext = glesContext;
+        if( glesContext ) glesContext->SetThread( this );
+        if( ret ) ret->SetThread( NULL );
+        }
+    return ret;
+    }
+
+void CEGLThread::SwitchGLESSurfaces( CEGLSurface* read, CEGLSurface* draw, CEGLSurface*& previousRead, CEGLSurface*& previousDraw )
+    {
+    previousRead = m_currentGLESReadSurface;
+    previousDraw = m_currentGLESDrawSurface;
+    m_currentGLESReadSurface = read;
+    if( read ) read->SetThread( this );
+    if( previousRead && previousRead != read ) previousRead->SetThread( NULL );
+    m_currentGLESDrawSurface = draw;
+    if( draw ) draw->SetThread( this );
+    if( previousDraw && previousDraw != draw ) previousDraw->SetThread( NULL );
+    }
+
+void CEGLThread::CurrentGLESSurfaces( CEGLSurface** read, CEGLSurface** draw ) const
+    {
+    if( read ) *read = m_currentGLESReadSurface;
+    if( draw ) *draw = m_currentGLESDrawSurface;
+    }
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLUtils.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,158 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLUtils.h"
+#include "EGLSurface.h"
+#include "EGLContext.h"
+#include "EGLImage.h"
+#include "EGLThread.h"
+#include "EGLProcess.h"
+#include "EGLConfig.h"
+#include "EGLDisplay.h"
+
+template<class T>
+void AddObject( std::vector<T*>& vector, T*& object )
+    {
+    if( !object ) return;
+    try
+        {
+        vector.push_back(object);
+        }
+    catch( std::bad_alloc )
+        {
+        delete object;
+        object = NULL;
+        }
+    }
+
+template<class T>
+T* FindObjectByPointer( const std::vector<T*>& vector, void* item, int* index )
+    {
+    T* ret = NULL;
+    for( typename std::vector<T*>::size_type i = 0; i < vector.size(); i++ )
+        {
+        if( vector[i] == item )
+            {
+            ret = vector[i];
+            if( index ) *index = i;
+            break;
+            }
+        }
+    return ret;
+    }
+
+template<class T>
+T* FindObjectById( const std::vector<T*>& vector, EGLint id, int* index )
+    {
+    T* ret = NULL;
+    for( typename std::vector<T*>::size_type i = 0; i < vector.size(); i++ )
+        {
+        if( vector[i]->Id() == id )
+            {
+            ret = vector[i];
+            if( index ) *index = i;
+            break;
+            }
+        }
+    return ret;
+    }
+
+template<class T>
+void DeleteObjectByPointer( std::vector<T*>& vector, void* item )
+    {
+    int index;
+    T* object = FindObjectByPointer<T>( vector, item, &index );
+    if( object )
+        {
+        delete object;
+        vector.erase( vector.begin() + index );
+        }
+    }
+
+template<class T>
+void DeleteObjectById( std::vector<T*>& vector, EGLint id )
+    {
+    int index;
+    T* object = FindObjectById<T>(vector, id, &index );
+    if( object && object->Id() == id )
+        {
+        delete object;
+        vector.erase( vector.begin() + index );
+        }
+    }
+
+template<class T>
+void DestroyPointerVector( std::vector<T*>& vector )
+    {
+    for(typename std::vector<T*>::iterator iter = vector.begin(); iter != vector.end(); iter++)
+        {
+        delete (*iter);
+        }
+    vector.clear();
+    }
+
+// CEGLSurface
+template void AddObject( std::vector<class CEGLSurface*>& vector, class CEGLSurface*& object );
+template class CEGLSurface* FindObjectByPointer( const std::vector<class CEGLSurface*>& vector, void* item, int* index );
+template void DeleteObjectByPointer( std::vector<class CEGLSurface*>& vector, void* item );
+template void DestroyPointerVector( std::vector<class CEGLSurface*>& vector );
+
+// CEGLContext
+template void AddObject( std::vector<class CEGLContext*>& vector, class CEGLContext*& object );
+template void DeleteObjectByPointer( std::vector<class CEGLContext*>& vector, void* item );
+template void DestroyPointerVector( std::vector<class CEGLContext*>& vector );
+
+// CEGLImage
+template void AddObject( std::vector<class CEGLImage*>& vector, class CEGLImage*& object );
+template void DeleteObjectByPointer( std::vector<class CEGLImage*>& vector, void* item );
+template void DestroyPointerVector( std::vector<class CEGLImage*>& vector );
+
+// CEGLThread
+template void AddObject( std::vector<class CEGLThread*>& vector, class CEGLThread*& object );
+template void DeleteObjectById( std::vector<class CEGLThread*>& vector, EGLint id );
+template void DestroyPointerVector( std::vector<class CEGLThread*>& vector );
+template class CEGLThread* FindObjectById( const std::vector<class CEGLThread*>& vector, EGLint id, int* index );
+
+// CEGLProcess
+template void AddObject( std::vector<class CEGLProcess*>& vector, class CEGLProcess*& object );
+template void DestroyPointerVector( std::vector<class CEGLProcess*>& vector );
+template void DeleteObjectById( std::vector<class CEGLProcess*>& vector, EGLint id );
+
+// CEGLDisplay
+template void AddObject( std::vector<class CEGLDisplay*>& vector, class CEGLDisplay*& object );
+template class CEGLDisplay* FindObjectByPointer( const std::vector<class CEGLDisplay*>& vector, void* item, int* index );
+template void DeleteObjectByPointer( std::vector<class CEGLDisplay*>& vector, void* item );
+template void DestroyPointerVector( std::vector<class CEGLDisplay*>& vector );
+
+// CEGLConfig
+template void AddObject( std::vector<class CEGLConfig*>& vector, class CEGLConfig*& object );
+template class CEGLConfig* FindObjectByPointer( const std::vector<class CEGLConfig*>& vector, void* item, int* index );
+template class CEGLConfig* FindObjectById( const std::vector<class CEGLConfig*>& vector, EGLint id, int* index );
+template void DestroyPointerVector( std::vector<class CEGLConfig*>& vector );
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/EGLWindowSurface.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,104 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLWindowSurface.h"
+#include "EGLConfig.h"
+#include "ColorDescriptor.h"
+#include "EGLOs.h"
+
+// \todo Use new[]/free[] instead?
+#include <stdlib.h>
+
+CEGLWindowSurface::CEGLWindowSurface() :
+    CEGLSurface( CEGLSurface::WINDOW_SURFACE,
+                 0,
+                 0,
+                 0,
+                 NULL ),
+    m_buffer0( NULL ),
+    m_buffer1( NULL ),
+    m_currentBuffer( NULL ),
+    m_swapInterval( 1 ),
+    m_osContext( NULL )
+    {
+    }
+
+CEGLWindowSurface::CEGLWindowSurface( CEGLConfig* config, EGLint colorSpace, EGLint alphaFormat, EGLint renderBuffer, EGLIOsWindowContext* osContext) :
+    CEGLSurface( CEGLSurface::WINDOW_SURFACE,
+                 colorSpace,
+                 alphaFormat,
+                 renderBuffer,
+                 config ),
+    m_buffer0( NULL ),
+    m_buffer1( NULL ),
+    m_currentBuffer( NULL ),
+    m_swapInterval( 1 ),
+    m_osContext( osContext )
+    {
+    EGLI_ASSERT( m_osContext != NULL );
+    }
+
+CEGLWindowSurface::~CEGLWindowSurface(void)
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( m_currentBuffer ) free( m_currentBuffer );
+#endif
+    if( m_osContext )
+        CEGLOs::DestroyOSWindowContext( m_osContext );
+    }
+
+void* CEGLWindowSurface::CurrentBuffer()
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    m_currentBuffer = (m_currentBuffer && m_currentBuffer == m_buffer0) ? m_buffer1 : m_buffer0;
+    EGLI_ASSERT( m_currentBuffer != NULL );
+    return m_currentBuffer;
+#else
+    if( !m_currentBuffer || m_osContext->width != Width() || m_osContext->height != Height() )
+        {
+        if( m_currentBuffer ) free( m_currentBuffer );
+        m_currentBuffer = malloc(m_height*m_stride);
+        }
+    return m_currentBuffer;//NULL;
+#endif
+    }
+
+void CEGLWindowSurface::SetSwapInterval( EGLint interval )
+    {
+    // \todo MIN, MAX
+    m_swapInterval = interval;
+    }
+
+void CEGLWindowSurface::SetOsContext( EGLIOsWindowContext* osContext ) 
+    {
+    if( m_osContext )
+        CEGLOs::DestroyOSWindowContext( m_osContext );
+    m_osContext = osContext;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/TransparentColor.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,72 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "TransparentColor.h"
+
+CTransparentColor::~CTransparentColor(void)
+    {
+    }
+
+CTransparentColor::CTransparentColor( EGLint type, EGLint redValue, EGLint greenValue, EGLint blueValue ) :
+    m_transparentType( type ),
+    m_redValue( redValue ),
+    m_greenValue( greenValue ),
+    m_blueValue( blueValue )
+    {
+    }
+
+void CTransparentColor::SetAttribute( EGLint attribute, EGLint value )
+    {
+    switch( attribute )
+        {
+        case EGL_TRANSPARENT_TYPE:
+            {
+            m_transparentType = value;
+            break;
+            }
+        case EGL_TRANSPARENT_RED_VALUE:
+            {
+            m_redValue = value;
+            break;
+            }
+        case EGL_TRANSPARENT_GREEN_VALUE:
+            {
+            m_greenValue = value;
+            break;
+            }
+        case EGL_TRANSPARENT_BLUE_VALUE:
+            {
+            m_blueValue = value;
+            break;
+            }
+        default:
+            EGLI_ASSERT( false );
+        }
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/eglapi.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2660 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include <string.h>
+#include <algorithm>
+#include <EGL/egl.h>
+#include "eglDefinitions.h"
+#include "eglInternal.h"
+#include "EGLState.h"
+#include "EGLProcess.h"
+#include "EGLDisplay.h"
+#include "EGLThread.h"
+#include "EGLContext.h"
+#include "EGLConfig.h"
+#include "EGLWindowSurface.h"
+#include "EGLPbufferSurface.h"
+#include "ColorDescriptor.h"
+#include "SurfaceDescriptor.h"
+#include "EGLExtension.h"
+#include "EGLOs.h"
+
+#if defined(_WIN32)
+#include <windows.h>
+#else
+    // \todo other platforms
+#endif
+
+#if defined(_WIN32) && !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+static DWORD g_tlsIndex = TLS_OUT_OF_INDEXES;
+#endif
+
+static CEGLState* g_eglState = NULL;
+static bool g_lockInitialized = false;
+EGLI_LOCK g_eglLock;
+
+CEGLState* getState()
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( !g_eglState )
+        {
+        g_eglState = EGLI_NEW CEGLState();
+        if( !g_eglState )
+            {
+            return NULL;
+            }
+        if( !(g_eglState->Initialize()) )
+            {
+            delete g_eglState;
+            g_eglState = NULL;
+            return NULL;
+            }
+        g_eglState->AddRef();
+        }
+    return g_eglState;
+#elif defined(_WIN32)
+    CEGLOs::GetLock( &g_eglLock );
+    if( !g_eglState )
+        {
+        g_eglState = EGLI_NEW CEGLState();
+        if( !g_eglState )
+            {
+            CEGLOs::ReleaseLock( &g_eglLock );
+            return NULL;
+            }
+        if( !(g_eglState->Initialize()) )
+            {
+            delete g_eglState;
+            g_eglState = NULL;
+            CEGLOs::ReleaseLock( &g_eglLock );
+            return NULL;
+            }
+        }
+    EGLI_ASSERT( g_tlsIndex != TLS_OUT_OF_INDEXES );
+    if( g_tlsIndex == TLS_OUT_OF_INDEXES )
+        {
+        CEGLOs::ReleaseLock( &g_eglLock );
+        return NULL;
+        }
+    CEGLThread* thread = (CEGLThread*)TlsGetValue( g_tlsIndex );
+    if( g_eglState && !thread )
+        {
+        // \todo Remove CEGLProcess when platsim extensions are not needed any more
+        thread = g_eglState->GetCurrentProcess()->AddThread( GetCurrentThreadId(), true, g_eglState->SupportedApis() );
+        if( !thread ) 
+            {
+            CEGLOs::ReleaseLock( &g_eglLock );
+            return NULL;
+            }
+        if( !(TlsSetValue( g_tlsIndex, (void *)thread )) )
+            {
+            CEGLOs::ReleaseLock( &g_eglLock );
+            return NULL;
+            }
+        g_eglState->AddRef();
+        }
+    CEGLOs::ReleaseLock( &g_eglLock );
+    return g_eglState;
+#else // Linux
+    // \todo
+    return NULL;
+#endif
+    }
+
+static void releaseState()
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( g_eglState )
+        {
+        if( g_eglState->RemoveRef() )
+            {
+            delete g_eglState;
+            g_eglState = NULL;
+            }
+        }
+#elif defined(_WIN32)
+    CEGLOs::GetLock( &g_eglLock );
+    if( g_eglState )
+        {
+        g_eglState->GetCurrentProcess()->RemoveThread( GetCurrentThreadId() );
+        EGLI_ASSERT( g_tlsIndex != TLS_OUT_OF_INDEXES );
+        if( g_tlsIndex != TLS_OUT_OF_INDEXES )
+            {
+            TlsSetValue( g_tlsIndex, 0 );
+            }
+        }
+    if( g_eglState && g_eglState->RemoveRef() )
+        {
+        delete g_eglState;
+        g_eglState = NULL;
+        }
+    CEGLOs::ReleaseLock( &g_eglLock );
+#else // Linux
+    // \todo
+    EGLI_ASSERT( false );
+#endif
+    }
+
+/*static*/ CEGLThread* getThread()
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    CEGLState* state = getState();
+    CEGLProcess* process = state->GetCurrentProcess();
+    if( process )
+        {
+        return process->CurrentThread();
+        }
+    return NULL;
+#elif defined(_WIN32)
+    EGLI_ASSERT( g_tlsIndex != TLS_OUT_OF_INDEXES );
+    if( g_tlsIndex == TLS_OUT_OF_INDEXES )
+        return NULL;
+    CEGLThread* thread = (CEGLThread*)TlsGetValue( g_tlsIndex );
+    if( !thread && GetLastError() == ERROR_SUCCESS )
+        {
+        // TlsGetValue() succeeded but didn't have thread => create one now
+        CEGLState* state = getState();
+        if( state ) 
+            {
+            thread = (CEGLThread*)TlsGetValue( g_tlsIndex );
+            }
+        }
+    return thread;
+#else // Linux
+    // \todo
+    EGLI_ASSERT( false );
+#endif
+    } 
+
+void setEGLError( EGLint error )
+    {
+    CEGLThread* thread = getThread();
+    if( thread )
+        {
+        thread->SetError( error );
+        }
+    }
+
+#define EGLI_GET_DISPLAY_RET(id,ret)\
+    CEGLDisplay* display = state->GetDisplay( id );\
+    if( !display )\
+        {\
+        EGLI_LEAVE_RET( ret, EGL_BAD_DISPLAY );\
+        }\
+    EGLI_ASSERT( display->ProcessId() == process->Id() );\
+    if( !(display->IsInitialized()) )\
+        {\
+        EGLI_LEAVE_RET( ret, EGL_NOT_INITIALIZED );\
+        }
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*When there is no status to return (in other words, when eglGetError is called
+as the first EGL call in a thread, or immediately after calling eglReleaseThread),
+EGL_SUCCESS will be returned.*/
+EGLAPI EGLint EGLAPIENTRY eglGetError(void)
+    {
+    EGLint err = EGL_SUCCESS;
+    CEGLThread* thread = getThread();
+    if( thread )
+        {
+        err = thread->Error();
+        thread->SetError( EGL_SUCCESS );
+        }
+    else
+        {
+        err = EGL_BAD_ALLOC;
+        }
+    return err;
+    }
+
+EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id)
+    {
+    EGLI_ENTER_RET( EGL_NO_DISPLAY );
+
+	if( display_id == EGL_DEFAULT_DISPLAY )
+		{
+		display_id = (EGLNativeDisplayType)state->DefaultDisplay();
+		}
+
+    CEGLDisplay* display = state->GetDisplayByNativeType( (EGLINativeDisplayType)display_id, process->Id() );
+    if( !display )
+        {
+        if( !(CEGLOs::IsValidNativeDisplay( (EGLINativeDisplayType)display_id )) )
+            {
+            EGLI_LEAVE_RET( EGL_NO_DISPLAY, EGL_BAD_PARAMETER );
+            }
+        display = state->AddDisplay( (EGLINativeDisplayType)display_id, process->Id() );
+        if( !display )
+            {
+            EGLI_LEAVE_RET( EGL_NO_DISPLAY, EGL_BAD_ALLOC );
+            }
+		display->AddRef();
+        }
+    EGLI_LEAVE_RET( (EGLDisplay)display, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+
+    CEGLDisplay* display = state->GetDisplay( dpy );
+    if( !display )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_DISPLAY );
+        }
+
+    if( !(display->IsInitialized()) && !(display->Initialize()) )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_NOT_INITIALIZED );
+        }
+
+    if( major ) *major = 1;
+    if( minor ) *minor = 4;
+
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglTerminate(EGLDisplay dpy)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    CEGLDisplay* display = state->GetDisplay( dpy );
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( display && display->ProcessId() != process->Id() )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_DISPLAY );
+        }
+#endif
+    if( !display )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_DISPLAY );
+        }
+
+    if( !(display->IsInitialized()) )
+        {
+        EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+        }
+    display->RemoveRef();
+    if( display->TerminateDisplay() )
+        {
+        state->RemoveDisplay( display );
+        }
+
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+/*
+    eglQueryString returns a pointer to a static, zero-terminated string describing
+    some aspect of the EGL implementation running on the specified display. name
+    may be one of EGL_CLIENT_APIS, EGL_EXTENSIONS, EGL_VENDOR, or EGL_-
+    VERSION.
+    The EGL_CLIENT_APIS string describes which client rendering APIs are
+    supported. It is zero-terminated and contains a space-separated list of API
+    names, which must include at least one of ‘‘OpenGL’’, ‘‘OpenGL_ES’’ or
+    ‘‘OpenVG’’.
+    The EGL_EXTENSIONS string describes which EGL extensions are supported
+    by the EGL implementation running on the specified display. The string is zeroterminated
+    and contains a space-separated list of extension names; extension names
+    themselves do not contain spaces. If there are no extensions to EGL, then the empty
+    string is returned.
+    The format and contents of the EGL_VENDOR string is implementation dependent.
+    The format of the EGL_VERSION string is:
+    <major version.minor version><space><vendor specific info>
+*/
+
+EGLAPI const char * EGLAPIENTRY eglQueryString(EGLDisplay dpy, EGLint name)
+    {
+    EGLI_ENTER_RET( NULL );
+    EGLI_GET_DISPLAY_RET( dpy, NULL );
+
+    const char* ret = NULL;
+    switch(name)
+        {
+        case EGL_CLIENT_APIS:
+            {
+            switch( state->SupportedApis() )
+                {
+                case EGL_OPENVG_BIT | EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT:
+                    {
+                    ret = "OpenVG OpenGL_ES OpenGL_ES2";
+                    break;
+                    }
+
+                case EGL_OPENVG_BIT | EGL_OPENGL_ES_BIT:
+                    {
+                    ret = "OpenVG OpenGL_ES";
+                    break;
+                    }
+
+                case EGL_OPENVG_BIT | EGL_OPENGL_ES2_BIT:
+                    {
+                    ret = "OpenVG OpenGL_ES2";
+                    break;
+                    }
+
+                case EGL_OPENVG_BIT:
+                    {
+                    ret = "OpenVG";
+                    break;
+                    }
+
+                case EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT:
+                    {
+                    ret = "OpenGL_ES OpenGL_ES2";
+                    break;
+                    }
+
+                case EGL_OPENGL_ES_BIT:
+                    {
+                    ret = "OpenGL_ES";
+                    break;
+                    }
+
+                case EGL_OPENGL_ES2_BIT:
+                    {
+                    ret = "OpenGL_ES2";
+                    break;
+                    }
+
+                default:
+                    {
+                    ret = "";
+                    break;
+                    }
+                }
+            break;
+            }
+        case EGL_EXTENSIONS:
+            {
+            // TODO
+            ret = "EGL_KHR_image_base";
+            break;
+            }
+        case EGL_VENDOR:
+            {
+            ret = "Nokia";
+            break;
+            }
+        case EGL_VERSION:
+            {
+            ret ="1.4 PlatSim";
+            break;
+            }
+
+        default:
+            {
+            EGLI_LEAVE_RET( NULL, EGL_BAD_PARAMETER );
+            break;
+            }
+        }
+    EGLI_LEAVE_RET( ret, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs(EGLDisplay dpy, EGLConfig *configs,
+			 EGLint config_size, EGLint *num_config)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    if( !num_config )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_PARAMETER );
+        }
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+
+    EGLint configCount = state->ConfigCount();
+    if( !configs )
+        {
+        *num_config = configCount;
+        EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+        }
+
+    *num_config = EGLI_MIN( configCount, config_size );
+
+    state->FillConfigs( configs, *num_config );
+
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list,
+			   EGLConfig *configs, EGLint config_size,
+			   EGLint *num_config)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+
+    CColorDescriptor* colorDesc = EGLI_NEW CColorDescriptor( 0, 0, 0, 0, true, 0, false, 0, 0 );
+    if( !colorDesc )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ALLOC );
+        }
+    colorDesc->SetAttribute( EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER );
+    CEGLConfig* filter = EGLI_NEW CEGLConfig(
+                    *colorDesc,
+                    EGL_DONT_CARE,  
+                    EGL_DONT_CARE,
+                    EGL_DONT_CARE,
+                    EGL_DONT_CARE,
+                    0, 0, 0,
+                    EGL_DONT_CARE,
+                    EGL_DONT_CARE,
+                    EGL_DONT_CARE,
+                    EGL_DONT_CARE,
+                    EGL_OPENGL_ES_BIT,
+                    0, 0, 0,
+                    EGL_WINDOW_BIT,
+                    NULL );          // transparent color    
+    delete colorDesc;
+    colorDesc = NULL;
+    if( !filter )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ALLOC );
+        }
+
+    EGLint configId = 0;
+    EGLint matchPixmap = EGL_NONE;
+
+    if( attrib_list && attrib_list[0] != EGL_NONE )
+        {
+        for( EGLint i=0; attrib_list[i] != EGL_NONE && configId == 0; i+=2 )
+            {
+            switch( attrib_list[i] )
+                {
+                case EGL_NATIVE_VISUAL_ID:
+                case EGL_MAX_PBUFFER_HEIGHT:
+                case EGL_MAX_PBUFFER_PIXELS:
+                case EGL_MAX_PBUFFER_WIDTH:
+                    {
+                    // IGNORED
+                    break;
+                    }
+
+                case EGL_CONFIG_ID:
+                    {
+                    configId = attrib_list[i+1];
+                    break;
+                    }
+                    
+                case EGL_MATCH_NATIVE_PIXMAP:
+                    {
+                    matchPixmap = attrib_list[i+1];
+                    break;
+                    }
+                default:
+                    {
+                    if( !(filter->SetAttribute(attrib_list[i], attrib_list[i+1])) )
+                        {
+                        delete filter;
+                        filter = NULL;
+                        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ATTRIBUTE );
+                        }
+                    }
+                }
+            }
+        }
+
+    if( configId > 0 )
+        {
+        CEGLConfig* config = state->FindConfigById( configId );
+        if( !config )
+            {
+            delete filter;
+            filter = NULL;
+            // TODO: is this correct error code? 
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ALLOC ); 
+            }
+        *num_config = 1;
+        configs[0] = (EGLConfig)config;
+        delete filter;
+        filter = NULL;
+        EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+        }
+
+    if( matchPixmap != EGL_NONE )
+        {
+        // eglChooseConfig – only pbuffer supported, so no need for EGL_MATCH_NATIVE_PIXMAP
+        }
+    
+    *num_config = state->MatchConfigs( filter, configs, config_size );
+    delete filter;
+    filter = NULL;
+    
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib(EGLDisplay dpy, EGLConfig configId,
+			      EGLint attribute, EGLint *value)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+    if( !value )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_PARAMETER );
+        }
+    CEGLConfig* config = state->GetConfig( configId );
+    if( !config )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_CONFIG );
+        }
+    EGLint val = config->GetAttribute( attribute );
+    if( val == EGL_BAD_ATTRIBUTE )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, val );
+        }
+    *value = val;
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+
+EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface(EGLDisplay dpy, EGLConfig configId,
+				  EGLNativeWindowType win,
+				  const EGLint *attrib_list)
+    {
+    EGLI_ENTER_RET( EGL_NO_SURFACE );
+    EGLI_GET_DISPLAY_RET ( dpy, EGL_NO_SURFACE );
+    // \todo eglCreateWindowSurface – EGL_BAD_MATCH raised (as no window-supporting configs)
+    CEGLConfig* config = state->GetConfig( configId );
+    if( !config )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_CONFIG );
+        }
+    EGLint surfaceType = config->GetAttribute( EGL_SURFACE_TYPE );
+    if( !(surfaceType & EGL_WINDOW_BIT) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_MATCH );
+        }
+    CEGLSurface* surface = display->GetSurfaceByNativeType( (EGLINativeWindowType)win );
+    if( surface && surface->Config() == config )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+
+	EGLint renderBuffer = EGL_BACK_BUFFER;
+	EGLint colorSpace = EGL_VG_COLORSPACE_sRGB;
+	EGLint alphaFormat = EGL_VG_ALPHA_FORMAT_NONPRE;
+    EGLint renderableType = config->GetAttribute( EGL_RENDERABLE_TYPE );
+	if( attrib_list && attrib_list[0] != EGL_NONE )
+	    {
+		for( int i=0; attrib_list[i] != EGL_NONE; i+=2 )
+		    {
+			switch( attrib_list[i] )
+			    {
+			    case EGL_RENDER_BUFFER:
+				    renderBuffer = attrib_list[i+1];
+				    break;
+
+			    case EGL_VG_COLORSPACE:
+                    if( !(renderableType & EGL_OPENVG_BIT) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+				    colorSpace = attrib_list[i+1];
+				    break;
+
+			    case EGL_VG_ALPHA_FORMAT:
+                    if( !(renderableType & EGL_OPENVG_BIT) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+				    alphaFormat = attrib_list[i+1];
+				    break;
+
+			    default:
+				    EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                }
+            }
+        }
+	
+    if( !(surfaceType & colorSpace) || !(surfaceType & alphaFormat) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_MATCH );
+        }
+    
+    if( !CEGLOs::IsValidNativeWindow( win ) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_NATIVE_WINDOW );
+        }
+
+    EGLIOsWindowContext* osContext = CEGLOs::CreateOSWindowContext( win, *config );
+    if( !osContext )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    
+    surface = EGLI_NEW CEGLWindowSurface( config, colorSpace, alphaFormat, renderBuffer, osContext );
+    if( !surface )
+        {
+        CEGLOs::DestroyOSWindowContext( osContext );
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    // \note AddSurface() will destroy the object if it fails to take ownership
+    surface = display->AddSurface( surface );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    int width = 0;
+    int height = 0;
+    if( !CEGLOs::GetNativeWindowSize( win, width, height ) ||
+        !(surface->Resize( width, height )) )
+        {
+        // \note RemoveSurface() will destroy the object
+        display->RemoveSurface( surface );
+        // \todo Is this correct error?
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    if( (state->SupportedApis() & EGL_OPENVG_BIT) && (renderableType & EGL_OPENVG_BIT) )
+        {
+        SurfaceDescriptor* surfaceDesc = surface->Descriptor();
+        if( !(state->VGInterface()->CreateSurface( surfaceDesc, surface->VGBuffers(), NULL )) )
+            {
+            // \note RemoveSurface() will destroy the object
+            display->RemoveSurface( surface );
+            EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+            }
+        }
+#endif // EGLI_USE_PLATSIM_EXTENSIONS
+
+    surface->AddRef();
+
+    EGLI_LEAVE_RET( (EGLSurface)surface, EGL_SUCCESS );
+    }
+
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig configId,
+				   const EGLint *attrib_list)
+    {
+    // \todo combine with eglCreatePbufferFromClientBuffer()
+    EGLI_ENTER_RET( EGL_NO_SURFACE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_NO_SURFACE );
+    CEGLConfig* config = state->GetConfig( configId );
+    if( !config )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_CONFIG );
+        }
+
+    if( !(config->GetAttribute( EGL_SURFACE_TYPE ) & EGL_PBUFFER_BIT) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_MATCH );
+        }
+    
+    EGLint width = 0;
+    EGLint height = 0;
+    EGLint textureFormat = EGL_NO_TEXTURE;
+    EGLint textureTarget = EGL_NO_TEXTURE;
+    EGLint mipmapTexture = EGL_FALSE;
+    EGLint largestPbuffer = EGL_FALSE;
+    EGLint colorSpace = EGL_VG_COLORSPACE_sRGB;
+    EGLint alphaFormat = EGL_VG_ALPHA_FORMAT_NONPRE;
+
+    EGLint renderableType = config->GetAttribute( EGL_RENDERABLE_TYPE );
+    if( attrib_list && attrib_list[0] != EGL_NONE )
+        {
+        for( int i=0; attrib_list[i] != EGL_NONE; i+=2 )
+            {
+            EGLint value = attrib_list[i+1];
+            switch( attrib_list[i] )
+                {
+                case EGL_WIDTH:
+                    {
+                    if( value < 0 )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_PARAMETER );
+                        }
+                    width = value;
+                    break;
+                    }
+
+                case EGL_HEIGHT:
+                    {
+                    if( value < 0 )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_PARAMETER );
+                        }
+                    height = value;
+                    break;
+                    }
+
+                case EGL_LARGEST_PBUFFER:
+                    {
+                    largestPbuffer = value;
+                    break;
+                    }
+
+                case EGL_TEXTURE_FORMAT:
+                    {
+                    if( !(renderableType & EGL_OPENGL_ES_BIT) &&
+                        !(renderableType & EGL_OPENGL_ES2_BIT) ||
+                        (value != EGL_TEXTURE_RGB &&
+                         value != EGL_TEXTURE_RGBA &&
+                         value != EGL_NO_TEXTURE) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+                    textureFormat = value;
+                    break;
+                    }
+
+                case EGL_TEXTURE_TARGET:
+                    {
+                    if( !(renderableType & EGL_OPENGL_ES_BIT) &&
+                        !(renderableType & EGL_OPENGL_ES2_BIT) ||
+                        (value != EGL_TEXTURE_2D &&
+                         value != EGL_NO_TEXTURE) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+                    textureTarget = value;
+                    break;
+                    }
+
+                case EGL_MIPMAP_TEXTURE:
+                    {
+                    if( !(renderableType & EGL_OPENGL_ES_BIT) ||
+                        !(renderableType & EGL_OPENGL_ES2_BIT) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+                    mipmapTexture = value;
+                    break;
+                    }
+
+                case EGL_VG_COLORSPACE:
+                    {
+                    if( !(renderableType & EGL_OPENVG_BIT) ||
+                        (value != EGL_VG_COLORSPACE_sRGB &&
+                         value != EGL_VG_COLORSPACE_LINEAR) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+                    colorSpace = value;
+                    break;
+                    }
+
+                case EGL_VG_ALPHA_FORMAT:
+                    {
+                    if( !(renderableType & EGL_OPENVG_BIT) ||
+                        (value != EGL_VG_ALPHA_FORMAT_PRE &&
+                         value != EGL_VG_ALPHA_FORMAT_NONPRE) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+                    alphaFormat = value;
+                    break;
+                    }
+
+                default:
+                    EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                }
+            }
+        }
+
+    if( (textureFormat == EGL_NO_TEXTURE && textureTarget != EGL_NO_TEXTURE) ||
+        (textureFormat != EGL_NO_TEXTURE && textureTarget == EGL_NO_TEXTURE) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_MATCH );
+        }
+
+    CEGLPbufferSurface* surface = EGLI_NEW CEGLPbufferSurface( colorSpace, alphaFormat,
+        EGL_BACK_BUFFER, config, largestPbuffer, textureFormat, textureTarget, mipmapTexture );
+    // \note AddSurface() will destroy the object if it fails to take ownership
+    surface = (CEGLPbufferSurface*)display->AddSurface( surface );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    if( !(surface->Resize(width, height)) )
+        {
+        display->RemoveSurface( surface );
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    // \todo refactor all this surface creation stuff
+    if( (renderableType & EGL_OPENVG_BIT) && (state->SupportedApis() & EGL_OPENVG_BIT) )
+        {
+        // \todo Delay surface creation until needed.
+        // \todo largest Pbuffer
+        if( !(state->VGInterface()->CreateSurface( surface->Descriptor(), surface->VGBuffers(), NULL )) )
+            {
+            // \note RemoveSurface() will destroy the object
+            display->RemoveSurface( surface );
+            EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+            }
+        }
+
+    if( renderableType & EGL_OPENGL_ES_BIT && (state->SupportedApis() & EGL_OPENGL_ES_BIT) )
+        {
+        struct EGLINativePbufferContainer* nativePbuffer = CEGLOs::CreateNativePbuffer( display->NativeType(),
+            *config, width, height, largestPbuffer, textureFormat, textureTarget );
+        if( !nativePbuffer )
+            {
+            if( surface->VGClientSurface() )
+                {
+                state->VGInterface()->ReleaseSurface( surface->VGClientSurface() );
+                }
+            // \note RemoveSurface() will destroy the object
+            display->RemoveSurface( surface );
+            EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+            }
+        surface->SetNativePbufferContainer( nativePbuffer );
+        }
+
+    if( renderableType & EGL_OPENGL_ES2_BIT && (state->SupportedApis() & EGL_OPENGL_ES2_BIT) )
+        {
+        struct EGLINativePbufferContainer* nativePbuffer = CEGLOs::CreateNativePbuffer( display->NativeType(),
+            *config, width, height, largestPbuffer, textureFormat, textureTarget );
+        if( !nativePbuffer )
+            {
+            if( surface->VGClientSurface() )
+                {
+                state->VGInterface()->ReleaseSurface( surface->VGClientSurface() );
+                }
+            // \note RemoveSurface() will destroy the object
+            display->RemoveSurface( surface );
+            EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+            }
+        surface->SetNativePbufferContainer( nativePbuffer );
+        }
+
+    surface->AddRef();
+
+    EGLI_LEAVE_RET( (EGLSurface)surface, EGL_SUCCESS );
+    }
+
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config,
+				  EGLNativePixmapType pixmap,
+				  const EGLint *attrib_list)
+    {
+    EGLI_ENTER_RET( EGL_NO_SURFACE );
+    // eglCreatePixmapSurface – EGL_BAD_MATCH raised (as no pixmap-supporting configs)
+    EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_MATCH );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface(EGLDisplay dpy, EGLSurface surfaceId)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+    CEGLSurface* surface = display->GetSurface( surfaceId );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+
+    // \note EGLI_ENTER_RET macro will fail if thread allocation didn't succeed
+    CEGLThread* thread = getThread();
+
+    surface->Lock();
+    //TODO: client apis
+    if( surface->RemoveRef() )
+        {
+        if( surface->VGClientSurface() )
+            {
+            if( !(state->VGInterface()->ReleaseSurface(surface->VGClientSurface())) )
+                {
+                // need to add reference because surface is still alive
+                surface->AddRef();
+                surface->Unlock();
+                // \todo error code?
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+                }
+            }
+        // \note RemoveSurface() will destroy the object
+        display->RemoveSurface( surface );
+        surface = NULL;
+        }
+    else
+        {
+        surface->Terminate();
+        }
+    if( surface ) surface->Unlock();
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface(EGLDisplay dpy, EGLSurface surfaceId,
+				  EGLint attribute, EGLint *value)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    if( !value )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_PARAMETER );
+        }
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+    
+    CEGLSurface* surface = display->GetSurface( surfaceId );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+    surface->Lock();
+    EGLint ret = EGL_BAD_ATTRIBUTE;
+    switch( attribute )
+        {
+        case EGL_VG_ALPHA_FORMAT:
+            {
+            ret = surface->AlphaFormat();
+            break;
+            }
+        case EGL_VG_COLORSPACE:
+            {
+            ret = surface->ColorSpace();
+            break;
+            }
+        case EGL_CONFIG_ID:
+            {
+            ret = surface->Config()->Id();
+            break;
+            }
+        case EGL_HEIGHT:
+            {
+            ret = surface->Height();
+            break;
+            }
+        case EGL_WIDTH:
+            {
+            ret = surface->Width();
+            break;
+            }
+        case EGL_HORIZONTAL_RESOLUTION:
+            {
+            if( surface->Type() == CEGLSurface::WINDOW_SURFACE )
+                {
+                //TODO
+                EGLI_ASSERT( false );
+                }
+            else
+                {
+                ret = EGL_UNKNOWN;
+                }
+            break;
+            }
+        case EGL_VERTICAL_RESOLUTION:
+            {
+            if( surface->Type() == CEGLSurface::WINDOW_SURFACE )
+                {
+                //TODO
+                EGLI_ASSERT( false );
+                }
+            else
+                {
+                ret = EGL_UNKNOWN;
+                }
+            break;
+            }
+        case EGL_PIXEL_ASPECT_RATIO:
+            {
+            if( surface->Type() == CEGLSurface::WINDOW_SURFACE )
+                {
+                //TODO
+                EGLI_ASSERT( false );
+                }
+            else
+                {
+                ret = EGL_UNKNOWN;
+                }
+            break;
+            }
+        case EGL_LARGEST_PBUFFER:
+            {
+            if( surface->Type() == CEGLSurface::PBUFFER_SURFACE )
+                {
+                ret = ((CEGLPbufferSurface*)surface)->IsLargestPbuffer();
+                }            
+            break;
+            }
+        case EGL_MIPMAP_TEXTURE:
+            {
+            if( surface->Type() == CEGLSurface::PBUFFER_SURFACE )
+                {
+				ret = ((CEGLPbufferSurface*)surface)->MipmapTexture();
+                }
+            break;
+            }
+        case EGL_MIPMAP_LEVEL:
+            {
+            if( surface->Type() == CEGLSurface::PBUFFER_SURFACE )
+                {
+                ret = surface->MipmapLevel();
+                }
+            break;
+            }
+        case EGL_MULTISAMPLE_RESOLVE:
+            {
+            ret = surface->MultisampleResolve();
+            break;
+            }
+        case EGL_RENDER_BUFFER:
+            {
+            ret = surface->RenderBuffer();
+            break;
+            }
+        case EGL_SWAP_BEHAVIOR:
+            {
+            ret = surface->SwapBehavior();
+            break;
+            }
+        case EGL_TEXTURE_FORMAT:
+            {
+            if( surface->Type() == CEGLSurface::PBUFFER_SURFACE )
+                {
+				ret = ((CEGLPbufferSurface*)surface)->TextureFormat();
+                }
+            break;
+            }
+        case EGL_TEXTURE_TARGET:
+            {
+            if( surface->Type() == CEGLSurface::PBUFFER_SURFACE )
+                {
+                ret = ((CEGLPbufferSurface*)surface)->TextureTarget();
+                }
+            break;
+            }
+        default:
+            {
+            surface->Unlock();
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ATTRIBUTE );
+            }
+        }
+    *value = ret;
+    surface->Unlock();
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+
+EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI(EGLenum api)
+    {    
+    CEGLThread* thread = getThread();
+    EGLI_ASSERT( thread != NULL );
+    
+    if( thread && thread->IsSupportedApi( api ) )
+        {
+        thread->SetApi( api );
+        thread->SetError( EGL_SUCCESS );
+        return EGL_TRUE;        
+        }
+    else if( thread )
+        {
+        thread->SetError( EGL_BAD_PARAMETER );
+        }
+    return EGL_FALSE;
+    }
+
+EGLAPI EGLenum EGLAPIENTRY eglQueryAPI(void)
+    {    
+    CEGLThread* thread = getThread();
+    EGLI_ASSERT( thread != NULL );
+    
+    EGLenum api = EGL_NONE;
+    if( thread )
+        {
+        api = thread->CurrentApi();
+        thread->SetError( EGL_SUCCESS );
+        }
+    return api;
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient(void)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );    
+    // Macro above fails if thread is not available.
+    CEGLThread* thread = getThread();
+
+    switch( thread->CurrentApi() )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( !(thread->CurrentVGSurface()) )
+                {
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_CURRENT_SURFACE );
+                }
+            if( !(thread->CurrentVGContext()) )
+                {
+                EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+                }
+            if( !(state->VGInterface()) )
+                {
+                // \todo error code?
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+                }
+            state->VGInterface()->Finish();
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            CEGLSurface* read = NULL;
+            CEGLSurface* draw = NULL;
+            thread->CurrentGLESSurfaces( &read, &draw );
+            if( !read || !draw )
+                {
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_CURRENT_SURFACE );
+                }
+            if( !(thread->CurrentGLESContext()) )
+                {
+                EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+                }
+			state->GLESInterface( thread->CurrentGLESContext()->ClientVersion() )->Finish();
+            break;
+            }
+        }
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread(void)
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+#if defined(_WIN32)
+    EGLI_ASSERT( g_tlsIndex != TLS_OUT_OF_INDEXES );
+    if( TlsGetValue( g_tlsIndex ) == NULL )
+        {
+        // Already released or first call => success
+        return EGL_TRUE;
+        }
+#else // Linux
+    // \todo
+    EGLI_ASSERT( false );
+#endif
+#else
+    EGLI_ENTER_RET( EGL_FALSE );
+#endif //EGLI_USE_PLATSIM_EXTENSIONS
+
+    CEGLThread* thread = getThread();
+    EGLenum api = thread->CurrentApi();
+    if( thread->CurrentVGContext() )
+        {
+        const CEGLDisplay* display = thread->CurrentVGContext()->Display();
+        EGLI_ASSERT( display );
+        thread->SetApi( EGL_OPENVG_API );
+        eglMakeCurrent( (EGLDisplay)display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
+        }
+    if( thread->CurrentGLESContext() )
+        {
+        const CEGLDisplay* display = thread->CurrentGLESContext()->Display();
+        EGLI_ASSERT( display );
+        thread->SetApi( EGL_OPENGL_ES_API );
+        eglMakeCurrent( (EGLDisplay)display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
+        }
+    thread->SetApi( api );
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    process->RemoveThread( thread->Id() );
+    if( process->ThreadCount() == 0 )
+        {
+        // All threads destroyed from process => it's not a process any more
+        state->RemoveProcess( process->Id() );
+        process = NULL;
+        }
+#else
+    releaseState();
+#endif
+    return EGL_TRUE;
+    }
+
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer(
+	      EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
+	      EGLConfig configId, const EGLint *attrib_list)
+    {
+    // \todo combine with eglCreatePbufferSurface()
+    EGLI_ENTER_RET( EGL_NO_SURFACE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_NO_SURFACE );
+    
+    // EGLI_ENTER_RET macro above will fail if thread is not available
+    CEGLThread* thread = getThread();
+    switch( buftype )
+        {
+        case EGL_OPENVG_IMAGE:
+            {
+            if( !(thread->CurrentVGContext()) )
+                {
+                EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ACCESS );
+                }
+            break;
+            }
+
+        default:
+            EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_PARAMETER );
+        }
+
+    CEGLConfig* config = state->GetConfig( configId );
+    if( !config )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_CONFIG );
+        }
+    
+    if( !(state->VGInterface()) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+
+    CColorDescriptor colorDescriptor;
+    int width = 0;
+    int height = 0;
+    if( !(state->VGInterface()->IsValidImage(buffer, &colorDescriptor, &width, &height)) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_PARAMETER );
+        }
+    if( display->FindSurfaceByClientBuffer( buffer ) != NULL ||
+        state->VGInterface()->IsImageInUse( buffer ) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ACCESS );
+        }
+    if( !(colorDescriptor.MatchBitDepth(*(config->GetDescriptor()))) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_MATCH );
+        }
+    
+    EGLint textureFormat = EGL_NO_TEXTURE;
+    EGLint textureTarget = EGL_NO_TEXTURE;
+    EGLint mipmapTexture = EGL_FALSE;
+    EGLint largestPbuffer = EGL_FALSE;
+    EGLint colorSpace = colorDescriptor.isNonlinear() ? EGL_VG_COLORSPACE_sRGB : EGL_VG_COLORSPACE_LINEAR;
+    EGLint alphaFormat = colorDescriptor.isPremultiplied() ? EGL_VG_ALPHA_FORMAT_PRE : EGL_VG_ALPHA_FORMAT_NONPRE;
+    
+    EGLint renderableType = config->GetAttribute( EGL_RENDERABLE_TYPE );
+    if( attrib_list && attrib_list[0] != EGL_NONE )
+        {
+        for( int i=0; attrib_list[i] != EGL_NONE; i+=2 )
+            {
+            EGLint value = attrib_list[i+1];
+            switch( attrib_list[i] )
+                {
+                case EGL_TEXTURE_FORMAT:
+                    {
+                    if( !(renderableType & EGL_OPENGL_ES_BIT) &&
+                        !(renderableType & EGL_OPENGL_ES2_BIT) ||
+                        (value != EGL_TEXTURE_RGB &&
+                         value != EGL_TEXTURE_RGBA &&
+                         value != EGL_NO_TEXTURE) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+                    textureFormat = value;
+                    break;
+                    }
+
+                case EGL_TEXTURE_TARGET:
+                    {
+                    if( !(renderableType & EGL_OPENGL_ES_BIT) &&
+                        !(renderableType & EGL_OPENGL_ES2_BIT) ||
+                        (value != EGL_TEXTURE_2D &&
+                         value != EGL_NO_TEXTURE) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+                    textureTarget = value;
+                    break;
+                    }
+
+                case EGL_MIPMAP_TEXTURE:
+                    {
+                    if( !(renderableType & EGL_OPENGL_ES_BIT) ||
+                        !(renderableType & EGL_OPENGL_ES2_BIT) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                        }
+                    mipmapTexture = value;
+                    break;
+                    }
+
+                default:
+                    EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ATTRIBUTE );
+                }
+            }
+        }
+
+    if( (textureFormat == EGL_NO_TEXTURE && textureTarget != EGL_NO_TEXTURE) ||
+        (textureFormat != EGL_NO_TEXTURE && textureTarget == EGL_NO_TEXTURE) )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_MATCH );
+        }
+
+    CEGLPbufferSurface* surface = EGLI_NEW CEGLPbufferSurface( colorSpace, alphaFormat,
+        EGL_BACK_BUFFER, config, largestPbuffer, textureFormat, textureTarget, mipmapTexture, buffer );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    // \note AddSurface() will destroy the object if it fails to take ownership
+    surface = (CEGLPbufferSurface*)display->AddSurface( surface );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    if( !(surface->Resize(width, height)) )
+        {
+        display->RemoveSurface( surface );
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    
+    if( !(state->VGInterface()->CreateSurface(surface->Descriptor(), surface->VGBuffers(), buffer)) )
+        {
+        // \note RemoveSurface() will destroy the object
+        display->RemoveSurface( surface );
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_ALLOC );
+        }
+    surface->AddRef();
+    
+    EGLI_LEAVE_RET( surface, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surfaceId,
+			    EGLint attribute, EGLint value)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+    CEGLSurface* surface = display->GetSurface( surfaceId );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+    surface->Lock();
+    switch( attribute )
+        {
+        case EGL_MIPMAP_LEVEL:
+            {
+            if( !(surface->Config()->GetAttribute( EGL_RENDERABLE_TYPE ) & EGL_OPENGL_ES_BIT ))
+                {
+                surface->Unlock();
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_PARAMETER );
+                }
+            break;
+            }
+        case EGL_MULTISAMPLE_RESOLVE:
+            {
+			bool hasBoxBit = !!(surface->Config()->GetAttribute( EGL_SURFACE_TYPE ) & EGL_MULTISAMPLE_RESOLVE_BOX_BIT );
+            if( value != EGL_MULTISAMPLE_RESOLVE_BOX ||
+                value != EGL_MULTISAMPLE_RESOLVE_DEFAULT )
+                {
+                surface->Unlock();
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ATTRIBUTE );
+                } 
+            else if( value == EGL_MULTISAMPLE_RESOLVE_BOX && !hasBoxBit )
+                {
+                surface->Unlock();
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_MATCH );
+                }
+            break;
+            }
+        case EGL_SWAP_BEHAVIOR:
+            {
+			bool hasPreservedBit = !!(surface->Config()->GetAttribute( EGL_SURFACE_TYPE ) & EGL_SWAP_BEHAVIOR_PRESERVED_BIT );
+            if( value != EGL_BUFFER_PRESERVED ||
+                value != EGL_BUFFER_DESTROYED )
+                {
+                surface->Unlock();
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ATTRIBUTE );
+                }
+            else if( value == EGL_BUFFER_PRESERVED && !hasPreservedBit )
+                {
+                surface->Unlock();
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_MATCH );
+                }
+            break;
+            }
+        default:
+            {
+            surface->Unlock();
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ATTRIBUTE );
+            }
+
+        }
+    surface->SetAttribute( attribute, value );
+    surface->Unlock();
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage(EGLDisplay dpy, EGLSurface surfaceId, EGLint buffer)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+
+    // EGLI_ENTER_RET macro above will fail if thread is not available
+    CEGLThread* thread = getThread();
+
+    CEGLSurface* surface = display->GetSurface( surfaceId );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+
+    if( buffer != EGL_BACK_BUFFER )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_PARAMETER );
+        }
+
+	if( thread->CurrentGLESContext() == NULL)
+		{
+		EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+		}
+
+	if( surface->IsLocked() )
+		{
+		EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+		}
+	surface->Lock();
+
+	CEGLSurface* glesReadSurface;
+	thread->CurrentGLESSurfaces( &glesReadSurface, NULL );
+	state->SyncSurface( EGL_OPENVG_API, 0, surface, glesReadSurface );
+
+    EGLint renderableType = surface->Config()->GetAttribute( EGL_RENDERABLE_TYPE );
+
+    if( (!(renderableType & EGL_OPENGL_ES_BIT) && !(renderableType & EGL_OPENGL_ES2_BIT)) ||
+        surface->Type() != CEGLSurface::PBUFFER_SURFACE ||
+        (surface->Config()->GetAttribute( EGL_BIND_TO_TEXTURE_RGB ) == EGL_FALSE &&
+         surface->Config()->GetAttribute( EGL_BIND_TO_TEXTURE_RGBA ) == EGL_FALSE ) )
+        {
+        surface->Unlock();
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+    if( ((CEGLPbufferSurface*)surface)->TextureFormat() == EGL_NO_TEXTURE )
+        {
+        surface->Unlock();
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_MATCH );
+        }
+	bool mipmapTexture = !!((CEGLPbufferSurface*)surface)->MipmapTexture();
+	IEGLtoGLESInterface* iFace = state->GLESInterface( thread->CurrentGLESContext()->ClientVersion() );
+	if( surface->BoundContext() == thread->CurrentGLESContext() )
+		{
+		iFace->Flush();
+		}
+	else
+		{
+		// \todo Wait for all issued client API commands drawing to the surface to complete.
+		}
+	int level = surface->Attribute( EGL_MIPMAP_LEVEL );
+	int textureName = iFace->BindTexImage( surface, level, mipmapTexture, surface->Descriptor(), surface->VGColorBuffer());
+	EGLITextureBinding& binding = surface->TextureBinding();
+	binding.name = textureName;
+	binding.level = level;
+	binding.clientVersion = thread->CurrentGLESContext()->ClientVersion();
+	binding.context = eglGetCurrentContext();
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage(EGLDisplay dpy, EGLSurface surfaceId, EGLint buffer)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+
+	// EGLI_ENTER_RET macro above will fail if thread is not available
+    CEGLThread* thread = getThread();
+
+    if( buffer != EGL_BACK_BUFFER )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_PARAMETER );
+        }
+    CEGLSurface* surface = display->GetSurface( surfaceId );
+    // \todo errors etc.
+    if( !surface || (surface && surface->Type() != CEGLSurface::PBUFFER_SURFACE) )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+    if( ((CEGLPbufferSurface*)surface)->TextureFormat() == EGL_NO_TEXTURE )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_MATCH );
+        }
+
+	EGLITextureBinding& binding = surface->TextureBinding();
+
+	if( display->GetContext( binding.context ))
+		{
+		EGLenum origAPI = eglQueryAPI();
+		EGLSurface origReadSurface, origDrawSurface;
+		EGLContext origContext;
+		bool switchAPI = origAPI == EGL_OPENGL_ES_API;
+		bool switchContext = binding.context != thread->CurrentGLESContext();
+		if( switchAPI )
+			{
+			eglBindAPI( EGL_OPENGL_ES_API );
+			}
+		if( switchContext )
+			{
+			// Switch to the context where the texture lives.
+			origReadSurface = eglGetCurrentSurface(EGL_READ);
+			origDrawSurface = eglGetCurrentSurface(EGL_DRAW);
+			origContext = eglGetCurrentContext();
+			eglMakeCurrent( display, surfaceId, surfaceId, binding.context );
+			}
+		state->GLESInterface(binding.clientVersion)->ReleaseTexImage( binding.name, binding.level );
+		if( switchContext )
+			{
+			// Switch back to the original context.
+			eglMakeCurrent( display, origDrawSurface, origReadSurface, origContext );
+			}
+		if( switchAPI )
+			{
+			eglBindAPI( origAPI );
+			}
+		}
+	else
+		{
+		// The context has been destroyed. Ignore the call.
+		}
+	binding.name = 0;
+	surface->Unlock();
+
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval(EGLDisplay dpy, EGLint interval)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread != NULL );
+    
+    if( !(thread->CurrentVGContext()) )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_CONTEXT );
+        }
+    if( !(thread->CurrentVGSurface()) )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+    // eglSwapInterval – hardcode EGL_MAX_SWAP_INTERVAL and EGL_MIN_SWAP_INTERVAL to 1, so nothing here
+    if( thread->CurrentVGSurface()->Type() == CEGLSurface::WINDOW_SURFACE )
+        {
+        ((CEGLWindowSurface*)thread->CurrentVGSurface())->SetSwapInterval( /*interval*/ 1 );
+        }
+
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig configId,
+			    EGLContext share_context,
+			    const EGLint *attrib_list)
+    {
+    EGLI_ENTER_RET( EGL_NO_CONTEXT );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_NO_CONTEXT );
+
+    CEGLConfig* config = state->GetConfig( configId );
+    if( !config )
+        {
+        EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_CONFIG );
+        }
+
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread != NULL );
+
+    EGLenum currentApi = thread->CurrentApi();
+    if( currentApi == EGL_NONE )
+        {
+        EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_MATCH );
+        }
+    
+    CEGLContext* shareContext = NULL;
+    if( share_context != EGL_NO_CONTEXT )
+        {
+        shareContext = display->GetContext( share_context );
+        if( !shareContext || (shareContext && process->Id() != shareContext->ProcessId()) )
+            {
+            EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_MATCH );
+            }
+        if( currentApi != shareContext->ClientApi() )
+            {
+            EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_CONTEXT );
+            }
+        }
+    
+    EGLint renderableType = config->GetAttribute( EGL_RENDERABLE_TYPE );
+    EGLint clientVersion = 1;
+    if( attrib_list && attrib_list[0] != EGL_NONE )
+        {
+        switch( attrib_list[0] )
+            {
+            case EGL_CONTEXT_CLIENT_VERSION:
+                {
+                if( currentApi != EGL_OPENGL_ES_API )
+                    {
+                    EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_ATTRIBUTE );
+                    }
+                if( attrib_list[1] == 1 ) //GLES 1.1
+                    {
+                    if( !(renderableType & EGL_OPENGL_ES_BIT) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_CONFIG );
+                        }
+                    clientVersion = 1;
+                    }
+                else if( attrib_list[1] == 2 ) //GLES 2.0
+                    {
+                    if( !(renderableType & EGL_OPENGL_ES2_BIT) )
+                        {
+                        EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_CONFIG );
+                        }
+                    clientVersion = 2;
+                    }
+                else
+                    {
+                    EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_ATTRIBUTE );
+                    }
+                break;
+                }
+
+            default:
+                {
+                EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_ATTRIBUTE );
+                break;
+                }
+            }
+        }
+    
+    void* clientContext = NULL;
+    CEGLContext* context = NULL;
+    switch( currentApi )
+        {
+        case EGL_OPENVG_API:
+            {
+            EGLI_ASSERT( state->VGInterface() != NULL );
+            clientContext = state->VGInterface()->CreateContext( 
+                shareContext != NULL ? shareContext->ClientContext() : shareContext );
+            if( clientContext )
+                {
+                context = EGLI_NEW CEGLContext( process->Id(), display, config, currentApi, clientVersion, clientContext );
+                // \note AddContext() will destroy the object if it fails to take ownership
+                context = display->AddContext( context );
+                if( !context )
+                    {
+                    state->VGInterface()->ReleaseContext( clientContext );
+                    EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_ALLOC );
+                    }
+                }
+            break;
+            }
+
+        case EGL_OPENGL_ES_API:
+            {
+			EGLINativeContextType nativeShareContext = shareContext != NULL ? shareContext->NativeContext() : NULL;
+			EGLINativeContextType nativeContext = CEGLOs::CreateNativeContext( *config, display->NativeType(), nativeShareContext );
+            if( !nativeContext )
+                {
+                EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_ALLOC );
+                }
+
+			IEGLtoGLESInterface* iFace = state->GLESInterface( clientVersion );
+			EGLI_ASSERT( iFace != NULL );
+			clientContext = state->GLESInterface( clientVersion )->CreateContext( nativeContext );
+			if( clientContext )
+		        {
+                context = EGLI_NEW CEGLContext( process->Id(), display, config, currentApi, clientVersion, clientContext );
+                if( context )
+                    // \note AddContext() will destroy the object if it fails to take ownership
+		            context = display->AddContext( context );
+		        if( !context )
+			        {
+			        iFace->ReleaseContext( clientContext );
+					CEGLOs::DestroyNativeContext( nativeContext );
+                    EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_ALLOC );
+			        }
+                context->SetNativeContext( nativeContext );
+		        }
+	        else
+		        {
+				CEGLOs::DestroyNativeContext( nativeContext );
+                EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_ALLOC );
+				}
+			break;
+			}
+
+        case EGL_NONE:
+            {
+            EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_MATCH );
+            break;
+            }
+        }
+    
+    if( context )
+        {
+        context->AddRef();
+        }
+    else
+        {
+        EGLI_LEAVE_RET( EGL_NO_CONTEXT, EGL_BAD_ALLOC );
+        }
+
+    EGLI_LEAVE_RET( (EGLContext)context, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread != NULL );
+
+    CEGLContext* context = display->GetContext( ctx );
+    if( !context )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_CONTEXT );
+        }
+
+    EGLenum clientApi = context->ClientApi();
+    switch( clientApi )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( context->RemoveRef() )
+                {
+                state->VGInterface()->ReleaseContext(context->ClientContext());
+                // \note RemoveContext() will destroy the object
+                display->RemoveContext( context );
+                }
+            else
+                {
+                context->Terminate();
+                }
+            break;
+            }
+
+        case EGL_OPENGL_ES_API:
+            {
+            if( context->RemoveRef() )
+                {
+				if( !(state->GLESInterface( context->ClientVersion() )->ReleaseContext( context->ClientContext() )) )
+					{
+					// \todo Handle errors!
+                    EGLI_ASSERT( false );
+					}
+                if( context->NativeContext() && !(CEGLOs::DestroyNativeContext(context->NativeContext())) )
+                    {
+                    // \todo Handle errors!
+                    EGLI_ASSERT( false );
+                    }
+                // \note RemoveContext() will destroy the object
+                display->RemoveContext( context );
+                }
+            else
+                {
+                context->Terminate();
+                }
+            break;
+            }
+        }
+
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw,
+			  EGLSurface read, EGLContext ctx)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread );
+    
+    bool releaseCurrent = ( draw == EGL_NO_SURFACE && read == EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT );
+    
+    if( (ctx == EGL_NO_CONTEXT && draw != EGL_NO_SURFACE && read != EGL_NO_SURFACE) ||
+        ((draw == EGL_NO_SURFACE || read == EGL_NO_SURFACE) && ctx != EGL_NO_CONTEXT) )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_MATCH );
+        }
+    
+    CEGLContext* context = display->GetContext( ctx );
+    if( (!releaseCurrent && !context ) || (context && context->ProcessId() != process->Id()) )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_CONTEXT );
+        }
+
+    EGLenum currentApi = thread->CurrentApi();
+    CEGLContext* currentContext = NULL;
+    CEGLSurface* currentDrawSurface = NULL;
+    CEGLSurface* currentReadSurface = NULL;
+    CEGLSurface* drawSurface = NULL;
+    CEGLSurface* readSurface = NULL;
+
+    if( !releaseCurrent )
+        {    
+        if( context && context->ClientApi() == EGL_OPENVG_API && ( draw != read ) )
+            {
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_MATCH );
+            }
+        drawSurface = display->GetSurface( draw );
+        readSurface = display->GetSurface( read );
+        if( !drawSurface || !readSurface )
+            {
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+            }
+
+        if( !(context->Config()->IsCompatible( *(drawSurface->Config()), context->ClientApi())) ||
+            !(context->Config()->IsCompatible( *(readSurface->Config()), context->ClientApi())) )
+            {
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_MATCH );
+            }
+
+        if( (context->Thread() && context->Thread() != thread) ||
+            (drawSurface->BoundContext() && drawSurface->BoundContext()->Thread() != thread) ||
+            (readSurface->BoundContext() && readSurface->BoundContext()->Thread() != thread) )
+            {
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+            }
+
+        if( drawSurface->Type() == CEGLSurface::WINDOW_SURFACE &&
+            !(CEGLOs::IsValidNativeWindow(((CEGLWindowSurface*)drawSurface)->NativeType())) )
+            {
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_NATIVE_WINDOW );
+            }
+        if( readSurface != drawSurface && readSurface->Type() == CEGLSurface::WINDOW_SURFACE &&
+            !(CEGLOs::IsValidNativeWindow(((CEGLWindowSurface*)readSurface)->NativeType())) )
+            {
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_NATIVE_WINDOW );
+            }
+
+        // TODO: If binding ctx would exceed the number of current contexts of that client
+        //       API type supported by the implementation, an EGL_BAD_ACCESS error is
+        //       generated.
+
+        // TODO: If either draw or read are pbuffers created with eglCreatePbufferFromClientBuffer,
+        //       and the underlying bound client API buffers are in use by the
+        //       client API that created them, an EGL_BAD_ACCESS error is generated        
+
+        // TODO: If draw and read cannot fit into graphics memory simultaneously, an EGL_BAD_MATCH error is generated.
+
+        // TODO: If the previous context of the calling thread has unflushed commands, and
+        //       the previous surface is no longer valid, an EGL_BAD_CURRENT_SURFACE
+        //       error is generated.
+
+        // TODO: If the ancillary buffers for draw and read cannot be allocated, an EGL_BAD_ALLOC error is generated.
+
+        // TODO: If a power management event has occurred, an EGL_CONTEXT_LOST error is generated.
+        
+        // TODO: flush context
+        switch( context->ClientApi() )
+            {
+            case EGL_OPENVG_API:
+                {
+                state->VGInterface()->Flush();
+                currentContext = thread->SwitchVGContext( context );
+                currentDrawSurface = thread->SwitchVGSurface( drawSurface );
+                drawSurface->BindToContext( context );
+                if( !(state->VGInterface()->SetCurrentSurface(context->ClientContext(), drawSurface->VGClientSurface())) )
+                    {
+                    // Restore previous context/surface
+                    thread->SwitchVGContext( currentContext );
+                    thread->SwitchVGSurface( currentDrawSurface );
+                    // \todo error code?
+                    EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+                    }
+                // \todo track changes through locking
+                drawSurface->SetVGDirty( true );
+                break;
+                }
+
+            case EGL_OPENGL_ES_API:
+                {
+				if( thread->CurrentGLESContext() )
+					{
+					state->GLESInterface(context->ClientVersion())->Flush();
+					}
+                currentContext = thread->SwitchGLESContext( context );
+                thread->SwitchGLESSurfaces( drawSurface, readSurface, currentReadSurface, currentDrawSurface );
+				drawSurface->BindToContext( context );
+                if( drawSurface != readSurface )
+                    {
+                    readSurface->BindToContext( context );
+                    }
+				EGLINativeContextType nativeContext = (EGLINativeContextType)state->GLESInterface(context->ClientVersion())->GetNativeContext( context->ClientContext() );
+                if( !(context->NativeGLFunctions()) )
+                    {
+                    EGLINativeGLFunctions* nativeFuncs = EGLI_NEW EGLINativeGLFunctions;
+                    if( !nativeFuncs )
+                        {
+                        // Restore previous context/surface
+                        thread->SwitchGLESContext( currentContext );
+                        thread->SwitchGLESSurfaces( currentReadSurface, currentDrawSurface, readSurface, drawSurface );
+                        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ALLOC );
+                        }
+                    memset( nativeFuncs, 0, sizeof(EGLINativeGLFunctions) );
+                    if( !(CEGLOs::InitializeNativeGLFunctions(nativeFuncs, display->NativeType(), nativeContext)) )
+                        {
+                        // Restore previous context/surface
+                        thread->SwitchGLESContext( currentContext );
+                        thread->SwitchGLESSurfaces( currentReadSurface, currentDrawSurface, readSurface, drawSurface );
+                        delete nativeFuncs;
+                        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ALLOC );
+                        }
+                    context->SetNativeGLFucntions( nativeFuncs );
+                    }
+                EGLINativeDisplayType drawDC = NULL;
+                EGLINativeDisplayType readDC = NULL;
+                if( drawSurface->Type() == CEGLSurface::PBUFFER_SURFACE ) 
+                    {
+                    drawDC = ((CEGLPbufferSurface*)drawSurface)->NativeDisplay();
+                    }
+                else if( drawSurface->Type() == CEGLSurface::WINDOW_SURFACE )
+                    {
+                    drawDC = ((CEGLWindowSurface*)drawSurface)->OsContext()->glesDisplay;
+                    }
+
+                if( readSurface == drawSurface )
+                    {
+                    readDC = drawDC;
+                    }
+                else if( readSurface->Type() == CEGLSurface::PBUFFER_SURFACE )
+                    {
+                    readDC = ((CEGLPbufferSurface*)readSurface)->NativeDisplay();
+                    }
+                else if( readSurface->Type() == CEGLSurface::WINDOW_SURFACE )
+                    {
+                    readDC = ((CEGLWindowSurface*)readSurface)->OsContext()->glesDisplay;
+                    }
+
+                if( !(CEGLOs::MakeNativeContextCurrent(context->NativeGLFunctions(), drawDC, readDC, context->NativeContext())) )
+                    {
+                    // Restore previous context/surface. CEGLOs::MakeNativeContextCurrent() will restore previous
+                    // native context/surface on failure
+                    thread->SwitchGLESContext( currentContext );
+                    thread->SwitchGLESSurfaces( currentReadSurface, currentDrawSurface, readSurface, drawSurface );
+                    // \todo error code?
+                    EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+                    }
+                break;
+                }
+
+            default:
+                {
+                EGLI_ASSERT( false );
+                break;
+                }
+            }        
+        }
+    else
+        {
+        switch( currentApi )
+            {
+            case EGL_OPENVG_API:
+                {
+                state->VGInterface()->Flush();
+				if( thread->CurrentGLESContext() )
+					{
+					// Sync surface before releasing the VG context because there
+					// might not be a VG context if GLES locks the surface later.
+					CEGLSurface* glesReadSurface;
+					thread->CurrentGLESSurfaces( &glesReadSurface, NULL );
+					state->SyncSurface( EGL_OPENGL_API, thread->CurrentGLESContext()->ClientVersion(), thread->CurrentVGSurface(), glesReadSurface );
+					}
+                currentContext = thread->SwitchVGContext( NULL );
+                currentDrawSurface = thread->SwitchVGSurface( NULL );
+                break;
+                }
+
+            case EGL_OPENGL_ES_API:
+                {
+				if( thread->CurrentGLESContext() )
+					{
+					state->GLESInterface(thread->CurrentGLESContext()->ClientVersion())->Flush();
+					}
+				if( thread->CurrentVGContext() )
+					{
+					// Sync surface before releasing the GLES context because there
+					// might not be a GLES context if VG locks the surface later.
+					CEGLSurface* glesReadSurface;
+					CEGLSurface* glesDrawSurface;
+					thread->CurrentGLESSurfaces( &glesReadSurface, &glesDrawSurface );
+					state->SyncSurface( EGL_OPENVG_API, 0, glesReadSurface, glesReadSurface );
+					if( glesDrawSurface != glesReadSurface )
+						{
+						state->SyncSurface( EGL_OPENVG_API, 0, glesDrawSurface, NULL );
+						}
+					}
+                currentContext = thread->SwitchGLESContext( NULL );
+                thread->SwitchGLESSurfaces( NULL, NULL, currentReadSurface, currentDrawSurface );
+                break;
+                }
+            }
+        }
+
+    if( currentDrawSurface && currentDrawSurface != drawSurface )
+        {
+        currentDrawSurface->BindToContext( NULL );
+        if( currentDrawSurface->RemoveRef() )
+            {
+            if( currentDrawSurface->VGClientSurface() )
+                {
+                if( !(state->VGInterface()->ReleaseSurface(currentDrawSurface->VGClientSurface())) )
+                    {
+                    // \todo error code?
+                    EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+                    }
+                }
+            if( currentDrawSurface->Type() == CEGLSurface::PBUFFER_SURFACE )
+                {
+                //((CEGLPbufferSurface*)currentDrawSurface)->SetNativePbufferContainer( NULL );
+                //EGLI_ASSERT( false );
+                }
+            // \note RemoveSurface() will destroy the object
+            display->RemoveSurface( currentDrawSurface );
+            }
+        if( currentReadSurface == currentDrawSurface )
+            {
+            currentReadSurface = NULL;
+            }
+        currentDrawSurface = NULL;
+        }
+
+    if( currentReadSurface && currentReadSurface != readSurface )
+        {
+        currentReadSurface->BindToContext( NULL );
+        if( currentReadSurface->RemoveRef() )
+            {
+            if( currentReadSurface->VGClientSurface() )
+                {
+                if( !(state->VGInterface()->ReleaseSurface(currentReadSurface->VGClientSurface())) )
+                    {
+                    // \todo error code?
+                    EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+                    }
+                }
+            if( currentReadSurface->Type() == CEGLSurface::PBUFFER_SURFACE )
+                {
+                // \todo 
+                ((CEGLPbufferSurface*)currentReadSurface)->SetNativePbufferContainer( NULL );
+                }
+            // \note RemoveSurface() will destroy the object
+            display->RemoveSurface( currentReadSurface );
+            }
+        }
+
+    if( currentContext && currentContext != context )
+        {
+        currentContext->SetThread( NULL );
+        if( currentContext->RemoveRef() )
+            {
+            if( currentContext->ClientContext() )
+                {
+                if( currentContext->ClientApi() == EGL_OPENVG_API )
+                    {
+					bool success = state->VGInterface()->ReleaseContext( currentContext->ClientContext() );
+                    EGLI_ASSERT( success );
+                    }
+                if( currentContext->ClientApi() == EGL_OPENGL_ES_API )
+                    {
+					bool success = state->GLESInterface(currentContext->ClientVersion())->ReleaseContext(currentContext->ClientContext());
+                    EGLI_ASSERT( success );
+                    }
+                }
+            if( currentContext->NativeContext() )
+                {
+                if( !(CEGLOs::DestroyNativeContext(currentContext->NativeContext())) )
+                    {
+                    // \todo Handle errors!
+                    EGLI_ASSERT( false );
+                    }
+                }
+            // \note RemoveContext() will destroy the object
+            display->RemoveContext( currentContext );
+            currentContext = NULL;
+            }
+        }
+    if( context && currentContext != context ) 
+        {
+        context->AddRef();
+        }
+    if( drawSurface && currentDrawSurface != drawSurface ) 
+        {
+        drawSurface->AddRef();
+        }
+    if( readSurface && readSurface != drawSurface && readSurface != currentReadSurface )
+        {
+        readSurface->AddRef();
+        }
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+
+EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext(void)
+    {
+    EGLI_ENTER_RET( EGL_NO_CONTEXT );
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread != NULL );
+    EGLContext ret = EGL_NO_CONTEXT;
+    switch( thread->CurrentApi() )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( thread->CurrentVGContext() )
+                {
+                ret = thread->CurrentVGContext();
+                }
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            if( thread->CurrentGLESContext() )
+                {
+                ret = thread->CurrentGLESContext();
+                }
+            break;
+            }
+        }
+    EGLI_LEAVE_RET( ret, EGL_SUCCESS );
+    }
+
+EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface(EGLint readdraw)
+    {    
+    EGLI_ENTER_RET( EGL_NO_SURFACE );
+    if( readdraw != EGL_READ && readdraw != EGL_DRAW )
+        {
+        EGLI_LEAVE_RET( EGL_NO_SURFACE, EGL_BAD_PARAMETER );
+        }
+
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread != NULL );
+
+    EGLSurface ret = EGL_NO_SURFACE;
+    EGLenum currentApi = thread->CurrentApi();
+    switch( currentApi )
+        {
+        case EGL_OPENVG_API:
+            {
+            CEGLContext* context = thread->CurrentVGContext();
+            if( context )
+                {
+                ret = thread->CurrentVGSurface();
+                }
+            break;
+            }
+
+        case EGL_OPENGL_ES_API:
+            {
+            CEGLSurface* read = NULL;
+            CEGLSurface* draw = NULL;
+            thread->CurrentGLESSurfaces( &read, &draw );
+            switch( readdraw )
+                {
+                case EGL_READ:
+                    {
+                    ret = (EGLSurface)read;
+                    break;
+                    }
+
+                case EGL_DRAW:
+                    {
+                    ret = (EGLSurface)draw;
+                    break;
+                    }
+                }
+            break;
+            }
+
+        default:
+            {
+            EGLI_ASSERT( false );
+            }
+        }
+    EGLI_LEAVE_RET( ret, EGL_SUCCESS );
+    }
+
+EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay(void)
+    {
+    EGLI_ENTER_RET( EGL_NO_DISPLAY );
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread );
+    EGLenum currentApi = thread->CurrentApi();
+    EGLDisplay ret = EGL_NO_DISPLAY;
+    switch( currentApi )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( thread->CurrentVGContext() )
+                {
+                ret = (EGLDisplay)thread->CurrentVGContext()->Display();
+                }
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            if( thread->CurrentGLESContext() )
+                {
+                ret = (EGLDisplay)thread->CurrentGLESContext()->Display();
+                }
+            break;
+            }
+
+        default:
+            EGLI_ASSERT( false );
+        }
+    EGLI_LEAVE_RET( ret, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext(EGLDisplay dpy, EGLContext ctx,
+			   EGLint attribute, EGLint *value)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE )
+    if( !value )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_PARAMETER );
+        }
+    CEGLContext* context = display->GetContext( ctx );
+    if( !context )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_CONTEXT );
+        }
+    switch( attribute )
+        {
+        case EGL_CONFIG_ID:
+            {
+            *value = ((CEGLConfig*)context->Config())->GetAttribute( EGL_CONFIG_ID );
+            break;
+            }
+
+        case EGL_CONTEXT_CLIENT_TYPE:
+            {
+            *value = context->ClientApi();
+            break;
+            }
+
+        case EGL_CONTEXT_CLIENT_VERSION:
+            {
+            *value = context->ClientVersion();
+            break;
+            }
+
+        case EGL_RENDER_BUFFER:
+            {
+            CEGLSurface* surface = NULL;
+            CEGLThread* thread = process->CurrentThread();
+            EGLI_ASSERT( thread != NULL );
+            if( thread->CurrentVGContext() == context )
+                {
+                surface = thread->CurrentVGSurface();
+                }
+            else if( thread->CurrentGLESContext() == context )
+                {
+                thread->CurrentGLESSurfaces( NULL, &surface );
+                }
+            else
+                {
+                surface = process->FindBoundSurface( context, false );
+                }
+            if( surface )
+                {
+                *value = surface->RenderBuffer();
+                }
+            else 
+                {
+                *value = EGL_NONE;
+                }
+            break;
+            }
+
+        default:
+            {
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ATTRIBUTE );
+            }
+        }
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL(void)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    // EGLI_ENTER_RET macro above will fail if thread is not available
+    CEGLThread* thread = getThread();
+    EGLBoolean ret = EGL_TRUE;
+    EGLenum api = eglQueryAPI();
+    if( eglBindAPI( EGL_OPENGL_ES_API ) )
+        {
+        ret = eglWaitClient();
+        if( thread->IsSupportedApi(api) )
+            {
+            eglBindAPI( api );
+            }
+        }    
+    EGLI_LEAVE_RET( ret, thread->Error() );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative(EGLint engine)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    // eglWaitNative – no-op, as no such thing as native rendering to pbuffers
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface surfaceId)
+    {
+    // \todo eglSwapBuffers – all surfaces are single-buffered pbuffers, so this just needs to do a flush in the current client API
+    EGLI_ENTER_RET( EGL_FALSE );
+    EGLI_GET_DISPLAY_RET( dpy, EGL_FALSE );
+
+    // EGLI_ENTER_RET macro above will fail if thread is not available
+    CEGLThread* thread = getThread();
+
+    CEGLSurface* surface = display->GetSurface( surfaceId );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+    EGLenum currentApi = thread->CurrentApi();
+    switch( currentApi )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( thread->CurrentVGContext() != surface->BoundContext() )
+                {
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+                }
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            if( thread->CurrentGLESContext() != surface->BoundContext() )
+                {
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+                }
+            // \todo other GLES stuff?
+            }
+        }
+    if( surface->Type() != CEGLSurface::WINDOW_SURFACE || surface->RenderBuffer() == EGL_SINGLE_BUFFER )
+        {
+        EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+        }
+
+    if( !(CEGLOs::IsValidNativeWindow(((CEGLWindowSurface*)surface)->NativeType())) )
+        {
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_NATIVE_WINDOW ); 
+        }
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    int w, h;
+    if( !(CEGLOs::GetNativeWindowSize(((CEGLWindowSurface*)surface)->NativeType(), w, h)) )
+        {
+        // \todo Error code?
+        EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_SURFACE );
+        }
+#else
+    int w = surface->Width();
+    int h = surface->Height();
+#endif
+    if( surface->Width() != w || surface->Height() != h )
+        {
+        if( !(surface->Resize(w, h)) )
+            {
+            EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ALLOC );
+            }
+        if( w <= 0 || h <= 0 )
+            {
+            // invisible window => do nothing
+            EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+            }
+        if( surface->VGClientSurface() && state->VGInterface() )
+            {
+            if( !(state->VGInterface()->ResizeSurface(thread->CurrentVGContext()->ClientContext(),
+                surface->VGClientSurface(), w, h, surface->VGBuffers())) )
+                {
+                EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ALLOC );
+                }
+            }
+        }
+
+    EGLint stride = surface->Stride();
+    void* buf = ((CEGLWindowSurface*)surface)->CurrentBuffer();
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    buf = (void*)((char*)buf + ((surface->Height() - 1) * stride));
+#else
+    switch( currentApi )
+        {
+        case EGL_OPENVG_API:
+            {
+            state->VGInterface()->CopyBuffers( buf, surface->Stride(), surface->VGClientSurface() );
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+			if( surface->BoundContext() && !(state->GLESInterface(surface->BoundContext()->ClientVersion())) )
+				{
+				// \todo error code?
+				EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_ACCESS );
+				}
+            }
+        }
+#endif
+    CEGLOs::BlitToOSWindow( currentApi, display, ((CEGLWindowSurface*)surface)->OsContext(), buf, surface->Width(), surface->Height(), stride );
+    EGLI_LEAVE_RET( EGL_TRUE, EGL_SUCCESS );
+    }
+
+EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy, EGLSurface surface,
+			  EGLNativePixmapType target)
+    {
+    EGLI_ENTER_RET( EGL_FALSE );
+    // eglCopyBuffers always raises EGL_BAD_NATIVE_PIXMAP error (as no native pixmaps supported)
+    EGLI_LEAVE_RET( EGL_FALSE, EGL_BAD_NATIVE_PIXMAP );
+    }
+
+/* Now, define eglGetProcAddress using the generic function ptr. type */
+EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY
+       eglGetProcAddress(const char *procname)
+    {
+    EGLI_ENTER_RET( NULL );
+    // \todo EGL
+    __eglMustCastToProperFunctionPointerType ret = NULL;
+    if( strncmp( procname, "vg", 2 ) == 0 )
+        {
+        ret = state->VGInterface()->GetVGProcAddress( procname );
+        }
+    else if( strncmp( procname, "egl", 3 ) == 0 )
+        {
+        ret = (__eglMustCastToProperFunctionPointerType)CEGLExtension::eglGetProcAddress( procname );
+        }
+    else if( strncmp( procname, "gl", 2 ) == 0 )
+        {
+        ret = state->GLESInterface(2)->GetGLProcAddress( procname );
+		if( ret == NULL )
+			{
+			// Not found in GLES2, try GLES1.
+			ret = state->GLESInterface(1)->GetGLProcAddress( procname );
+			}
+        }
+    else
+        {
+        // return just NULL pointer...
+        }
+    EGLI_LEAVE_RET( ret, EGL_SUCCESS );
+    }
+
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+// non-standard platsim functions
+EGLAPI void EGLAPIENTRY eglPlatsimSetProcessInformation( EGLint processId, EGLint threadId )
+    {
+    EGLI_ENTER_RET(EGLI_NO_RET);
+    if( process && process->Id() != processId )
+        {
+        process = state->GetProcess( processId );
+        }
+    if( !process )
+        {
+        process = state->AddProcess( processId, true );
+        EGLI_ASSERT( process != NULL );
+        CEGLThread* thread = process->AddThread( threadId, true, state->SupportedApis() );
+        EGLI_ASSERT( thread != NULL );
+        }
+    else if( !(process->HasThread( threadId )) )
+        {
+        CEGLThread* thread = process->AddThread( threadId, true, state->SupportedApis() );
+        EGLI_ASSERT( thread != NULL );
+        }
+    else
+        {
+        state->SetCurrentProcessThread( processId, threadId );
+        } 
+    EGLI_LEAVE_RET( EGLI_NO_RET, EGL_SUCCESS );
+    }
+
+EGLAPI EGLint EGLAPIENTRY eglPlatsimGetError()
+    {
+    //TODO
+    EGLI_ENTER_RET( EGL_SUCCESS );
+    EGLI_ASSERT( process != NULL );
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread != NULL );
+    EGLint err = thread->Error();
+    EGLI_LEAVE_RET( err, err );
+    }
+
+// This is called after eglCreateWindowSurface()
+EGLAPI void EGLAPIENTRY eglPlatsimSetSurfaceParams(
+    EGLDisplay displayId, EGLSurface surfaceId, EGLint width, EGLint height,
+    EGLint stride, void* buffer0, void *buffer1)
+    {
+    EGLI_ENTER_RET( EGLI_NO_RET );
+    CEGLDisplay* display = state->GetDisplay( displayId );
+    if( !display || (display && !(display->IsInitialized())) )
+        {
+        EGLI_LEAVE_RET( EGLI_NO_RET, EGL_NOT_INITIALIZED );
+        }
+    EGLI_ASSERT( display->ProcessId() == process->Id() );
+
+    CEGLSurface* surface = display->GetSurface( surfaceId );
+    if( !surface )
+        {
+        EGLI_LEAVE_RET( EGLI_NO_RET, EGL_BAD_SURFACE );
+        }
+
+    EGLI_ASSERT( surface->Type() == CEGLSurface::WINDOW_SURFACE );
+    if( !(surface->Resize(width, height)) )
+        {
+        EGLI_LEAVE_RET( EGLI_NO_RET, EGL_BAD_ALLOC );
+        }
+    ((CEGLWindowSurface*)surface)->SetStride( stride );
+    ((CEGLWindowSurface*)surface)->SetWindowBuffers( buffer0, buffer1 );
+    
+    CEGLThread* thread = process->CurrentThread();
+    EGLI_ASSERT( thread != NULL );
+    //TODO: resizing
+    switch( thread->CurrentApi() )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( !(surface->VGColorBuffer()) )
+                {
+                EGLI_ASSERT( state->VGInterface() != NULL );
+                SurfaceDescriptor* surfaceDesc = surface->Descriptor();                
+				bool success = state->VGInterface()->CreateSurface( surfaceDesc, surface->VGBuffers(), NULL );
+                EGLI_ASSERT( success );
+                }
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+            //TODO: GLES not implemented
+            //EGLI_ASSERT( false );
+            break;
+            }
+        default:
+            {
+            EGLI_ASSERT( false );
+            }
+        }
+    
+    //TODO: what else? 
+    EGLI_LEAVE_RET( EGLI_NO_RET, EGL_SUCCESS );
+    }
+
+EGLAPI EGLNativePixmapType EGLAPIENTRY eglPlatsimGetPixmapSurfaceBitmap( EGLDisplay display, EGLSurface surface)
+    {
+    //TODO
+    return NULL;
+    }
+#endif
+
+#if defined(_WIN32)
+
+BOOL WINAPI DllMain( HINSTANCE hinstDLL,
+                     DWORD fdwReason,
+                     LPVOID lpvReserved )
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    switch( fdwReason )
+        {
+        case DLL_PROCESS_ATTACH:
+            {
+            g_tlsIndex = TlsAlloc();
+            if( g_tlsIndex == TLS_OUT_OF_INDEXES )
+                return FALSE;
+            if( !g_lockInitialized )
+                {
+                CEGLOs::InitializeLock( &g_eglLock );
+                g_lockInitialized = true;
+                }
+            break;
+            }
+	    case DLL_THREAD_ATTACH:
+            {
+            break;
+            }
+
+	    case DLL_THREAD_DETACH:
+            {
+            break;
+            }
+	    case DLL_PROCESS_DETACH:
+            {
+            if( g_eglState )
+                {
+                EGLI_ASSERT( g_eglState->RefCount() == 0 );
+                delete g_eglState;
+                g_eglState = NULL;
+                }
+             if( g_lockInitialized )
+                {
+                CEGLOs::DestroyLock( &g_eglLock );
+                g_lockInitialized = false;
+                }
+            if( g_tlsIndex != TLS_OUT_OF_INDEXES )
+                {
+                TlsFree( g_tlsIndex );
+                }
+            break;
+            }
+        }
+#else
+switch( fdwReason )
+        {
+        case DLL_PROCESS_ATTACH:
+	    case DLL_THREAD_ATTACH:
+	    case DLL_THREAD_DETACH:
+            {
+            break;
+            }
+	    case DLL_PROCESS_DETACH:
+            {
+            EGLI_ASSERT( g_eglState == NULL );
+            break;
+            }
+        }
+#endif // EGLI_USE_PLATSIM_EXTENSIONS
+
+    return TRUE;
+    }
+
+#endif // _WIN32
+
+#ifdef __cplusplus
+}
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/linux/EGLOs.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,207 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLOs.h"
+#include "EGLState.h"
+#include "EGLProcess.h"
+#include "EGLThread.h"
+#include "EGLWindowSurface.h"
+#include "EGLDisplay.h"
+
+#include <dlfcn.h>
+
+void CEGLOs::InitializeLock( EGLI_LOCK *lock )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    }
+
+void CEGLOs::GetLock( EGLI_LOCK *lock )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    }
+
+void CEGLOs::ReleaseLock(EGLI_LOCK *lock )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    }
+
+void CEGLOs::DestroyLock( EGLI_LOCK *lock )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    }
+
+void CEGLOs::ConfigToNativePixelFormat( const CEGLConfig& config, EGLINativePixelFormatType* nativeFormat )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    }
+
+/*static*/ EGLINativeContextType CEGLOs::CreateNativeContext( const CEGLConfig& config, EGLINativeDisplayType display, EGLINativeContextType shareContext )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return NULL;
+    }
+
+EGLINativeContextType CEGLOs::CurrentNativeContext()
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return NULL;
+    }
+
+EGLINativeDisplayType CEGLOs::CurrentNativeSurface()
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return NULL;
+    }
+
+bool CEGLOs::MakeNativeContextCurrent( struct EGLINativeGLFunctions* func, EGLINativeDisplayType draw, EGLINativeDisplayType read, EGLINativeContextType context )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return false;
+    }
+
+bool CEGLOs::DestroyNativeContext( EGLINativeContextType context )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return false;
+    }
+
+bool CEGLOs::InitializeNativeGLFunctions( struct EGLINativeGLFunctions* func, EGLINativeDisplayType display, EGLINativeContextType context )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return false;
+    }
+
+struct EGLINativePbufferContainer* CEGLOs::CreateNativePbuffer( EGLINativeDisplayType display,
+        const CEGLConfig& config, EGLint width, EGLint height, EGLBoolean largestPbuffer,
+        EGLint textureFormat, EGLint textureTarget )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return NULL;
+    }
+
+bool CEGLOs::DestroyNativePbuffer( struct EGLINativePbufferContainer* container )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return false;
+    }
+
+EGLINativeWindowType CEGLOs::CreateNativeWindow( int width, int height )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return NULL;
+    }
+
+bool CEGLOs::IsValidNativeWindow( EGLINativeWindowType wnd )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return false;
+    }
+
+bool CEGLOs::GetNativeWindowSize( EGLINativeWindowType wnd, int& width, int& height )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return false;
+    }
+
+EGLIOsWindowContext* CEGLOs::CreateOSWindowContext( EGLINativeWindowType wnd, const CEGLConfig& config )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    return NULL;
+    }
+
+void CEGLOs::DestroyOSWindowContext( EGLIOsWindowContext* context )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    }
+
+void CEGLOs::BlitToOSWindow( EGLenum api, CEGLDisplay* display, EGLIOsWindowContext* context, void* buf, int w, int h, int stride )
+    {
+    // \todo
+    EGLI_ASSERT( false );
+    }
+
+void* CEGLOs::LoadHostGL()
+    {
+    EGLI_ASSERT(0);
+    return NULL;
+    }
+
+void* CEGLOs::GetGLProcAddress(EGLILibraryHandle& libraryHandle, const char* proc)
+    {
+    EGLI_ASSERT(0);
+    return NULL;
+    }
+
+bool CEGLOs::FreeClientLibrary(EGLILibraryHandle& libraryHandle)
+    {
+    //assert(libraryHandle);
+    return (dlclose(libraryHandle) == 0);
+    }
+
+IEGLtoVGInterface* CEGLOs::LoadVGInterface( void*& libraryHandle )
+    {
+    fpGetVGInterface proc;
+    void* libHandle = dlopen("libopenvg_sf.so", RTLD_NOW);
+
+    if (libHandle == NULL)
+        return NULL;
+
+    libraryHandle = libHandle;
+    proc = (fpGetVGInterface)dlsym(libHandle, "getVGInterface");
+
+    if (!proc)
+        return NULL;
+
+    return proc();
+    }
+
+IEGLtoGLES2Interface* CEGLOs::LoadGLES2Interface( void*& libraryHandle )
+    {
+    EGLI_ASSERT( false );
+    return NULL;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostegl/src/win32/EGLOs.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,807 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLOs.h"
+#include "EGLState.h"
+#include "EGLProcess.h"
+#include "EGLThread.h"
+#include "EGLWindowSurface.h"
+#include "EGLDisplay.h"
+#include "EGLContext.h"
+
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+void doBlit( EGLIOsWindowContext* context, void* buf, int width, int height, int stride )
+    {
+    if( !context->osBuffer || !context->pixmap || context->width != width || context->height != height )
+        {
+            if( context->pixmap )
+                DeleteObject( context->pixmap );
+            context->osBuffer = NULL;
+            context->pixmap = NULL;
+
+            context->width = width;
+            context->height = height;
+
+            struct
+            {
+                BITMAPINFOHEADER	header;
+                DWORD				rMask;
+                DWORD				gMask;
+                DWORD				bMask;
+            } bmi;
+            bmi.header.biSize			= sizeof( BITMAPINFOHEADER );
+            bmi.header.biWidth			= width;
+            bmi.header.biHeight			= height;
+            bmi.header.biPlanes			= 1;
+            bmi.header.biBitCount		= (WORD)32;
+            bmi.header.biCompression	= BI_BITFIELDS;
+            bmi.rMask = 0x00FF0000;
+            bmi.gMask = 0x0000FF00;
+            bmi.bMask = 0x000000FF;
+            
+            context->pixmap = CreateDIBSection( context->vgDisplay, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&context->osBuffer, NULL, 0 );
+            if( !context->pixmap )
+            {
+                context->osBuffer = NULL;
+                return;
+            }
+        }
+     
+        if( context->osBuffer )
+            {
+            HDC winDC = GetDC( context->window );
+			GdiFlush();
+            memcpy( context->osBuffer, buf, stride*height );
+            SelectObject( context->vgDisplay, context->pixmap );
+            EGLI_ASSERT( BitBlt(winDC, 0, 0, width, height, context->vgDisplay, 0, 0, SRCCOPY) );
+            ReleaseDC( context->window, winDC );
+            SelectObject( context->vgDisplay, NULL );
+        }
+    }
+#endif
+
+LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
+{
+   switch (message)
+    {
+    case WM_CLOSE:
+    case WM_DESTROY:
+        //PostQuitMessage(0);
+        return 0;
+    case WM_PAINT:
+        {
+        /*CEGLState* state = getState();
+        if( state )
+            {
+            CEGLThread* thread = state->GetCurrentProcess()->CurrentThread();
+            if( thread && thread->CurrentVGSurface() )
+                {
+                if( thread->CurrentVGSurface()->Type() == CEGLSurface::WINDOW_SURFACE )
+                    {
+                    CEGLWindowSurface* surface = (CEGLWindowSurface*)thread->CurrentVGSurface();
+                    InvalidateRect(hwnd, NULL, 0);
+                    doBlit( surface->OsContext(), surface->VGColorBuffer(), surface->Width(), surface->Height(), surface->Stride() );
+                    }
+                }
+            }*/
+        return 0;
+        }
+    default:
+        break;
+        }
+        return DefWindowProc(hwnd, message, wParam, lParam);
+}
+
+void CEGLOs::InitializeLock( EGLI_LOCK *lock )
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    InitializeCriticalSection( lock );
+#endif
+    }
+
+void CEGLOs::GetLock( EGLI_LOCK *lock )
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    EnterCriticalSection( lock );
+#endif
+    }
+
+void CEGLOs::ReleaseLock(EGLI_LOCK *lock )
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    LeaveCriticalSection( lock );
+#endif
+    }
+
+void CEGLOs::DestroyLock( EGLI_LOCK *lock )
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    DeleteCriticalSection( lock );
+#endif
+    }
+
+void CEGLOs::ConfigToNativePixelFormat( const CEGLConfig& config, EGLINativePixelFormatType* nativeFormat )
+    {
+    EGLI_ASSERT( nativeFormat != NULL );
+    memset( nativeFormat, 0, sizeof(PIXELFORMATDESCRIPTOR) );
+    nativeFormat->nSize = sizeof( PIXELFORMATDESCRIPTOR );
+    nativeFormat->nVersion = 1;
+    nativeFormat->dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; // always support OGL
+    
+    // \todo Do we need color index?
+    nativeFormat->iPixelType = PFD_TYPE_RGBA;
+    
+    // \todo overlay/underlay?
+    nativeFormat->iLayerType = PFD_MAIN_PLANE;
+
+    EGLint surfaceType = config.GetAttribute( EGL_SURFACE_TYPE );
+    if( surfaceType & EGL_WINDOW_BIT )
+        {
+        nativeFormat->dwFlags |= PFD_DRAW_TO_WINDOW;
+        }
+    if( surfaceType & EGL_PIXMAP_BIT )
+        {
+        nativeFormat->dwFlags |= PFD_DRAW_TO_BITMAP;
+        }
+    nativeFormat->cColorBits = config.GetAttribute( EGL_RED_SIZE ) +
+                               config.GetAttribute( EGL_GREEN_SIZE ) +
+                               config.GetAttribute( EGL_BLUE_SIZE );
+
+    nativeFormat->cAlphaBits = config.GetAttribute( EGL_ALPHA_SIZE );
+    nativeFormat->cDepthBits = config.GetAttribute( EGL_DEPTH_SIZE );
+    nativeFormat->cStencilBits = config.GetAttribute( EGL_STENCIL_SIZE );
+
+    // \todo Aux buffers, accumulation buffers?
+    }
+
+EGLINativeContextType CEGLOs::CreateNativeContext( const CEGLConfig& config, EGLINativeDisplayType display, EGLINativeContextType shareContext )
+    {
+    EGLINativeContextType ret = NULL;
+    DWORD error = ERROR_SUCCESS;
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    PIXELFORMATDESCRIPTOR pfd;
+    memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
+    CEGLOs::ConfigToNativePixelFormat( config, &pfd );
+	int pixelFormat = ChoosePixelFormat( display, &pfd );
+	if( !pixelFormat )
+		{
+        return ret;
+		}
+    int currentPixelFormat = GetPixelFormat( display );
+	if( !currentPixelFormat && !SetPixelFormat( display, pixelFormat, &pfd ) )
+		{
+        error = GetLastError();
+		return ret;
+		}
+    ret = wglCreateContext( display );
+	if( ret != NULL && shareContext != NULL)
+		{
+		// Share context data
+		if( !wglShareLists( shareContext, ret ) )
+			{
+			wglDeleteContext( ret );
+			ret = NULL;
+			}
+		}
+#endif
+    return ret;
+    }
+
+EGLINativeContextType CEGLOs::CurrentNativeContext()
+    {
+    return wglGetCurrentContext();
+    }
+
+EGLINativeDisplayType CEGLOs::CurrentNativeSurface()
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    return wglGetCurrentDC();
+#else
+    return NULL;
+#endif
+    }
+
+bool CEGLOs::MakeNativeContextCurrent( struct EGLINativeGLFunctions* func, EGLINativeDisplayType draw, EGLINativeDisplayType read, EGLINativeContextType context )
+    {
+    bool ret = true;
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    DWORD err;
+    EGLINativeContextType prevContext = wglGetCurrentContext();
+    EGLINativeDisplayType prevDraw = wglGetCurrentDC();
+    EGLINativeDisplayType prevRead = NULL;
+    if( prevDraw ) prevRead = func->wglGetCurrentReadDCARB();
+    if( context == NULL )
+        {
+        if( wglGetCurrentContext() != NULL )
+            {
+            //warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)
+            ret = (wglMakeCurrent( NULL, context ) != 0);
+            }
+        }
+    else
+        {
+        //warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)
+        ret = (func->wglMakeContextCurrentARB( draw, read, context ) != 0);
+        }
+    if( !ret )
+        {
+        // \todo Handle error
+        err = GetLastError();
+        // Restore previous context/surface on failure
+        func->wglMakeContextCurrentARB( prevDraw, prevRead, prevContext );        
+        }
+#endif
+    return ret;
+    }
+
+bool CEGLOs::DestroyNativeContext( EGLINativeContextType context )
+    {
+    bool ret = true;
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( context != NULL )
+        {
+        //warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)
+        ret = (wglDeleteContext( context ) != 0);
+        }
+#endif
+    return ret;
+    }
+
+bool CEGLOs::InitializeNativeGLFunctions( struct EGLINativeGLFunctions* func, EGLINativeDisplayType display, EGLINativeContextType context )
+    {
+    bool ret = true;
+    DWORD error = ERROR_SUCCESS;
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    HDC currentDC = wglGetCurrentDC();
+    HGLRC currentContext = wglGetCurrentContext();
+    
+	ret = !!wglMakeCurrent( display, context );
+    if( ret )
+        {
+        func->wglMakeContextCurrentARB = (PFNWGLMAKECONTEXTCURRENTARBPROC)wglGetProcAddress( "wglMakeContextCurrentARB" );
+        func->wglGetCurrentReadDCARB = (PFNWGLGETCURRENTREADDCARBPROC)wglGetProcAddress ( "wglGetCurrentReadDCARB" );
+        func->wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress( "wglChoosePixelFormatARB" );
+        func->wglCreatePbufferARB = (PFNWGLCREATEPBUFFERARBPROC)wglGetProcAddress( "wglCreatePbufferARB" );
+        func->wglDestroyPbufferARB = (PFNWGLDESTROYPBUFFERARBPROC)wglGetProcAddress( "wglDestroyPbufferARB" );
+        func->wglGetPbufferDCARB = (PFNWGLGETPBUFFERDCARBPROC)wglGetProcAddress( "wglGetPbufferDCARB" );
+        func->wglReleasePbufferDCARB = (PFNWGLRELEASEPBUFFERDCARBPROC)wglGetProcAddress( "wglReleasePbufferDCARB" );
+        func->wglQueryPbufferARB = (PFNWGLQUERYPBUFFERARBPROC)wglGetProcAddress( "wglQueryPbufferARB" );
+
+        if( !(func->wglChoosePixelFormatARB &&
+              func->wglCreatePbufferARB &&
+              func->wglDestroyPbufferARB &&
+              func->wglGetPbufferDCARB &&
+              func->wglMakeContextCurrentARB &&
+              func->wglGetCurrentReadDCARB &&
+              func->wglQueryPbufferARB &&
+              func->wglReleasePbufferDCARB) )
+              ret = false;
+        }
+
+    // \todo Other needed extensions.
+
+    if( !(wglMakeCurrent( currentDC, currentContext )) )
+        {
+        error = GetLastError();
+        if( error == ERROR_INVALID_HANDLE )
+            {
+            // For some reason the current DC or current wgl context was invalid.
+            // Just set them NULL for now.
+            wglMakeCurrent(NULL, NULL);
+            }
+        else
+            {
+            ret = false;
+            }
+        }
+#endif //EGLI_USE_PLATSIM_EXTENSIONS
+    return ret;
+    }
+
+struct EGLINativePbufferContainer* CEGLOs::CreateNativePbuffer( EGLINativeDisplayType display,
+        const CEGLConfig& config, EGLint width, EGLint height, EGLBoolean largestPbuffer, 
+        EGLint textureFormat, EGLint textureTarget )
+    {
+    struct EGLINativePbufferContainer* ret = EGLI_NEW EGLINativePbufferContainer;
+    if( !ret ) return NULL;
+    memset( ret, 0, sizeof(struct EGLINativePbufferContainer) );
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    EGLINativeContextType context = CEGLOs::CreateNativeContext( config, display, NULL );
+    if( !context )
+        {
+        delete ret;
+        ret = NULL;
+        return ret;
+        }
+    ret->copyContext = context;
+    if( !(CEGLOs::InitializeNativeGLFunctions( &(ret->functions), display, ret->copyContext )) )
+        {
+        CEGLOs::DestroyNativePbuffer( ret );
+        delete ret;
+        ret = NULL;
+        return ret;
+        }
+    
+    int redSize = config.GetAttribute( EGL_RED_SIZE );
+    int greenSize = config.GetAttribute( EGL_GREEN_SIZE );
+    int blueSize = config.GetAttribute( EGL_BLUE_SIZE );
+    int alphaSize = config.GetAttribute( EGL_ALPHA_SIZE );
+    int depthSize = config.GetAttribute( EGL_DEPTH_SIZE );
+    int stencilSize = config.GetAttribute( EGL_STENCIL_SIZE );
+    
+    // \todo Map EGL config properly to WGL config.
+    int attributes[] =
+        {
+        WGL_SUPPORT_OPENGL_ARB, TRUE,
+        WGL_DRAW_TO_PBUFFER_ARB, TRUE,
+        WGL_RED_BITS_ARB, redSize,
+        WGL_GREEN_BITS_ARB, greenSize,
+        WGL_BLUE_BITS_ARB, blueSize,
+        WGL_ALPHA_BITS_ARB, alphaSize,
+        WGL_DEPTH_BITS_ARB, depthSize,
+        WGL_STENCIL_BITS_ARB, stencilSize,
+        WGL_DOUBLE_BUFFER_ARB, TRUE,
+        0
+        };
+    unsigned int formatCount = 0;
+    int pixelFormat = 0;
+    if( !(ret->functions.wglChoosePixelFormatARB( display, attributes, NULL, 1, &pixelFormat, &formatCount )) )
+        {
+        EGLI_ASSERT(false);
+        DWORD err = GetLastError();
+        CEGLOs::DestroyNativePbuffer( ret );
+        delete ret;
+        ret = NULL;
+        return ret;
+        }
+    if( formatCount == 0 )
+        {
+        EGLI_ASSERT(false);
+        DWORD err = GetLastError();
+        CEGLOs::DestroyNativePbuffer( ret );
+        delete ret;
+        ret = NULL;
+        return ret;
+        }
+    int wglTextureFormat = WGL_NO_TEXTURE_ARB;
+    switch( textureFormat )
+        {
+        case EGL_TEXTURE_RGB:
+            {
+            wglTextureFormat = WGL_TEXTURE_RGB_ARB;
+            break;
+            }
+        case EGL_TEXTURE_RGBA:
+            {
+            wglTextureFormat = WGL_TEXTURE_RGBA_ARB;
+            break;
+            }
+        }
+    int wglTextureTarget = WGL_NO_TEXTURE_ARB;
+    switch( textureTarget )
+        {
+        case EGL_TEXTURE_2D:
+            {
+            wglTextureTarget = WGL_TEXTURE_2D_ARB;
+            break;
+            }      
+        }
+    int pbufferAttributes[] =
+        {
+        WGL_TEXTURE_FORMAT_ARB, wglTextureFormat,
+        WGL_TEXTURE_TARGET_ARB, wglTextureTarget,
+        WGL_PBUFFER_LARGEST_ARB, largestPbuffer,
+        0
+        };
+    ret->pbuffer = ret->functions.wglCreatePbufferARB( display, pixelFormat,
+        width, height, pbufferAttributes );
+    if( !(ret->pbuffer) )
+        {
+        EGLI_ASSERT(false);
+        DWORD err = GetLastError();
+        CEGLOs::DestroyNativePbuffer( ret );
+        delete ret;
+        ret = NULL;
+        return ret;
+        }
+    ret->display = ret->functions.wglGetPbufferDCARB( ret->pbuffer );
+    if( !(ret->display) )
+        {
+        EGLI_ASSERT(false);
+        DWORD err = GetLastError();
+        CEGLOs::DestroyNativePbuffer( ret );
+        delete ret;
+        ret = NULL;
+        return ret;
+        }
+#endif // EGLI_USE_PLATSIM_EXTENSIONS
+    return ret;
+    }
+
+bool CEGLOs::DestroyNativePbuffer( struct EGLINativePbufferContainer* container )
+    {
+    // \todo Handle errors!
+    bool ret = true;
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    DWORD err;
+    if( container->display && container->pbuffer && container->functions.wglReleasePbufferDCARB )
+        {
+        if( !(container->functions.wglReleasePbufferDCARB(container->pbuffer, container->display)) )
+            {
+            err = GetLastError();
+            ret = false;
+            }
+        }
+    if( container->pbuffer && container->functions.wglDestroyPbufferARB )
+        {
+        if( !(container->functions.wglDestroyPbufferARB(container->pbuffer)) )
+            {
+            err = GetLastError();
+            ret = false;
+            }
+        }
+    if( container->copyContext )
+        {
+        ret = CEGLOs::DestroyNativeContext( container->copyContext );
+        if( !ret )
+            {
+            err = GetLastError();
+            }
+        }
+#endif //EGLI_USE_PLATSIM_EXTENSIONS
+    return ret;
+    }
+
+EGLINativeDisplayType CEGLOs::CreateDefaultDisplay()
+    {
+    // \todo It seems that we can't use any of these DC-functions.
+    //       Problems with pixel format selection etc. at least with
+    //       NVidia and Intel GPUs, ATI/AMD seems to work with GetDC(NULL)
+    //       or CreateDC(). No idea how to create EGL_DEFAULT_DISPLAY for
+    //       NV/Intel GPUs. For now CEGLDisplay::Initialize() creates dummy
+    //       window and uses DC from that window.
+    //return (EGLINativeDisplayType)CreateDC(TEXT("DISPLAY"), TEXT("DISPLAY")/*NULL*/, NULL, NULL);
+    //return (EGLINativeDisplayType)GetDC(NULL);
+    //return GetWindowDC(NULL);
+    return NULL;
+    }
+
+void CEGLOs::DestroyDefaultDisplay( EGLINativeDisplayType display )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    // no-op
+#else
+    DeleteDC( display );
+#endif
+    }
+
+EGLINativeWindowType CEGLOs::CreateNativeWindow( int width, int height )
+    {
+    int xBorder = GetSystemMetrics( SM_CXBORDER );
+    int yBorder = GetSystemMetrics( SM_CYBORDER );
+    int caption = GetSystemMetrics( SM_CYCAPTION );
+    
+
+    WNDCLASS wndclass;
+    wndclass.style		   = 0;
+    wndclass.lpfnWndProc   = WndProc;
+    wndclass.cbClsExtra    = 0;
+    wndclass.cbWndExtra    = 0;
+    wndclass.hInstance	   = (HINSTANCE)GetModuleHandle(NULL);
+    wndclass.hIcon		   = LoadIcon(wndclass.hInstance, MAKEINTRESOURCE(101));
+    wndclass.hCursor	   = LoadCursor(NULL, IDC_ARROW);
+    wndclass.hbrBackground = NULL;
+    wndclass.lpszMenuName  = NULL;
+    wndclass.lpszClassName = "EGLMainWndClass";
+    if (!wndclass.hIcon)
+        wndclass.hIcon = LoadIcon(NULL, IDI_EXCLAMATION);
+    
+    // \todo We should store this class somewhere
+    RegisterClass(&wndclass);
+
+    EGLINativeWindowType window = CreateWindow(
+        "EGLMainWndClass",
+        "Platsim EGL window",
+        WS_OVERLAPPEDWINDOW,
+        0, 0,
+        width /*+ 2*xBorder*/,
+        height /*+ 2*yBorder + caption*/,
+        NULL,
+        NULL,
+        (HINSTANCE)GetModuleHandle(NULL),
+        NULL);
+    return window;
+    }
+
+void CEGLOs::DestroyNativeWindow( EGLINativeWindowType wnd )
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if( wnd )
+        EGLI_ASSERT( DestroyWindow( wnd ) );
+    // \todo Should use stored WNDCLASS to unregister, see CEGLOs::CreateNativeWindow()
+    UnregisterClass( "EGLMainWndClass", (HINSTANCE)GetModuleHandle(NULL) );
+#endif
+    }
+
+bool CEGLOs::IsValidNativeDisplay( EGLINativeDisplayType dsp )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    // we can't validate symbian display
+    return true;
+#else
+    // Check if we have invalid handle or handle is not display
+    bool ret = true;
+    DWORD err = GetLastError();
+    SetLastError( ERROR_SUCCESS );
+    int technology = GetDeviceCaps( dsp, TECHNOLOGY );
+    if( GetLastError() == ERROR_INVALID_HANDLE || technology != DT_RASDISPLAY )
+        {
+        ret = false;
+        }
+    SetLastError( err );
+    return ret;
+#endif
+    }
+
+bool CEGLOs::IsValidNativeWindow( EGLINativeWindowType wnd )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    // We can't validate symbian window
+    return true;
+#else
+    bool ret = false;
+    if( wnd )
+        {
+        // \todo should we skip thread id check?
+        DWORD processId = GetCurrentProcessId();
+        DWORD threadId = GetCurrentThreadId();
+        DWORD windowProcessId;
+        DWORD windowThreadId = GetWindowThreadProcessId( wnd, &windowProcessId );
+        ret = ((threadId == windowThreadId) && (processId == windowProcessId));
+        }
+    return ret;
+#endif //EGLI_USE_PLATSIM_EXTENSIONS
+    }
+
+bool CEGLOs::GetNativeWindowSize( EGLINativeWindowType wnd, int& width, int& height )
+    {
+#if defined( EGLI_USE_PLATSIM_EXTENSIONS )
+    // Window size is transferred through eglPlatsimSetSurfaceParameters()
+    return true;
+
+#else
+    bool ret = false;
+    RECT rect;
+    ret = !!GetClientRect( wnd, &rect );
+    if( ret )
+        {
+        width = rect.right - rect.left;
+        height = rect.bottom - rect.top;
+        }
+    return ret;
+#endif
+    }
+
+EGLIOsWindowContext* CEGLOs::CreateOSWindowContext( EGLINativeWindowType wnd, const CEGLConfig& config )
+    {
+    EGLIOsWindowContext* ctx = NULL;
+    ctx = EGLI_NEW EGLIOsWindowContext;
+    if( !ctx )
+        {
+        return NULL;
+        }
+    ctx->window = wnd;
+    ctx->vgDisplay = NULL;
+    ctx->glesDisplay = NULL;
+    ctx->pixmap = NULL;
+    ctx->osBuffer = NULL;
+    ctx->width = 0;
+    ctx->height = 0;
+    ctx->colorBuf = NULL;
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    // no-op
+#else
+    if( ctx->window )
+        {
+        EGLint renderableType = config.GetAttribute( EGL_RENDERABLE_TYPE );
+        if( renderableType & EGL_OPENVG_BIT )
+            {
+            HDC winDC = GetDC(ctx->window);
+            ctx->vgDisplay = CreateCompatibleDC(winDC);
+            ReleaseDC(ctx->window, winDC);
+            if(!ctx->vgDisplay)
+                {
+                delete ctx;
+                return NULL;
+                }
+            }
+        if( renderableType & EGL_OPENGL_ES_BIT )
+            {
+            HDC winDC = GetDC(ctx->window);
+            ctx->glesDisplay = winDC;
+            if(!ctx->glesDisplay)
+                {
+                delete ctx;
+                return NULL;
+                }
+            PIXELFORMATDESCRIPTOR pfd;
+            CEGLOs::ConfigToNativePixelFormat( config, &pfd );
+
+	        int pixelFormat = ChoosePixelFormat( ctx->glesDisplay, &pfd );
+	        if( !pixelFormat )
+		        {
+                EGLI_ASSERT( false );
+		        }
+	        if( !SetPixelFormat(ctx->glesDisplay, pixelFormat, &pfd ) )
+		        {
+		        EGLI_ASSERT( false );
+		        }
+            }
+        }
+#endif
+    return ctx;
+    }
+
+void CEGLOs::DestroyOSWindowContext( EGLIOsWindowContext* context )
+    {
+#if !defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    if(!context->vgDisplay)
+        {
+        SelectObject(context->vgDisplay, NULL);
+        DeleteDC(context->vgDisplay);
+        }
+    if( context->glesDisplay )
+        {
+        ReleaseDC( context->window, context->glesDisplay );
+        }
+    if( context->pixmap )
+        DeleteObject( context->pixmap );
+    if( context->colorBuf )
+        free( context->colorBuf );
+    delete context;
+#else
+    delete context;
+#endif
+    }
+
+void CEGLOs::BlitToOSWindow( EGLenum api, CEGLDisplay* display, EGLIOsWindowContext* context, void* buf, int width, int height, int stride )
+    {
+#if defined(EGLI_USE_PLATSIM_EXTENSIONS)
+    // \todo GLES
+    CEGLState* state = getState();
+    if( !state )
+        return;
+    CEGLThread* thread = state->GetCurrentProcess()->CurrentThread();
+    switch( api )
+        {
+        case EGL_OPENVG_API:
+            {
+            if( thread && state->VGInterface() )
+                {                
+                if( thread->CurrentVGSurface() )
+                    {
+                    CEGLSurface* surface = thread->CurrentVGSurface();
+                    EGLI_ASSERT( surface->Type() == CEGLSurface::WINDOW_SURFACE );
+                    state->VGInterface()->CopyBuffers( buf, -stride, surface->VGClientSurface() );
+                    }
+                }
+            break;
+            }
+        case EGL_OPENGL_ES_API:
+            {
+                if (state->GLESInterface(thread->CurrentGLESContext()->ClientVersion()))
+                {
+                // \todo
+                }
+            break;
+            }
+        }
+#else
+    if( api == EGL_OPENGL_ES_API )
+        {
+        SwapBuffers( context->glesDisplay );
+        }
+    else
+        {
+        doBlit(context, buf, width, height, stride);
+        }
+#endif
+    }
+
+EGLILibraryHandle CEGLOs::LoadHostGL()
+    {
+    return LoadLibrary( TEXT("opengl32.dll") );
+    }
+
+void* CEGLOs::GetGLProcAddress(EGLILibraryHandle& libraryHandle, const char* proc)
+    {
+    void* addr = GetProcAddress(libraryHandle, proc);
+	if(!addr)
+		{
+		addr = wglGetProcAddress(proc);
+		}
+
+	return addr;
+    }
+
+bool CEGLOs::FreeClientLibrary(EGLILibraryHandle& libraryHandle)
+    {
+    // != 0 added to expression below because of
+    // warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' (performance warning)
+    return (FreeLibrary( libraryHandle ) != 0);
+    }
+
+IEGLtoVGInterface* CEGLOs::LoadVGInterface( EGLILibraryHandle& libraryHandle )
+    {
+    IEGLtoVGInterface* iFace = NULL;
+    fpGetVGInterface proc;
+    libraryHandle = LoadLibrary( TEXT("libOpenVG.dll") );
+    if( libraryHandle != NULL )
+        {
+        proc = (fpGetVGInterface)GetProcAddress( libraryHandle, "getVGInterface" );
+        if( proc != NULL )
+            {
+            iFace = proc();
+            }
+        }
+    return iFace;
+    }
+
+IEGLtoGLESInterface* CEGLOs::LoadGLES1Interface( EGLILibraryHandle& libraryHandle )
+    {
+    IEGLtoGLESInterface* iFace = NULL;
+    fpGetGLES1Interface proc;
+    libraryHandle = LoadLibrary( TEXT("libGLESv1.dll") );
+    if( libraryHandle != NULL )
+        {
+        proc = (fpGetGLES1Interface)GetProcAddress( libraryHandle, "getGLESInterface" );
+        if( proc != NULL )
+            {
+            iFace = proc();
+            }
+        }
+    return iFace;
+    }
+
+IEGLtoGLES2Interface* CEGLOs::LoadGLES2Interface( EGLILibraryHandle& libraryHandle )
+    {
+    IEGLtoGLES2Interface* iFace = NULL;
+    fpGetGLES2Interface proc;
+    libraryHandle = LoadLibrary( TEXT("libGLESv2.dll") );
+    if( libraryHandle != NULL )
+        {
+        proc = (fpGetGLES2Interface)GetProcAddress( libraryHandle, "getGLES2Interface" );
+        if( proc != NULL )
+            {
+            iFace = proc();
+            }
+        }
+    return iFace;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/CMakeLists.txt	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,74 @@
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+# CMake meta build file for host libGLESv1
+
+set(GLES_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)
+set(GLES_INC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/inc)
+
+if(WIN32)
+	message("*** EGL Win32")
+	set(GLES_SSE_FLAGS "/arch:SSE2")
+	set(GLES_PLATFORM_LINK_LIBRARIES "")
+else(WIN32)
+	set(GLES_SSE_FLAGS "-msse2 -mfpmath=sse -march=pentium4")
+	set(GLES_PLATFORM_LINK_LIBRARIES m stdc++)
+endif(WIN32)
+
+set(GLES_SRC_FILES
+    ${GLES_INC_DIR}/EGLInterface.h
+    ${GLES_INC_DIR}/glDefinitions.h
+    ${GLES_INC_DIR}/GLESArray.h
+    ${GLES_INC_DIR}/GLESBuffer.h
+    ${GLES_INC_DIR}/GLESContext.h
+    ${GLES_INC_DIR}/GLESDesktopGL.h
+    ${GLES_INC_DIR}/glesGet.h
+    ${GLES_INC_DIR}/glesInternal.h
+    ${GLES_INC_DIR}/glesOS.h
+    ${GLES_INC_DIR}/GLESTexture.h
+
+    ${GLES_SRC_DIR}/EGLInterface.cpp
+    ${GLES_SRC_DIR}/glesapi.cpp
+    ${GLES_SRC_DIR}/GLESArray.cpp
+    ${GLES_SRC_DIR}/GLESContext.cpp
+    ${GLES_SRC_DIR}/GLESDesktopGL.cpp
+    ${GLES_SRC_DIR}/glesGet.cpp
+    ${GLES_SRC_DIR}/glesOS.cpp
+    ${GLES_SRC_DIR}/GLESTexture.cpp
+  )
+
+include_directories(
+  ${GLES_SRC_DIR}
+  ${GLES_INC_DIR}
+  ${COMMON_INC_DIR}
+  )
+
+add_definitions(-DKHRONOS_APICALL_EXPORT)
+
+add_library(${LIBRARY_NAME_PREFIX}GLESv1 SHARED ${GLES_SRC_FILES})
+
+target_link_libraries(${LIBRARY_NAME_PREFIX}GLESv1 ${GLES_PLATFORM_LINK_LIBRARIES})
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/EGLInterface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,72 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _EGLINTERFACE_H_
+#define _EGLINTERFACE_H_
+
+#include "GLESInterface.h"
+#include "glesInternal.h"
+#include <set>
+
+extern "C"
+{
+GLES_API_CALL IEGLtoGLESInterface* getGLESInterface(void);
+
+void glesReleaseTexImage(void* surface, int name, int level);
+}
+
+class GLESContext;
+
+class EGLtoGLESInterface : public IEGLtoGLESInterface
+{
+public:
+    EGLtoGLESInterface();
+
+    void SetEGLInterface(IGLEStoEGLInterface* egl);
+	void* CreateContext(void* nativeContext);
+	bool ReleaseContext(void* context);
+	void* GetNativeContext(void* context);
+	fpGLProc GetGLProcAddress( const char *procname );
+    int BindTexImage( void* surface, int level, bool generateMipmap, const SurfaceDescriptor* desc, void* buffer );
+	bool ReleaseTexImage( int name, int level );
+    bool CopyBuffers( void* buf, const SurfaceDescriptor* desc );
+    bool UpdateBuffers( void* buf, const SurfaceDescriptor* desc );
+    void Flush();
+    void Finish();
+
+	// Methods for local OpenGL ES -implementation. To be called only from OpenGL ES internals.
+    static IGLEStoEGLInterface* GetEGLInterface();
+
+private:
+    IGLEStoEGLInterface* m_egl;
+	std::set<GLESContext*> m_contexts;
+};
+
+#endif // _EGLINTERFACE_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/GLESArray.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,87 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLESARRAY_H_
+#define _GLESARRAY_H_
+
+#include <GLES/gl.h>
+#include <cstddef>
+#include "GLESBuffer.h"
+
+class GLESArrayPointer
+{
+public:
+	GLESArrayPointer();
+	GLESArrayPointer(const void* pointer, int stride, int size, GLenum type);
+
+	int Size() { return m_size; }
+	GLenum Type() { return m_type; }
+
+	bool operator!=(void* pointer) { return m_pointer != pointer; }
+	GLESArrayPointer& operator+=(int step) { m_pointer += step * m_stride; return *this; }
+	const void* operator[](int i) { return m_pointer + i * m_stride; }
+
+private:
+	const char* m_pointer;
+	int m_stride;
+	int m_size;
+	GLenum m_type;
+};
+
+class GLESArray
+{
+public:
+	GLESArray();
+	GLESArray(int size, GLenum type, int stride, void* pointer, const GLESBuffer* buffer, bool ownsData=false);
+	~GLESArray();
+
+	int Size() const { return m_size; }
+	GLenum Type() const { return m_type; }
+	int Stride() const { return m_stride; }
+	const void* Pointer() const { return m_pointer; }
+	GLESArrayPointer ArrayPointer() const;
+	const GLESBuffer* Buffer() const { return m_buffer; }
+	unsigned int BufferName() const { return m_buffer ? m_buffer->name : 0; }
+	const void* BufferPointer() const { return m_buffer ? m_buffer->data : NULL; }
+
+	GLESArray* Convert(int count) const;
+
+	void ReleaseBuffer() { m_buffer = NULL; }
+	
+private:
+	int m_size;
+	GLenum m_type;
+	int m_stride;
+	void* m_pointer;
+	bool m_ownsData;
+	const GLESBuffer* m_buffer;
+};
+
+#endif // _GLESARRAY_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/GLESBuffer.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,47 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLESBUFFER_H_
+#define _GLESBUFFER_H_
+
+#include <GLES/gl.h>
+
+struct GLESBuffer
+{
+	GLESBuffer(GLuint buffer) : name(buffer), size(0), data(NULL), usage(GL_STATIC_DRAW) {}
+	~GLESBuffer() { delete[] data; };
+
+	GLuint name;
+	GLsizeiptr size;
+	char* data;
+	GLenum usage;
+};
+
+#endif // _GLESBUFFER_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/GLESContext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,205 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLESCONTEXT_H_
+#define _GLESCONTEXT_H_
+
+#include <GLES/gl.h>
+#include <map>
+#include <iostream>
+#include "GLESArray.h"
+#include "glesInternal.h"
+#include "GLESDesktopGL.h"
+#include "glesOS.h"
+#include "EGLInterface.h"
+
+struct GLESBuffer;
+class GLESTexture;
+struct GLESTextureLevel;
+
+namespace
+{
+typedef std::map<unsigned int, GLESBuffer*> BufferMap;
+typedef std::map<unsigned int, GLESTexture*> TextureMap;
+}
+
+enum GLESArrayFlag
+{
+	GLES_INVALID_ARRAY			= 0,
+	GLES_VERTEX_ARRAY			= 1 << 0,
+	GLES_NORMAL_ARRAY			= 1 << 1,
+	GLES_COLOR_ARRAY			= 1 << 2,
+	GLES_POINT_SIZE_ARRAY		= 1 << 3,
+	GLES_TEXTURE_COORD_ARRAY	= 1 << 4
+};
+
+class GLESContext {
+public:
+	GLESContext(void* nativeContext);
+	~GLESContext();
+
+	bool Initialize();
+
+	bool IsInitialized() const { return m_initialized; }
+	const GLESDesktopGL& DGL() const { return m_dgl; }
+	void* NativeContext() const { return m_nativeContext; }
+	GLenum Error() const { return m_error; }
+	GLenum GetHostError();
+	unsigned int MaxTextureLevel() const { return m_maxTextureLevel; }
+	unsigned int MaxTextureUnits() const { return m_maxTextureUnits; }
+	unsigned int MaxClipPlanes() const { return m_maxClipPlanes; }
+	unsigned int MaxLights() const { return m_maxLights; }
+	int ClientActiveTexture() const { return m_clientActiveTexture; }
+	GLESArray& VertexArray() { return m_vertexArray; }
+	const GLESArray& VertexArray() const { return m_vertexArray; }
+	GLESArray& NormalArray() { return m_normalArray; }
+	const GLESArray& NormalArray() const { return m_normalArray; }
+	GLESArray& ColorArray() { return m_colorArray; }
+	const GLESArray& ColorArray() const { return m_colorArray; }
+	const GLESArray& PointSizeArray() const { return m_pointSizeArray; }
+	GLESArray& TexCoordArray(unsigned int texture);
+	GLESArray& TexCoordArray();
+	const GLESArray& TexCoordArray(unsigned int texture) const;
+	const GLESArray& TexCoordArray() const;
+	unsigned int ArrayBufferBinding() const { return m_arrayBufferBinding; }
+	GLESBuffer* ArrayBuffer();
+	unsigned int ElementArrayBufferBinding() const { return m_elementArrayBufferBinding; }
+	GLESBuffer* ElementArrayBuffer();
+	const GLESBuffer* Buffer(unsigned int buffer) const;
+	unsigned int TextureBinding() const { return m_textureBinding; }
+	GLESTexture* Texture(unsigned int name);
+	const GLESTextureLevel* TextureLevel(GLint level) const;
+
+	bool IsArrayEnabled(GLESArrayFlag array) const { return !!(m_enabledArrays & array); }
+
+	void SetError(GLenum error) { m_error = error; }
+	void SetClientActiveTexture(int texture) { m_clientActiveTexture = texture; }
+	void SetVertexArray(int size, GLenum type, int stride, const void *pointer);
+	void SetNormalArray(GLenum type, int stride, const void *pointer);
+	void SetColorArray(int size, GLenum type, int stride, const void *pointer);
+	void SetPointerSizeArray(GLenum type, int stride, const void *pointer);
+	void SetTexCoordArray(int size, GLenum type, int stride, const void *pointer);
+
+	void EnableArray(GLESArrayFlag array) { m_enabledArrays |= array; }
+	void DisableArray(GLESArrayFlag array) { m_enabledArrays &= ~array; }
+
+	void ReserveBufferNames(int num, unsigned int* names);
+	void DeleteBuffer(unsigned int buffer);
+	
+	bool BindArrayBuffer(unsigned int buffer);
+	bool BindElementArrayBuffer(unsigned int buffer);
+
+	void DeleteTexture(unsigned int texture);
+	bool BindTexture(unsigned int texture);
+
+private:
+	bool m_initialized;
+	void* m_nativeContext;
+	GLESDesktopGL m_dgl;
+	GLenum m_error;
+	unsigned int m_maxTextureLevel;
+	unsigned int m_maxTextureUnits;
+	unsigned int m_maxClipPlanes;
+	unsigned int m_maxLights;
+	int m_clientActiveTexture;
+	GLESArray m_vertexArray;
+	GLESArray m_normalArray;
+	GLESArray m_colorArray;
+	GLESArray m_pointSizeArray;
+	GLESArray* m_texCoordArray;
+	unsigned int m_enabledArrays;
+	unsigned int m_arrayBufferBinding;
+	unsigned int m_elementArrayBufferBinding;
+	unsigned int m_textureBinding;
+	BufferMap m_buffers;
+	TextureMap m_textures;
+};
+
+void* glesGetCurrentGLESContext();
+
+#define GLES_ENTER_RET(RETVAL) \
+	GLESContext* ctx; \
+	do \
+	{ \
+		glesGetLock(); \
+		ctx = (GLESContext*)glesGetCurrentGLESContext(); \
+		if(!ctx) \
+		{ \
+			glesReleaseLock(); \
+			return RETVAL; \
+		} \
+		if(!ctx->IsInitialized()) \
+		{ \
+			if(!ctx->Initialize()) \
+			{ \
+				std::cerr << "Failed to initialize context" << std::endl; \
+				exit(1); \
+			} \
+		} \
+	} while(0)
+
+#define GLES_ENTER() GLES_ENTER_RET(GLES_NO_RETVAL)
+
+// Check the host error after every API function call so that the error flag
+// in the wrapper always contains the latest error.
+#define GLES_LEAVE_RET(RETVAL) \
+	do \
+	{ \
+		ctx->GetHostError(); \
+		glesReleaseLock(); \
+		return RETVAL; \
+	} while(0)
+
+#define GLES_LEAVE() GLES_LEAVE_RET(GLES_NO_RETVAL)
+
+#define GLES_LEAVE_NO_ERROR_CHECK_RET(RETVAL) \
+	do \
+	{ \
+		glesReleaseLock(); \
+		return RETVAL; \
+	} while(0)
+
+#define GLES_LEAVE_NO_ERROR_CHECK() GLES_LEAVE_NO_ERROR_CHECK_RET(GLES_NO_RETVAL)
+
+#define GLES_ERROR_IF_RET(COND, ERROR, RETVAL) \
+	do \
+	{ \
+		if(COND) \
+		{ \
+			ctx->SetError(ERROR); \
+			return RETVAL; \
+		} \
+	} while(0)
+
+#define GLES_ERROR_IF(COND, ERROR) GLES_ERROR_IF_RET(COND, ERROR, GLES_NO_RETVAL)
+#define GLES_ERROR_RET(ERROR, RETVAL) GLES_ERROR_IF_RET(true, ERROR, RETVAL)
+#define GLES_ERROR(ERROR) GLES_ERROR_IF(true, ERROR)
+
+#endif // _GLESCONTEXT_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/GLESDesktopGL.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,177 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _DESKTOPGL_H_
+#define _DESKTOPGL_H_
+
+#include <GLES/gl.h>
+#include "glesInternal.h"
+
+class GLESDesktopGL
+{
+public:
+	GLESDesktopGL();
+
+	bool Load();
+
+	void (GL_APIENTRY *glActiveTexture) ( GLenum texture );
+	void (GL_APIENTRY *glAlphaFunc) (GLenum func, GLclampf ref);
+	void (GL_APIENTRY *glBegin)( GLenum mode );
+	void (GL_APIENTRY *glBindBuffer) (GLenum target, GLuint buffer);
+	void (GL_APIENTRY *glBindTexture) (GLenum target, GLuint texture);
+	void (GL_APIENTRY *glBlendFunc) (GLenum sfactor, GLenum dfactor);
+	void (GL_APIENTRY *glBufferData) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
+	void (GL_APIENTRY *glBufferSubData) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+	void (GL_APIENTRY *glClear) (GLbitfield mask);
+	void (GL_APIENTRY *glClearColor) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+	void (GL_APIENTRY *glClearDepth) (GLclampd depth);
+	void (GL_APIENTRY *glClearStencil) (GLint s);
+	void (GL_APIENTRY *glClientActiveTexture) ( GLenum texture );
+	void (GL_APIENTRY *glClipPlane) (GLenum plane, const GLdouble *equation);
+	void (GL_APIENTRY *glColor4d) (GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+	void (GL_APIENTRY *glColor4f) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+	void (GL_APIENTRY *glColor4fv) ( const GLfloat *v );
+	void (GL_APIENTRY *glColor4ub) (GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+	void (GL_APIENTRY *glColor4ubv) ( const GLubyte *v );
+	void (GL_APIENTRY *glColorMask) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+	void (GL_APIENTRY *glColorPointer) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+	void (GL_APIENTRY *glCompressedTexImage2D) ( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data );
+	void (GL_APIENTRY *glCompressedTexSubImage2D) ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data );
+	void (GL_APIENTRY *glCopyTexImage2D) (GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+	void (GL_APIENTRY *glCopyTexSubImage2D) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+	void (GL_APIENTRY *glCullFace) (GLenum mode);
+	void (GL_APIENTRY *glDeleteBuffers) (GLsizei n, const GLuint *buffers);
+	void (GL_APIENTRY *glDeleteTextures) (GLsizei n, const GLuint *textures);
+	void (GL_APIENTRY *glDepthFunc) (GLenum func);
+	void (GL_APIENTRY *glDepthMask) (GLboolean flag);
+	void (GL_APIENTRY *glDepthRange) (GLclampd zNear, GLclampd zFar);
+	void (GL_APIENTRY *glDisable) (GLenum cap);
+	void (GL_APIENTRY *glDisableClientState) (GLenum array);
+	void (GL_APIENTRY *glDrawArrays) (GLenum mode, GLint first, GLsizei count);
+	void (GL_APIENTRY *glDrawElements) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+	void (GL_APIENTRY *glEnable) (GLenum cap);
+	void (GL_APIENTRY *glEnableClientState) (GLenum array);
+	void (GL_APIENTRY *glEnd) ( void );
+	void (GL_APIENTRY *glFinish) (void);
+	void (GL_APIENTRY *glFlush) (void);
+	void (GL_APIENTRY *glFogf) (GLenum pname, GLfloat param);
+	void (GL_APIENTRY *glFogfv) (GLenum pname, const GLfloat *params);
+	void (GL_APIENTRY *glFrontFace) (GLenum mode);
+	void (GL_APIENTRY *glFrustum) (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+	void (GL_APIENTRY *glGenBuffers) (GLsizei n, GLuint *buffers);
+	void (GL_APIENTRY *glGenTextures) (GLsizei n, GLuint *textures);
+	void (GL_APIENTRY *glGetBooleanv) (GLenum pname, GLboolean *params);
+	void (GL_APIENTRY *glGetBufferParameteriv) (GLenum, GLenum, GLint *);
+	void (GL_APIENTRY *glGetClipPlane) (GLenum plane, GLdouble *equation);
+	void (GL_APIENTRY *glGetDoublev) ( GLenum pname, GLdouble *params );
+	GLenum (GL_APIENTRY *glGetError) (void);
+	void (GL_APIENTRY *glGetFloatv) (GLenum pname, GLfloat *params);
+	void (GL_APIENTRY *glGetIntegerv) (GLenum pname, GLint *params);
+	void (GL_APIENTRY *glGetLightfv) (GLenum light, GLenum pname, GLfloat *params);
+	void (GL_APIENTRY *glGetMaterialfv) (GLenum face, GLenum pname, GLfloat *params);
+	void (GL_APIENTRY *glGetPointerv) (GLenum pname, GLvoid* *params);
+	const GLubyte * (GL_APIENTRY *glGetString) (GLenum name);
+	void (GL_APIENTRY *glGetTexEnvfv) (GLenum target, GLenum pname, GLfloat *params);
+	void (GL_APIENTRY *glGetTexEnviv) (GLenum target, GLenum pname, GLint *params);
+	void (GL_APIENTRY *glGetTexParameterfv) (GLenum target, GLenum pname, GLfloat *params);
+	void (GL_APIENTRY *glGetTexParameteriv) (GLenum target, GLenum pname, GLint *params);
+	void (GL_APIENTRY *glHint) (GLenum target, GLenum mode);
+	GLboolean (GL_APIENTRY *glIsBuffer) (GLuint);
+	GLboolean (GL_APIENTRY *glIsEnabled) (GLenum cap);
+	GLboolean (GL_APIENTRY *glIsTexture) (GLuint texture);
+	void (GL_APIENTRY *glLightf) (GLenum light, GLenum pname, GLfloat param);
+	void (GL_APIENTRY *glLightfv) (GLenum light, GLenum pname, const GLfloat *params);
+	void (GL_APIENTRY *glLightModelf) (GLenum pname, GLfloat param);
+	void (GL_APIENTRY *glLightModelfv) (GLenum pname, const GLfloat *params);
+	void (GL_APIENTRY *glLineWidth) (GLfloat width);
+	void (GL_APIENTRY *glLoadIdentity) (void);
+	void (GL_APIENTRY *glLoadMatrixf) (const GLfloat *m);
+	void (GL_APIENTRY *glLogicOp) (GLenum opcode);
+	void (GL_APIENTRY *glMaterialf) (GLenum face, GLenum pname, GLfloat param);
+	void (GL_APIENTRY *glMaterialfv) (GLenum face, GLenum pname, const GLfloat *params);
+	void (GL_APIENTRY *glMultiTexCoord2fv) ( GLenum target, const GLfloat *v );
+	void (GL_APIENTRY *glMultiTexCoord2sv) ( GLenum target, const GLshort *v );
+	void (GL_APIENTRY *glMultiTexCoord3fv) ( GLenum target, const GLfloat *v );
+	void (GL_APIENTRY *glMultiTexCoord3sv) ( GLenum target, const GLshort *v );
+	void (GL_APIENTRY *glMultiTexCoord4f) ( GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q );
+	void (GL_APIENTRY *glMultiTexCoord4fv) ( GLenum target, const GLfloat *v );
+	void (GL_APIENTRY *glMultiTexCoord4sv) ( GLenum target, const GLshort *v );
+	void (GL_APIENTRY *glMultMatrixf) (const GLfloat *m);
+	void (GL_APIENTRY *glNormal3f) (GLfloat nx, GLfloat ny, GLfloat nz);
+	void (GL_APIENTRY *glNormal3fv) ( const GLfloat *v );
+	void (GL_APIENTRY *glNormal3sv) ( const GLshort *v );
+	void (GL_APIENTRY *glOrtho) (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+	void (GL_APIENTRY *glPointParameterf) (GLenum, GLfloat);
+	void (GL_APIENTRY *glPointParameterfv) (GLenum, const GLfloat *);
+	void (GL_APIENTRY *glPointSize) (GLfloat size);
+	void (GL_APIENTRY *glPolygonOffset) (GLfloat factor, GLfloat units);
+	void (GL_APIENTRY *glRotatef) (GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+	void (GL_APIENTRY *glScalef) (GLfloat x, GLfloat y, GLfloat z);
+	void (GL_APIENTRY *glTexEnvf) (GLenum target, GLenum pname, GLfloat param);
+	void (GL_APIENTRY *glTexEnvfv) (GLenum target, GLenum pname, const GLfloat *params);
+	void (GL_APIENTRY *glTexParameterf) (GLenum target, GLenum pname, GLfloat param);
+	void (GL_APIENTRY *glTexParameterfv) (GLenum target, GLenum pname, const GLfloat *params);
+	void (GL_APIENTRY *glMatrixMode) (GLenum mode);
+	void (GL_APIENTRY *glNormalPointer) (GLenum type, GLsizei stride, const GLvoid *pointer);
+	void (GL_APIENTRY *glPixelStorei) (GLenum pname, GLint param);
+	void (GL_APIENTRY *glPopMatrix) (void);
+	void (GL_APIENTRY *glPushMatrix) (void);
+	void (GL_APIENTRY *glReadPixels) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+	void (GL_APIENTRY *glSampleCoverage) ( GLclampf value, GLboolean invert );
+	void (GL_APIENTRY *glScissor) (GLint x, GLint y, GLsizei width, GLsizei height);
+	void (GL_APIENTRY *glShadeModel) (GLenum mode);
+	void (GL_APIENTRY *glStencilFunc) (GLenum func, GLint ref, GLuint mask);
+	void (GL_APIENTRY *glStencilMask) (GLuint mask);
+	void (GL_APIENTRY *glStencilOp) (GLenum fail, GLenum zfail, GLenum zpass);
+	void (GL_APIENTRY *glTexCoordPointer) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+	void (GL_APIENTRY *glTexEnvi) (GLenum target, GLenum pname, GLint param);
+	void (GL_APIENTRY *glTexEnviv) (GLenum target, GLenum pname, const GLint *params);
+	void (GL_APIENTRY *glTexImage2D) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+	void (GL_APIENTRY *glTexParameteri) (GLenum target, GLenum pname, GLint param);
+	void (GL_APIENTRY *glTexParameteriv) (GLenum target, GLenum pname, const GLint *params);
+	void (GL_APIENTRY *glTexSubImage2D) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+	void (GL_APIENTRY *glTranslatef) (GLfloat x, GLfloat y, GLfloat z);
+	void (GL_APIENTRY *glVertex2fv) ( const GLfloat *v );
+	void (GL_APIENTRY *glVertex2sv) ( const GLshort *v );
+	void (GL_APIENTRY *glVertex3fv) ( const GLfloat *v );
+	void (GL_APIENTRY *glVertex3sv) ( const GLshort *v );
+	void (GL_APIENTRY *glVertex4fv) ( const GLfloat *v );
+	void (GL_APIENTRY *glVertex4sv) ( const GLshort *v );
+	void (GL_APIENTRY *glVertexPointer) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+	void (GL_APIENTRY *glViewport) (GLint x, GLint y, GLsizei width, GLsizei height);
+    
+    // for internal use in EGLtoGLESInterface::UpdateBuffers()
+    void (GL_APIENTRY *glDrawPixels) (GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+
+private:
+	bool m_loaded;
+};
+
+#endif // _DESKTOPGL_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/GLESTexture.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,67 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLESTEXTURE_H_
+#define _GLESTEXTURE_H_
+
+#include <GLES/gl.h>
+
+struct GLESTextureLevel
+{
+	GLenum format;
+	GLsizei width;
+	GLsizei height;
+	void* boundSurface; // The EGLSurface bound to this image with eglBindTexImage.
+};
+
+class GLESTexture
+{
+public:
+	GLESTexture(GLuint name);
+	bool AllocateLevels(int numLevels);
+	~GLESTexture();
+
+	GLuint Name() const { return m_name; }
+	GLESTextureLevel* Level(int level);
+
+	void SetLevel(int level, GLenum format, GLsizei width, GLsizei height);
+	void GenerateMipmap();
+
+private:
+	GLuint m_name;
+	int m_numLevels;
+	GLESTextureLevel* m_levels;
+};
+
+bool glesIsValidCompressedFormat(GLenum format);
+GLenum glesMapCompressedToBaseFormat(GLenum format);
+void* glesUncompressImage(int level, GLenum format, int width, int height, int imageSize, const void* data);
+
+#endif // _GLES_TEXTURE_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/glDefinitions.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,37 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _gldefinitions_h_
+#define _gldefinitions_h_
+
+#define GL_VERSION_MAJOR 1
+#define GL_VERSION_MINOR 1
+
+#endif // _gldefinitions_h_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/glesGet.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,51 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLESGET_H_
+#define _GLESGET_H_
+
+#include <GLES/gl.h>
+
+class GLESContext;
+class GLESDesktopGL;
+
+enum GLESGetType
+{
+	GLES_TYPE_BOOLEAN,
+	GLES_TYPE_INTEGER,
+	GLES_TYPE_ENUM,
+	GLES_TYPE_FLOAT,
+	GLES_TYPE_DOUBLE,
+	GLES_TYPE_FIXED
+};
+
+bool glesGetParameter(const GLESContext& context, const GLESDesktopGL &dgl, GLenum pname, GLESGetType dstType, void* params);
+
+#endif // _GLESGET_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/glesInternal.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,136 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLINTERNAL_H_
+#define _GLINTERNAL_H_
+
+#include "glesOS.h"
+#include <GLES/gl.h>
+#include <new>
+
+#define X_TO_D(x) ((x) / 65536.0)
+#define X_TO_F(x) ((x) / 65536.0f)
+#define D_TO_X(d) ((d) > 32767.65535 ? 32767 * 65536 + 65535 : \
+                   (d) < -32768.65535 ? -32768 * 65536 + 65535 : \
+                   ((GLfixed) ((d) * 65536)))
+#define F_TO_X(f) D_TO_X(f)
+#define F_TO_D(f) ((double) (f))
+#define I_TO_X(i) ((GLfixed) ((i) * 65536))
+#define X_TO_I(x) ((x) / 65536)
+
+#include <assert.h>
+
+#if defined(_DEBUG)
+#define GLES_ASSERT assert
+#else // defined(_DEBUG)
+#define GLES_ASSERT
+#endif // !defined(_DEBUG)
+
+#define GLES_NEW new(std::nothrow)
+
+// Types not in OpenGL ES
+typedef double GLdouble;
+typedef double GLclampd;
+
+// Definitions not in OpenGL ES
+#define GL_POINT_SIZE_ARRAY 			0x8B9C
+#define GL_POINT_SPRITE					0x8861
+#define GL_COORD_REPLACE				0x8862
+#define GL_BGR              			0x80E0
+#define GL_BGRA             			0x80E1
+#define GL_RGB8             			0x8051
+#define GL_RGBA8            			0x8058
+#ifndef GLES_NO_SRGB
+#define GL_SRGB8						0x8C41
+#define GL_SRGB8_ALPHA8					0x8C43
+#define GL_SLUMINANCE8					0x8C47
+#else
+// No sRGB support in OpenGL 2.0.
+#define GL_SRGB8						GL_RGB8
+#define GL_SRGB8_ALPHA8					GL_RGBA8
+#define GL_SLUMINANCE8					GL_LUMINANCE8
+#endif
+#define GL_LUMINANCE8					0x8040
+#define GL_ALPHA8						0x803C
+#define GL_UNSIGNED_INT_8_8_8_8_REV		0x8367
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV   0x8366
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV   0x8365
+
+#define GLES_API_CALL GL_API
+
+#define GLES_MIN(A, B) (A < B ? A : B)
+#define GLES_MAX(A, B) (A > B ? A : B)
+
+#define GLES_NO_RETVAL ;
+
+// Surface locking
+#define GLES_LOCK_SURFACE_RET(READ, DRAW, RETVAL) \
+	do \
+	{ \
+		if(!EGLtoGLESInterface::GetEGLInterface()->LockGLESSurface(READ, DRAW)) \
+		{ \
+			GLES_LEAVE_NO_ERROR_CHECK_RET(RETVAL); \
+		} \
+	} while(0)
+
+#define GLES_LOCK_SURFACE(READ, DRAW) GLES_LOCK_SURFACE_RET(READ, DRAW, GLES_NO_RETVAL)
+
+#define GLES_LOCK_DRAW_SURFACE_RET(RETVAL) GLES_LOCK_SURFACE_RET(false, true, RETVAL)
+#define GLES_LOCK_READ_SURFACE_RET(RETVAL) GLES_LOCK_SURFACE_RET(true, false, RETVAL)
+#define GLES_LOCK_DRAW_SURFACE() GLES_LOCK_SURFACE_RET(false, true, GLES_NO_RETVAL)
+#define GLES_LOCK_READ_SURFACE() GLES_LOCK_SURFACE_RET(true, false, GLES_NO_RETVAL)
+
+#define GLES_UNLOCK_SURFACE_RET(RETVAL) \
+	do \
+	{ \
+		if(!EGLtoGLESInterface::GetEGLInterface()->UnlockGLESSurface()) \
+		{ \
+			GLES_LEAVE_RET(RETVAL); \
+		} \
+	} while(0)
+
+#define GLES_UNLOCK_SURFACE() GLES_UNLOCK_SURFACE_RET(GLES_NO_RETVAL)
+
+inline bool glesIsPowerOfTwo(int x)
+{
+	return (x != 0) && ((x & (x - 1)) == 0);
+}
+
+inline int glesLog2(unsigned int x)
+{
+	int r = 0;
+	while(x >>= 1)
+	{
+		r++;
+	}
+	return r;
+}
+
+#endif // _GLINTERNAL_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/inc/glesOS.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,48 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLESOS_H_
+#define _GLESOS_H_
+
+#if defined(_WIN32)
+#	ifndef WIN32_LEAN_AND_MEAN
+#		define WIN32_LEAN_AND_MEAN 1
+#	endif
+#	include <windows.h>
+	typedef CRITICAL_SECTION GLES_LOCK;
+#else // defined(_WIN32)
+#   include <pthread.h>
+	typedef pthread_mutex_t GLES_LOCK;
+#endif // !defined(_WIN32)
+
+void glesGetLock();
+void glesReleaseLock();
+
+#endif // _GLESOS_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/src/EGLInterface.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,426 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "EGLInterface.h"
+#include <new>
+#include "glesInternal.h"
+#include "GLESContext.h"
+#include "SurfaceDescriptor.h"
+#include "GLESTexture.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+namespace
+{
+EGLtoGLESInterface g_EGLtoGLESInterface;
+}
+
+GLES_API_CALL IEGLtoGLESInterface* getGLESInterface(void)
+{
+    return &g_EGLtoGLESInterface;
+}
+
+void glesReleaseTexImage(void* surface, int name, int level)
+{
+	EGLtoGLESInterface::GetEGLInterface()->ReleaseTexImage(surface, name, level);
+}
+
+EGLtoGLESInterface::EGLtoGLESInterface() :
+    m_egl(NULL)
+{
+}
+
+void EGLtoGLESInterface::SetEGLInterface( IGLEStoEGLInterface* egl )
+{
+    m_egl = egl;
+}
+
+void* EGLtoGLESInterface::CreateContext(void* nativeContext)
+{
+    GLESContext* newContext = NULL;
+
+    newContext = GLES_NEW GLESContext(nativeContext);
+    if(newContext == NULL)
+    {
+        return NULL;
+    }
+    m_contexts.insert(newContext);
+    return newContext;
+}
+
+bool EGLtoGLESInterface::ReleaseContext(void* context)
+{
+    GLES_ASSERT(context != NULL);
+
+    GLESContext* ctx = static_cast<GLESContext*>(context);
+    if(m_contexts.find(ctx) == m_contexts.end())
+    {
+        return false;
+    }
+
+    delete ctx;
+    m_contexts.erase(ctx);
+	
+    return true;
+}
+
+void* EGLtoGLESInterface::GetNativeContext(void* context)
+{
+    GLES_ASSERT(context != NULL);
+
+    GLESContext* ctx = static_cast<GLESContext*>(context);
+    if(m_contexts.find(ctx) == m_contexts.end())
+    {
+        return false;
+    }
+	
+    return ctx->NativeContext();
+}
+
+fpGLProc EGLtoGLESInterface::GetGLProcAddress( const char *procname )
+{
+	if(strcmp(procname, "glPointSizePointerOES") == 0)
+	{
+		return (fpGLProc)glPointSizePointerOES;
+	}
+	else
+	{
+		return NULL;
+	}
+}
+
+static SurfaceDescriptor createSurfaceDescriptor(int redBits, int redShift, int greenBits, int greenShift, int blueBits, int blueShift, int alphaBits, int alphaShift, int luminanceBits, int luminanceShift, CColorDescriptor::ColorFormat format, int bpp)
+{
+	SurfaceDescriptor desc;
+	desc.m_colorDescriptor.m_redSize = redBits;
+	desc.m_colorDescriptor.m_greenSize = greenBits;
+	desc.m_colorDescriptor.m_blueSize = blueBits;
+	desc.m_colorDescriptor.m_alphaSize = alphaBits;
+	desc.m_colorDescriptor.m_luminanceSize = luminanceBits;
+	desc.m_redShift = redShift;
+	desc.m_greenShift = greenShift;
+	desc.m_blueShift = blueShift;
+	desc.m_alphaShift = alphaShift;
+	desc.m_luminanceShift = luminanceShift;
+	desc.m_colorDescriptor.m_format = format;
+	desc.m_colorDescriptor.m_bpp = bpp;
+	return desc;
+}
+
+typedef struct
+{
+	SurfaceDescriptor desc;
+	GLenum internal_format;
+	GLenum data_format;
+	GLenum data_type;
+} DescToEnumMapping;
+
+static bool isDescEqualToMapping(const SurfaceDescriptor& desc, const DescToEnumMapping& mapping)
+{
+    if ((desc.m_colorDescriptor.m_redSize == mapping.desc.m_colorDescriptor.m_redSize) &&
+		(desc.m_colorDescriptor.m_greenSize == mapping.desc.m_colorDescriptor.m_greenSize) &&
+        (desc.m_colorDescriptor.m_blueSize == mapping.desc.m_colorDescriptor.m_blueSize) &&
+		(desc.m_colorDescriptor.m_alphaSize == mapping.desc.m_colorDescriptor.m_alphaSize) &&
+		(desc.m_colorDescriptor.m_luminanceSize == mapping.desc.m_colorDescriptor.m_luminanceSize) &&
+        (desc.m_redShift == mapping.desc.m_redShift) &&
+        (desc.m_greenShift == mapping.desc.m_greenShift) &&
+        (desc.m_blueShift == mapping.desc.m_blueShift) &&
+        (desc.m_alphaShift == mapping.desc.m_alphaShift) &&
+        (desc.m_luminanceShift == mapping.desc.m_luminanceShift) &&
+        (desc.m_colorDescriptor.m_format == mapping.desc.m_colorDescriptor.m_format) &&
+		(desc.m_colorDescriptor.m_bpp == mapping.desc.m_colorDescriptor.m_bpp))
+        return true;
+
+    return false;
+}
+
+static void surfaceDescriptorToGLEnums(const SurfaceDescriptor& desc, GLenum& internal_format, GLenum& data_format, GLenum& data_type)
+{
+	static const DescToEnumMapping map[] = {
+		/* RGB{A,X} channel ordering */
+		 // sRGBX_8888
+		{createSurfaceDescriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8, GL_RGBA, GL_UNSIGNED_BYTE},
+		 // sRGBA_8888
+		{createSurfaceDescriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // sRGBA_8888_PRE
+        {createSurfaceDescriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, CColorDescriptor::sRGBA_PRE, 32), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // sRGB_565
+        {createSurfaceDescriptor(5, 11, 6, 5, 5, 0, 0, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8, GL_RGB, GL_UNSIGNED_SHORT_5_6_5},
+         // sRGBA_5551
+        {createSurfaceDescriptor(5, 11, 5, 6, 5, 1, 1, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1},
+         // sRGBA_4444
+        {createSurfaceDescriptor(4, 12, 4, 8, 4, 4, 4, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4},
+         // sL_8
+        {createSurfaceDescriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, CColorDescriptor::sLA, 8), GL_SLUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE},
+         // lRGBX_8888
+        {createSurfaceDescriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGB8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // lRGBA_8888
+        {createSurfaceDescriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // lRGBA_8888_PRE
+        {createSurfaceDescriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, CColorDescriptor::lRGBA_PRE, 32), GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // lL_8
+        {createSurfaceDescriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, CColorDescriptor::lLA, 8), GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE},
+         // A_8
+        {createSurfaceDescriptor(0, 0, 0, 0, 0, 0, 8, 0, 0, 0, CColorDescriptor::lRGBA, 8), GL_ALPHA8, GL_ALPHA, GL_UNSIGNED_BYTE},
+		// These should be converted to a compatible format by VG.
+		/*
+         // BW_1
+        {createSurfaceDescriptor(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, CColorDescriptor::lLA, 1), 0, 0, 0},
+         // A_1
+        {createSurfaceDescriptor(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, CColorDescriptor::lRGBA, 1), 0, 0, 0},
+         // A_4
+        {createSurfaceDescriptor(0, 0, 0, 0, 0, 0, 4, 0, 0, 0, CColorDescriptor::lRGBA, 4), 0, 0, 0},
+		*/
+
+		/* {A,X}RGB channel ordering */
+         // sXRGB_8888
+        {createSurfaceDescriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sARGB_8888
+        {createSurfaceDescriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sARGB_8888_PRE
+        {createSurfaceDescriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, CColorDescriptor::sRGBA_PRE, 32), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sARGB_1555
+        {createSurfaceDescriptor(5, 10, 5, 5, 5, 0, 1, 15, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV},
+         // sARGB_4444
+        {createSurfaceDescriptor(4, 8, 4, 4, 4, 0, 4, 12, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV},
+         // lXRGB_8888
+        {createSurfaceDescriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGB8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // lARGB_8888
+        {createSurfaceDescriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // lARGB_8888_PRE
+        {createSurfaceDescriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, CColorDescriptor::lRGBA_PRE, 32), GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+
+		/* BGR{A,X} channel ordering */
+         // sBGRX_8888
+		{createSurfaceDescriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // sBGRA_8888
+        {createSurfaceDescriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // sBGRA_8888_PRE
+        {createSurfaceDescriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, CColorDescriptor::sRGBA_PRE, 32), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // sBGR_565
+        {createSurfaceDescriptor(5, 0, 6, 5, 5, 11, 0, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8, GL_BGR, GL_UNSIGNED_SHORT_5_6_5},
+         // sBGRA_5551
+        {createSurfaceDescriptor(5, 1, 5, 6, 5, 11, 1, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_SHORT_5_5_5_1},
+         // sBGRA_4444
+        {createSurfaceDescriptor(4, 4, 4, 8, 4, 12, 4, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4},
+         // lBGRX_8888
+        {createSurfaceDescriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGB8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // lBGRA_8888
+        {createSurfaceDescriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // lBGRA_8888_PRE
+        {createSurfaceDescriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, CColorDescriptor::lRGBA_PRE, 32), GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE},
+
+		/* {A,X}BGR channel ordering */
+         // sXBGR_8888
+        {createSurfaceDescriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sABGR_8888
+        {createSurfaceDescriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sABGR_8888_PRE
+        {createSurfaceDescriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, CColorDescriptor::sRGBA_PRE, 32), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sABGR_1555
+        {createSurfaceDescriptor(5, 0, 5, 5, 5, 10, 1, 15, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV},
+         // sABGR_4444
+		{createSurfaceDescriptor(4, 0, 4, 4, 4, 8, 4, 12, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV},
+         // lXBGR_8888
+        {createSurfaceDescriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGB8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // lABGR_8888
+        {createSurfaceDescriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGBA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+		 // lABGR_8888_PRE:
+		{createSurfaceDescriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, CColorDescriptor::lRGBA_PRE, 32), GL_RGBA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV}};
+
+    for (size_t i = 0; i < sizeof(map)/sizeof(map[0]); i++)
+    {
+        if (isDescEqualToMapping(desc, map[i]))
+		{
+			internal_format = map[i].internal_format;
+			data_format = map[i].data_format;
+			data_type = map[i].data_type;
+			GLES_ASSERT(internal_format != 0 && data_format != 0 && data_type != 0);
+			return;
+		}
+    }
+    GLES_ASSERT(false);
+    return;
+}
+
+int EGLtoGLESInterface::BindTexImage( void* surface, int level, bool generateMipmap, const SurfaceDescriptor* desc, void* buffer )
+{
+    GLES_ENTER_RET(NULL);
+
+	GLuint ret = 0;
+
+    // Store the current error and clear the error flag.
+    ctx->GetHostError();
+
+	if(level < 0)
+	{
+		level = 0;
+	}
+	else if(level > (int)ctx->MaxTextureLevel())
+	{
+		level = ctx->MaxTextureLevel();
+	}
+
+	GLint origGenMipmapParam;
+	ctx->DGL().glGetTexParameteriv(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, &origGenMipmapParam);
+
+	if(!generateMipmap)
+	{
+		// Disable automatic mipmap generation.
+		ctx->DGL().glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_FALSE);
+	}
+
+	// Clear all mipmap levels.
+	for(unsigned int i = 0; i < ctx->MaxTextureLevel(); i++)
+	{
+		ctx->DGL().glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+	}
+
+	GLenum internalFormat, dataFormat, dataType;
+	surfaceDescriptorToGLEnums(*desc, internalFormat, dataFormat, dataType);
+	ctx->DGL().glTexImage2D(GL_TEXTURE_2D, level, internalFormat, desc->m_width, desc->m_height, 0,
+		dataFormat, dataType, buffer);
+
+	if(!generateMipmap)
+	{
+		// Restore original state.
+		ctx->DGL().glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, origGenMipmapParam);
+	}
+
+	// Clear any possible error flag.
+	if(ctx->DGL().glGetError() == GL_NO_ERROR)
+	{
+		GLESTexture* texture = ctx->Texture(ctx->TextureBinding());
+		GLES_ASSERT(texture != NULL);
+		texture->SetLevel(level, GL_RGBA, desc->m_width, desc->m_height);
+
+		if(generateMipmap && origGenMipmapParam && level == 0)
+		{
+			texture->GenerateMipmap();
+		}
+
+		if(texture->Level(level)->boundSurface != NULL)
+		{
+			glesReleaseTexImage(texture->Level(level)->boundSurface, texture->Name(), level);
+		}
+		texture->Level(level)->boundSurface = surface;
+
+		ret = texture->Name();
+	}
+
+    GLES_LEAVE_NO_ERROR_CHECK_RET(ret);
+}
+
+bool EGLtoGLESInterface::ReleaseTexImage( int name, int level )
+{
+	GLES_ENTER_RET(false);
+
+	ctx->GetHostError();
+		
+	GLuint binding;
+	ctx->DGL().glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&binding);
+	ctx->DGL().glBindTexture(GL_TEXTURE_2D, (GLuint)name);
+	ctx->DGL().glTexImage2D(GL_TEXTURE_2D, level, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+	ctx->DGL().glBindTexture(GL_TEXTURE_2D, binding);
+
+	GLES_LEAVE_NO_ERROR_CHECK_RET(ctx->DGL().glGetError() == GL_NO_ERROR);
+}
+
+bool EGLtoGLESInterface::CopyBuffers( void* buf, const SurfaceDescriptor* desc )
+{
+    GLES_ENTER_RET(false);
+
+    // Store the current error and clear the error flag.
+    ctx->GetHostError();
+
+	GLenum internal_format, data_format, data_type;
+	surfaceDescriptorToGLEnums(*desc, internal_format, data_format, data_type);
+
+	GLint pack_alignment;
+	ctx->DGL().glGetIntegerv(GL_PACK_ALIGNMENT, &pack_alignment);
+	ctx->DGL().glPixelStorei(GL_PACK_ALIGNMENT, 1);
+    ctx->DGL().glReadPixels(0, 0, desc->m_width, desc->m_height, data_format, data_type, buf);
+	ctx->DGL().glPixelStorei(GL_PACK_ALIGNMENT, pack_alignment);
+
+    GLES_LEAVE_NO_ERROR_CHECK_RET(ctx->DGL().glGetError() == GL_NO_ERROR);
+}
+
+bool EGLtoGLESInterface::UpdateBuffers( void* buf, const SurfaceDescriptor* desc )
+{
+    GLES_ENTER_RET(false);
+
+    // Store the current error and clear the error flag.
+    ctx->GetHostError();
+
+	GLenum internal_format, data_format, data_type;
+	surfaceDescriptorToGLEnums(*desc, internal_format, data_format, data_type);
+
+	GLint unpack_alignment;
+	ctx->DGL().glGetIntegerv(GL_UNPACK_ALIGNMENT, &unpack_alignment);
+	ctx->DGL().glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+    ctx->DGL().glDrawPixels( desc->m_width, desc->m_height, data_format, data_type, buf );
+	ctx->DGL().glPixelStorei(GL_UNPACK_ALIGNMENT, unpack_alignment);
+
+    GLES_LEAVE_NO_ERROR_CHECK_RET(ctx->DGL().glGetError() == GL_NO_ERROR);
+}
+
+void EGLtoGLESInterface::Flush()
+{
+    GLES_ENTER();
+
+    // Store the current error and clear the error flag.
+    ctx->GetHostError();
+
+    ctx->DGL().glFlush();
+
+    ctx->DGL().glGetError();
+
+    GLES_LEAVE();
+}
+
+void EGLtoGLESInterface::Finish()
+{
+    GLES_ENTER();
+
+    // Store the current error and clear the error flag.
+    ctx->GetHostError();
+
+    ctx->DGL().glFinish();
+
+    ctx->DGL().glGetError();
+
+    GLES_LEAVE();
+}
+
+/*static*/ IGLEStoEGLInterface* EGLtoGLESInterface::GetEGLInterface()
+{
+    return g_EGLtoGLESInterface.m_egl;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/src/GLESArray.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,172 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "GLESArray.h"
+#include "glesInternal.h"
+#include "GLESBuffer.h"
+#include "GLESContext.h"
+
+GLESArrayPointer::GLESArrayPointer() :
+    m_pointer(NULL),
+    m_stride(0),
+    m_size(4),
+    m_type(GL_FLOAT)
+{
+}
+
+GLESArrayPointer::GLESArrayPointer(const void* pointer, int stride, int size, GLenum type) :
+    m_pointer(static_cast<const char*>(pointer)),
+    m_stride(stride),
+    m_size(size),
+    m_type(type)
+{
+}
+
+GLESArray::GLESArray() :
+    m_size(4),
+    m_type(GL_FLOAT),
+    m_stride(0),
+    m_pointer(NULL),
+    m_ownsData(false),
+    m_buffer(NULL)
+{
+}
+
+GLESArray::GLESArray(int size, GLenum type, int stride, void* pointer, const GLESBuffer* buffer, bool ownsData) :
+    m_size(size),
+    m_type(type),
+    m_stride(stride),
+    m_pointer(pointer),
+    m_ownsData(ownsData),
+    m_buffer(buffer)
+{
+}
+
+GLESArray::~GLESArray()
+{
+    if(m_ownsData)
+    {
+        delete[] m_pointer;
+    }
+}
+
+GLESArrayPointer GLESArray::ArrayPointer() const
+{
+	int stride;
+	if(m_stride)
+	{
+		stride = m_stride;
+	}
+	else
+	{
+		switch(m_type)
+		{
+		case GL_BYTE:
+			stride = sizeof(GLbyte);
+			break;
+		case GL_SHORT:
+			stride = sizeof(GLshort);
+			break;
+		case GL_FLOAT:
+			stride = sizeof(GLfloat);
+			break;
+		case GL_UNSIGNED_BYTE:
+			stride = sizeof(GLubyte);
+			break;
+		default:
+			GLES_ASSERT(false);
+		}
+	}
+	return GLESArrayPointer(m_pointer, m_size * stride, m_size, m_type);
+}
+
+GLESArray* GLESArray::Convert(int count) const
+{
+	if(m_type == GL_BYTE)
+	{
+		const char* oldPtr = NULL;
+		unsigned int size = m_size;
+		if(m_buffer)
+		{
+			oldPtr = static_cast<const char*>(m_buffer->data);
+			size = GLES_MIN(m_buffer->size / sizeof(GLbyte), count * size);
+		}
+		else
+		{
+			oldPtr = static_cast<const char*>(m_pointer);
+		}
+
+		GLshort* newArr = GLES_NEW GLshort[count * m_size];
+		if(newArr == NULL)
+		{
+			return NULL;
+		}
+		int stride = m_stride ? m_stride : sizeof(GLbyte);
+		for(unsigned int i = 0; i < count * size; i++)
+		{
+			newArr[i] = *reinterpret_cast<const GLbyte*>(oldPtr);
+			oldPtr += stride;
+		}
+		return GLES_NEW GLESArray(size, GL_SHORT, 0, newArr, NULL, true);
+	}
+	else if(m_type == GL_FIXED)
+	{
+		const char* oldPtr = NULL;
+		unsigned int size = m_size;
+		if(m_buffer)
+		{
+			oldPtr = static_cast<const char*>(m_buffer->data);
+			size = GLES_MIN(m_buffer->size / sizeof(GLfixed), count * size);
+		}
+		else
+		{
+			oldPtr = static_cast<const char*>(m_pointer);
+		}
+
+		GLfloat* newArr = GLES_NEW GLfloat[count * m_size];
+		if(newArr == NULL)
+		{
+			return NULL;
+		}
+		int stride = m_stride ? m_stride : sizeof(GLfixed);
+		for(unsigned int i = 0; i < count * size; i++)
+		{
+			newArr[i] = X_TO_F(*reinterpret_cast<const GLfixed*>(oldPtr));
+			oldPtr += stride;
+		}
+		return GLES_NEW GLESArray(size, GL_FLOAT, 0, newArr, NULL, true);
+	}
+	else
+	{
+		return GLES_NEW GLESArray(m_size, m_type, m_stride, m_buffer ? m_buffer->data : m_pointer, NULL);
+	}
+
+    return NULL;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/src/GLESContext.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,341 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "GLESContext.h"
+#include "GLESTexture.h"
+
+GLESContext::GLESContext(void* nativeContext) :
+	m_nativeContext(nativeContext),
+	m_texCoordArray(NULL),
+	m_initialized(false)
+{
+}
+
+GLESContext::~GLESContext()
+{
+	delete[] m_texCoordArray;
+
+	{
+		BufferMap::iterator iter;
+		for(iter = m_buffers.begin(); iter != m_buffers.end(); ++iter)
+		{
+			delete iter->second;
+		}
+	}
+
+	{
+		TextureMap::iterator iter;
+		for(iter = m_textures.begin(); iter != m_textures.end(); ++iter)
+		{
+			delete iter->second;
+		}
+	}
+}
+
+bool GLESContext::Initialize()
+{
+	GLES_ASSERT(!m_initialized);
+	
+	if(!m_dgl.Load())
+	{
+		return false;
+	}
+
+	// Initialize state.
+	m_error = GL_NO_ERROR;
+	m_clientActiveTexture = 0;
+	m_arrayBufferBinding = 0;
+	m_elementArrayBufferBinding = 0;
+	m_enabledArrays = 0;
+
+	int maxTextureUnits;
+	int maxClipPlanes;
+	int maxLights;
+	m_dgl.glGetIntegerv(GL_MAX_TEXTURE_UNITS, &maxTextureUnits);
+	m_dgl.glGetIntegerv(GL_MAX_CLIP_PLANES, &maxClipPlanes);
+	m_dgl.glGetIntegerv(GL_MAX_LIGHTS, &maxLights);
+	// The maximum number of texture units supported by the wrapper depends on the number
+	// of bits in the array state variable (four bits are used by vertex, normal, color
+	// and point size arrays).
+	m_maxTextureUnits = GLES_MIN(maxTextureUnits, sizeof(m_enabledArrays) * 8 - 4);
+	m_maxClipPlanes = maxClipPlanes;
+	m_maxLights = maxLights;
+
+	int maxTextureSize;
+	m_dgl.glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
+	m_maxTextureLevel = glesLog2(maxTextureSize);
+
+	m_texCoordArray = GLES_NEW GLESArray[m_maxTextureUnits];
+	if(m_texCoordArray == NULL)
+	{
+		return false;
+	}
+
+	// Create texture named zero.
+	BindTexture(0);
+
+	m_initialized = true;
+
+	return true;
+}
+
+GLenum GLESContext::GetHostError()
+{
+	GLenum host_error = m_dgl.glGetError();
+	if(host_error != GL_NO_ERROR)
+	{
+		m_error = host_error;
+	}
+	return host_error;
+}
+
+GLESArray& GLESContext::TexCoordArray(unsigned int texture)
+{
+	GLES_ASSERT(texture >= 0 && texture < m_maxTextureUnits);
+	return m_texCoordArray[texture];
+}
+
+GLESArray& GLESContext::TexCoordArray()
+{
+	return m_texCoordArray[m_clientActiveTexture];
+}
+
+const GLESArray& GLESContext::TexCoordArray(unsigned int texture) const
+{
+	GLES_ASSERT(texture >= 0 && texture < m_maxTextureUnits);
+	return m_texCoordArray[texture];
+}
+
+const GLESArray& GLESContext::TexCoordArray() const
+{
+	return m_texCoordArray[m_clientActiveTexture];
+}
+
+void GLESContext::SetVertexArray(int size, GLenum type, int stride, const void *pointer)
+{
+	m_vertexArray = GLESArray(size, type, stride, const_cast<void*>(pointer), m_buffers[m_arrayBufferBinding]);
+}
+
+void GLESContext::SetNormalArray(GLenum type, int stride, const void *pointer)
+{
+	m_normalArray = GLESArray(3, type, stride, const_cast<void*>(pointer), m_buffers[m_arrayBufferBinding]);
+}
+
+void GLESContext::SetColorArray(int size, GLenum type, int stride, const void *pointer)
+{
+	m_colorArray = GLESArray(size, type, stride, const_cast<void*>(pointer), m_buffers[m_arrayBufferBinding]);
+}
+
+void GLESContext::SetPointerSizeArray(GLenum type, int stride, const void *pointer)
+{
+	m_pointSizeArray = GLESArray(1, type, stride, const_cast<void*>(pointer), m_buffers[m_arrayBufferBinding]);
+}
+
+void GLESContext::SetTexCoordArray(int size, GLenum type, int stride, const void *pointer)
+{
+	m_texCoordArray[m_clientActiveTexture] = GLESArray(size, type, stride,
+													   const_cast<void*>(pointer), m_buffers[m_arrayBufferBinding]);
+}
+
+const GLESBuffer* GLESContext::Buffer(unsigned int buffer) const
+{
+	BufferMap::const_iterator iter = m_buffers.find(buffer);
+	if(iter == m_buffers.end())
+	{
+		// Not found
+		return NULL;
+	}
+
+	return iter->second;
+}
+
+GLESBuffer* GLESContext::ArrayBuffer()
+{
+	if(m_arrayBufferBinding)
+	{
+		return m_buffers[m_arrayBufferBinding];
+	}
+	else
+	{
+		return NULL;
+	}
+}
+
+GLESBuffer* GLESContext::ElementArrayBuffer()
+{
+	if(m_elementArrayBufferBinding)
+	{
+		return m_buffers[m_elementArrayBufferBinding];
+	}
+	else
+	{
+		return NULL;
+	}
+}
+
+void GLESContext::ReserveBufferNames(int num, unsigned int* names)
+{
+	GLES_ASSERT(num >= 0);
+	unsigned int candidate = 1;
+	while(num && candidate > 0)
+	{
+		if(m_buffers.find(candidate) == m_buffers.end())
+		{
+			m_buffers[candidate] = NULL;
+			names[num-1] = candidate;
+			num--;
+		}
+		candidate++;
+	}
+}
+
+void GLESContext::DeleteBuffer(unsigned int buffer)
+{
+	if(m_vertexArray.BufferName() == buffer)
+	{
+		m_vertexArray.ReleaseBuffer();
+	}
+	
+	if(m_normalArray.BufferName() == buffer)
+	{
+		m_normalArray.ReleaseBuffer();
+	}
+
+	if(m_colorArray.BufferName() == buffer)
+	{
+		m_colorArray.ReleaseBuffer();
+	}
+
+	for(unsigned int i = 0; i < m_maxTextureUnits; i++)
+	{
+		if(m_texCoordArray[i].BufferName() == buffer)
+		{
+			m_texCoordArray[i].ReleaseBuffer();
+		}
+	}
+
+	if(m_arrayBufferBinding == buffer)
+	{
+		m_arrayBufferBinding = 0;
+	}
+
+	delete Buffer(buffer);
+	m_buffers.erase(buffer);
+}
+
+bool GLESContext::BindArrayBuffer(unsigned int buffer)
+{
+	if(buffer != 0 && Buffer(buffer) == NULL)
+	{
+		// A new buffer must be created
+		m_buffers[buffer] = GLES_NEW GLESBuffer(buffer);
+		if(m_buffers[buffer] == NULL)
+		{
+			return false;
+		}
+	}
+	m_arrayBufferBinding = buffer;
+
+	return true;
+}
+
+bool GLESContext::BindElementArrayBuffer(unsigned int buffer)
+{
+	if(buffer != 0 && Buffer(buffer) == NULL)
+	{
+		// A new buffer must be created
+		m_buffers[buffer] = GLES_NEW GLESBuffer(buffer);
+		if(m_buffers[buffer] == NULL)
+		{
+			return false;
+		}
+	}
+	m_elementArrayBufferBinding = buffer;
+
+	return true;
+}
+
+void GLESContext::DeleteTexture(unsigned int texture)
+{
+	if(texture == 0)
+	{
+		// The texture named zero cannot be destroyed.
+		return;
+	}
+
+	// Unbind texture.
+	if(m_textureBinding == texture)
+	{
+		m_textureBinding = 0;
+	}
+
+	delete Texture(texture);
+	m_textures.erase(texture);
+}
+
+bool GLESContext::BindTexture(unsigned int texture)
+{
+	if(Texture(texture) == NULL)
+	{
+		// A new texture must be created
+		m_textures[texture] = GLES_NEW GLESTexture(texture);
+		if(m_textures[texture] == NULL)
+		{
+			return false;
+		}
+
+		if(!m_textures[texture]->AllocateLevels(m_maxTextureLevel))
+		{
+			delete m_textures[texture];
+			m_textures[texture] = NULL;
+		}
+	}
+	m_textureBinding = texture;
+
+	return true;
+}
+
+GLESTexture* GLESContext::Texture(unsigned int texture)
+{
+	TextureMap::const_iterator iter = m_textures.find(texture);
+	if(iter == m_textures.end())
+	{
+		// Not found
+		return NULL;
+	}
+
+	return iter->second;
+}
+
+void* glesGetCurrentGLESContext()
+{
+	void* context = EGLtoGLESInterface::GetEGLInterface()->GetGLESContext();
+	return context;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/src/GLESDesktopGL.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,195 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "GLESDesktopGL.h"
+#include "glesInternal.h"
+#include "EGLInterface.h"
+#include <iostream>
+
+// Load function via EGL interface
+#define LOAD(func) do \
+	{ \
+		*reinterpret_cast<void**>(&func) = iFace->GetHostProcAddress(#func); \
+		if(func == NULL) \
+		{ \
+			std::cerr << "Symbol " << #func << " not found" << std::endl; \
+			success = false; \
+		} \
+	} while(0)
+
+GLESDesktopGL::GLESDesktopGL() :
+	m_loaded(false)
+{
+}
+
+bool GLESDesktopGL::Load()
+{
+	if( m_loaded )
+	{
+		return true;
+	}
+
+	bool success = true;
+
+	IGLEStoEGLInterface* iFace = EGLtoGLESInterface::GetEGLInterface();
+
+	LOAD(glActiveTexture);
+	LOAD(glAlphaFunc);
+	LOAD(glBegin);
+	LOAD(glBindBuffer);
+	LOAD(glBindTexture);
+	LOAD(glBlendFunc);
+	LOAD(glBufferData);
+	LOAD(glBufferSubData);
+	LOAD(glClear);
+	LOAD(glClearColor);
+	LOAD(glClearDepth);
+	LOAD(glClearStencil);
+	LOAD(glClientActiveTexture);
+	LOAD(glClipPlane);
+	LOAD(glColor4d);
+	LOAD(glColor4f);
+	LOAD(glColor4fv);
+	LOAD(glColor4ub);
+	LOAD(glColor4ubv);
+	LOAD(glColorMask);
+	LOAD(glColorPointer);
+	LOAD(glCompressedTexImage2D);
+	LOAD(glCompressedTexSubImage2D);
+	LOAD(glCopyTexImage2D);
+	LOAD(glCopyTexSubImage2D);
+	LOAD(glCullFace);
+	LOAD(glDeleteBuffers);
+	LOAD(glDeleteTextures);
+	LOAD(glDepthFunc);
+	LOAD(glDepthMask);
+	LOAD(glDepthRange);
+	LOAD(glDisable);
+	LOAD(glDisableClientState);
+	LOAD(glDrawArrays);
+	LOAD(glDrawElements);
+	LOAD(glEnable);
+	LOAD(glEnableClientState);
+	LOAD(glEnd);
+	LOAD(glFinish);
+	LOAD(glFlush);
+	LOAD(glFogf);
+	LOAD(glFogfv);
+	LOAD(glFrontFace);
+	LOAD(glFrustum);
+	LOAD(glGenBuffers);
+	LOAD(glGenTextures);
+	LOAD(glGetBooleanv);
+	LOAD(glGetBufferParameteriv);
+	LOAD(glGetClipPlane);
+	LOAD(glGetDoublev);
+	LOAD(glGetError);
+	LOAD(glGetFloatv);
+	LOAD(glGetIntegerv);
+	LOAD(glGetLightfv);
+	LOAD(glGetMaterialfv);
+	LOAD(glGetPointerv);
+	LOAD(glGetString);
+	LOAD(glGetTexEnvfv);
+	LOAD(glGetTexEnviv);
+	LOAD(glGetTexParameterfv);
+	LOAD(glGetTexParameteriv);
+	LOAD(glHint);
+	LOAD(glIsBuffer);
+	LOAD(glIsEnabled);
+	LOAD(glIsTexture);
+	LOAD(glLightf);
+	LOAD(glLightfv);
+	LOAD(glLightModelf);
+	LOAD(glLightModelfv);
+	LOAD(glLineWidth);
+	LOAD(glLoadIdentity);
+	LOAD(glLoadMatrixf);
+	LOAD(glLogicOp);
+	LOAD(glMaterialf);
+	LOAD(glMaterialfv);
+	LOAD(glMultiTexCoord2fv);
+	LOAD(glMultiTexCoord2sv);
+	LOAD(glMultiTexCoord3fv);
+	LOAD(glMultiTexCoord3sv);
+	LOAD(glMultiTexCoord4fv);
+	LOAD(glMultiTexCoord4sv);
+	LOAD(glMultiTexCoord4f);
+	LOAD(glMultMatrixf);
+	LOAD(glNormal3f);
+	LOAD(glNormal3fv);
+	LOAD(glNormal3sv);
+	LOAD(glOrtho);
+	LOAD(glPointParameterf);
+	LOAD(glPointParameterfv);
+	LOAD(glPointSize);
+	LOAD(glPolygonOffset);
+	LOAD(glRotatef);
+	LOAD(glScalef);
+	LOAD(glTexEnvf);
+	LOAD(glTexEnvfv);
+	LOAD(glTexParameterf);
+	LOAD(glTexParameterfv);
+	LOAD(glMatrixMode);
+	LOAD(glNormalPointer);
+	LOAD(glPixelStorei);
+	LOAD(glPopMatrix);
+	LOAD(glPushMatrix);
+	LOAD(glReadPixels);
+	LOAD(glSampleCoverage);
+	LOAD(glScissor);
+	LOAD(glShadeModel);
+	LOAD(glStencilFunc);
+	LOAD(glStencilMask);
+	LOAD(glStencilOp);
+	LOAD(glTexCoordPointer);
+	LOAD(glTexEnvi);
+	LOAD(glTexEnviv);
+	LOAD(glTexImage2D);
+	LOAD(glTexParameteri);
+	LOAD(glTexParameteriv);
+	LOAD(glTexSubImage2D);
+	LOAD(glTranslatef);
+	LOAD(glVertex2fv);
+	LOAD(glVertex2sv);
+	LOAD(glVertex3fv);
+	LOAD(glVertex3sv);
+	LOAD(glVertex4fv);
+	LOAD(glVertex4sv);
+	LOAD(glVertexPointer);
+	LOAD(glViewport);
+    LOAD(glDrawPixels);
+
+	m_loaded = success;
+
+	return success;
+}
+
+#undef LOAD
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/src/GLESTexture.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,337 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "GLESTexture.h"
+#include "glesInternal.h"
+
+GLESTexture::GLESTexture(unsigned int name) :
+	m_name(name),
+	m_numLevels(0),
+	m_levels(NULL)
+{
+}
+
+GLESTexture::~GLESTexture()
+{
+	delete[] m_levels;
+}
+
+bool GLESTexture::AllocateLevels(int numLevels)
+{
+	GLES_ASSERT(m_levels == NULL);
+
+	m_numLevels = numLevels;
+	m_levels = GLES_NEW GLESTextureLevel[numLevels];
+	if(m_levels == NULL)
+	{
+		return false;
+	}
+
+	for(int i = 0; i < numLevels; i++)
+	{
+		// From desktop GL spec.
+		m_levels[i].format = 1;
+		m_levels[i].width = 0;
+		m_levels[i].height = 0;
+		
+		m_levels[i].boundSurface = NULL;
+	}
+
+	return true;
+}
+
+GLESTextureLevel* GLESTexture::Level(int level)
+{
+	GLES_ASSERT(m_levels != NULL);
+	GLES_ASSERT(level >= 0 && level < m_numLevels);
+	return &m_levels[level];
+}
+
+void GLESTexture::SetLevel(int level, GLenum format, GLsizei width, GLsizei height)
+{
+	GLES_ASSERT(m_levels != NULL);
+	GLES_ASSERT(level >= 0 && level < m_numLevels);
+	m_levels[level].format = format;
+	m_levels[level].width = width;
+	m_levels[level].height = height;
+}
+
+void GLESTexture::GenerateMipmap()
+{
+	GLES_ASSERT(m_levels != NULL);
+
+	const GLESTextureLevel& level_zero = m_levels[0];
+
+	m_numLevels = glesLog2(GLES_MAX(level_zero.width, level_zero.height)) + 1;
+
+	int width = level_zero.width;
+	int height = level_zero.height;
+
+	for(int level = 1; level < m_numLevels; level++)
+	{
+		if(width > 1) width /= 2;
+		if(height > 1) height /= 2;
+
+		GLES_ASSERT((width > 1 || height > 1) || level == m_numLevels - 1);
+
+		m_levels[level].format = level_zero.format;
+		m_levels[level].width = width;
+		m_levels[level].height = height;
+	}
+}
+
+bool glesIsValidCompressedFormat(GLenum format)
+{
+	switch(format)
+	{
+	case GL_PALETTE4_RGB8_OES:
+	case GL_PALETTE4_RGBA8_OES:
+	case GL_PALETTE4_R5_G6_B5_OES:
+	case GL_PALETTE4_RGBA4_OES:
+	case GL_PALETTE4_RGB5_A1_OES:
+	case GL_PALETTE8_RGB8_OES:
+	case GL_PALETTE8_RGBA8_OES:
+	case GL_PALETTE8_R5_G6_B5_OES:
+	case GL_PALETTE8_RGBA4_OES:
+	case GL_PALETTE8_RGB5_A1_OES:
+		return true;
+	default:
+		return false;
+	}
+}
+
+GLenum glesMapCompressedToBaseFormat(GLenum format)
+{
+	switch(format)
+	{
+	case GL_PALETTE4_RGB8_OES:
+	case GL_PALETTE4_R5_G6_B5_OES:
+	case GL_PALETTE8_RGB8_OES:
+	case GL_PALETTE8_R5_G6_B5_OES:
+		return GL_RGB;
+
+	case GL_PALETTE4_RGBA8_OES:
+	case GL_PALETTE4_RGBA4_OES:
+	case GL_PALETTE4_RGB5_A1_OES:
+	case GL_PALETTE8_RGBA8_OES:
+	case GL_PALETTE8_RGBA4_OES:
+	case GL_PALETTE8_RGB5_A1_OES:
+		return GL_RGBA;
+	
+	default:
+		GLES_ASSERT(false);
+	}
+
+	// not reached
+	return 0;
+}
+
+void* glesUncompressImage(int level, GLenum format, int width, int height, int imageSize, const void* data)
+{
+	const unsigned char* palette = static_cast<const unsigned char*>(data);
+	int bitsPerPixel;
+	int paletteEntrySize;
+	
+	switch(format)
+	{
+	case GL_PALETTE4_RGB8_OES:
+		bitsPerPixel = 4;
+		paletteEntrySize = 3;
+		break;
+
+	case GL_PALETTE4_RGBA8_OES:
+		bitsPerPixel = 4;
+		paletteEntrySize = 4;
+		break;
+
+	case GL_PALETTE4_R5_G6_B5_OES:
+	case GL_PALETTE4_RGB5_A1_OES:
+	case GL_PALETTE4_RGBA4_OES:
+		bitsPerPixel = 4;
+		paletteEntrySize = 2;
+		break;
+
+	case GL_PALETTE8_RGB8_OES:
+		bitsPerPixel = 8;
+		paletteEntrySize = 3;
+		break;
+
+	case GL_PALETTE8_RGBA8_OES:
+		bitsPerPixel = 8;
+		paletteEntrySize = 4;
+		break;
+
+	case GL_PALETTE8_R5_G6_B5_OES:
+	case GL_PALETTE8_RGBA4_OES:
+	case GL_PALETTE8_RGB5_A1_OES:
+		bitsPerPixel = 8;
+		paletteEntrySize = 2;
+		break;
+
+	default:
+		GLES_ASSERT(false);
+	}
+
+	int numPaletteEntries = 2 << (bitsPerPixel - 1);
+	const unsigned char* imageData = palette + numPaletteEntries * paletteEntrySize;
+
+	// Skip to the correct mip level
+	for(int i = 0; i < level; i++)
+	{
+		if(bitsPerPixel == 8)
+		{
+			imageData += width * height * bitsPerPixel / 8;
+		}
+		else
+		{
+			GLES_ASSERT(bitsPerPixel == 4);
+			imageData += width * height * bitsPerPixel / 8 / 2;
+		}
+		width /= 2;
+		height /= 2;
+	}
+
+	int bytesPerPixel;
+	GLenum baseFormat = glesMapCompressedToBaseFormat(format);
+	if(baseFormat == GL_RGB)
+	{
+		bytesPerPixel = 3;
+	}
+	else
+	{
+		GLES_ASSERT(baseFormat == GL_RGBA);
+		bytesPerPixel = 4;
+	}
+
+	char* uncompressedData = GLES_NEW char[width * height * bytesPerPixel];
+	if(uncompressedData == NULL)
+	{
+		return NULL;
+	}
+	
+	// Don't go past the end of the data
+	int pixelsPerByte = 8 / bitsPerPixel;
+	int maxPixels = (static_cast<const unsigned char*>(data) + imageSize - imageData) * pixelsPerByte;
+	int end = GLES_MIN(width * height, maxPixels);
+
+	for(int i = 0; i < end; i++)
+	{
+		int index;
+		if(bitsPerPixel == 4)
+		{
+			if(i & 1)
+			{
+				index = imageData[i / 2] & 15;
+			}
+			else
+			{
+				index = imageData[i / 2] >> 4;
+			}
+		}
+		else
+		{
+			GLES_ASSERT(bitsPerPixel == 8);
+			index = imageData[i];
+		}
+
+		int r, g, b, a;
+
+		switch(format)
+		{
+		case GL_PALETTE4_RGB8_OES:
+		case GL_PALETTE8_RGB8_OES:
+			r = palette[index*3];
+			g = palette[index*3+1];
+			b = palette[index*3+2];
+			break;
+
+		case GL_PALETTE4_RGBA8_OES:
+		case GL_PALETTE8_RGBA8_OES:
+			r = palette[index*4];
+			g = palette[index*4+1];
+			b = palette[index*4+2];
+			a = palette[index*4+3];
+			break;
+
+		case GL_PALETTE4_R5_G6_B5_OES:
+		case GL_PALETTE8_R5_G6_B5_OES:
+			r = palette[index*2+1] >> 3;
+			r = (r << 3) | (r >> 2);
+			g = ((palette[index*2+1] & 7) << 3) | (palette[index*2] >> 5);
+			g = (g << 2) | (g >> 4);
+			b = palette[index*2] & 0x1f;
+			b = (b << 3) | (b >> 2);
+			break;
+
+		case GL_PALETTE4_RGBA4_OES:
+		case GL_PALETTE8_RGBA4_OES:
+			r = palette[index*2+1] >> 4;
+			r |= (r << 4) | r;
+			g = palette[index*2+1] & 0xf;
+			g |= (g << 4) | g;
+			b = palette[index*2] >> 4;
+			b |= (b << 4) | b;
+			a = palette[index*2] & 0xf;
+			a |= (a << 4) | a;
+			break;
+
+		case GL_PALETTE4_RGB5_A1_OES:
+		case GL_PALETTE8_RGB5_A1_OES:
+			r = palette[index*2+1] >> 3;
+			r = (r << 3) | (r >> 2);
+			g = ((palette[index*2+1] & 7) << 2) | (palette[index*2] >> 6);
+			g = (g << 3) | (g >> 2);
+			b = (palette[index*2] >> 1) & 0x1f;
+			b = (b << 3) | (b >> 2);
+			a = (palette[index*2] & 1) ? 255 : 0;
+			break;
+			
+		default:
+			GLES_ASSERT(false);
+		}
+
+		if(baseFormat == GL_RGB)
+		{
+			uncompressedData[i*3+0] = r;
+			uncompressedData[i*3+1] = g;
+			uncompressedData[i*3+2] = b;
+		}
+		else
+		{
+			GLES_ASSERT(baseFormat == GL_RGBA);
+			uncompressedData[i*4+0] = r;
+			uncompressedData[i*4+1] = g;
+			uncompressedData[i*4+2] = b;
+			uncompressedData[i*4+3] = a;
+		}
+	}
+
+	return uncompressedData;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/src/glesGet.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,492 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "glesGet.h"
+#include <GLES/glext.h>
+#include "GLESContext.h"
+#include "GLESDesktopGL.h"
+
+// UINT_MAX
+#include <limits.h>
+
+bool glesGetParameter(const GLESContext& context, const GLESDesktopGL &dgl, GLenum pname, GLESGetType dstType, void* params)
+{
+    GLESGetType srcType;
+    GLboolean b[4];
+    GLint i[16];
+    GLdouble d[16];
+    int n = 1;
+
+    switch(pname)
+    {
+    case GL_MAX_TEXTURE_UNITS:
+        i[0] = context.MaxTextureUnits();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_MAX_CLIP_PLANES:
+        i[0] = context.MaxClipPlanes();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_MAX_LIGHTS:
+        i[0] = context.MaxLights();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_CLIENT_ACTIVE_TEXTURE:
+        i[0] = GL_TEXTURE0 + context.ClientActiveTexture();
+        srcType = GLES_TYPE_ENUM;
+        break;
+
+    case GL_VERTEX_ARRAY:
+        i[0] = context.IsArrayEnabled(GLES_VERTEX_ARRAY);
+        srcType = GLES_TYPE_BOOLEAN;
+        break;
+
+    case GL_VERTEX_ARRAY_SIZE:
+        i[0] = context.VertexArray().Size();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_VERTEX_ARRAY_TYPE:
+        i[0] = context.VertexArray().Type();
+        srcType = GLES_TYPE_ENUM;
+        break;
+
+    case GL_VERTEX_ARRAY_STRIDE:
+        i[0] = context.VertexArray().Stride();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_NORMAL_ARRAY:
+        i[0] = context.IsArrayEnabled(GLES_NORMAL_ARRAY);
+        srcType = GLES_TYPE_BOOLEAN;
+        break;
+
+    case GL_NORMAL_ARRAY_TYPE:
+        i[0] = context.NormalArray().Type();
+        srcType = GLES_TYPE_ENUM;
+        break;
+
+    case GL_NORMAL_ARRAY_STRIDE:
+        i[0] = context.NormalArray().Stride();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_COLOR_ARRAY:
+        i[0] = context.IsArrayEnabled(GLES_COLOR_ARRAY);
+        srcType = GLES_TYPE_BOOLEAN;
+        break;
+
+    case GL_COLOR_ARRAY_SIZE:
+        i[0] = context.ColorArray().Size();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_COLOR_ARRAY_TYPE:
+        i[0] = context.ColorArray().Type();
+        srcType = GLES_TYPE_ENUM;
+        break;
+
+    case GL_COLOR_ARRAY_STRIDE:
+        i[0] = context.ColorArray().Stride();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_POINT_SIZE_ARRAY_OES:
+        i[0] = context.IsArrayEnabled(GLES_POINT_SIZE_ARRAY);
+        srcType = GLES_TYPE_BOOLEAN;
+        break;
+
+    case GL_POINT_SIZE_ARRAY_TYPE_OES:
+        i[0] = context.PointSizeArray().Type();
+        srcType = GLES_TYPE_ENUM;
+        break;
+
+    case GL_POINT_SIZE_ARRAY_STRIDE_OES:
+        i[0] = context.PointSizeArray().Stride();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES:
+        i[0] = context.PointSizeArray().BufferName();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_TEXTURE_COORD_ARRAY:
+        i[0] = context.IsArrayEnabled(static_cast<GLESArrayFlag>(GLES_TEXTURE_COORD_ARRAY << context.ClientActiveTexture()));
+        srcType = GLES_TYPE_BOOLEAN;
+        break;
+
+    case GL_TEXTURE_COORD_ARRAY_SIZE:
+        i[0] = context.TexCoordArray().Size();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_TEXTURE_COORD_ARRAY_TYPE:
+        i[0] = context.TexCoordArray().Type();
+        srcType = GLES_TYPE_ENUM;
+        break;
+
+    case GL_TEXTURE_COORD_ARRAY_STRIDE:
+        i[0] = context.TexCoordArray().Stride();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_VERTEX_ARRAY_BUFFER_BINDING:
+        i[0] = context.VertexArray().BufferName();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_NORMAL_ARRAY_BUFFER_BINDING:
+        i[0] = context.NormalArray().BufferName();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_COLOR_ARRAY_BUFFER_BINDING:
+        i[0] = context.ColorArray().BufferName();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING:
+        i[0] = context.TexCoordArray().BufferName();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_ARRAY_BUFFER_BINDING:
+        i[0] = context.ArrayBufferBinding();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_ELEMENT_ARRAY_BUFFER_BINDING:
+        i[0] = context.ElementArrayBufferBinding();
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES:
+        if(dstType != GLES_TYPE_INTEGER)
+        {
+            return false;
+        }
+        dgl.glGetDoublev(GL_MODELVIEW_MATRIX, d);
+        n = 16;
+        for(int j = 0; j < n; j++)
+        {
+            static_cast<GLint*>(params)[j] = *reinterpret_cast<GLint*>(&d[j]);
+        }
+        break;
+
+    case GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES:
+        if(dstType != GLES_TYPE_INTEGER)
+        {
+            return false;
+        }
+        dgl.glGetDoublev(GL_PROJECTION_MATRIX, d);
+        n = 16;
+        for(int j = 0; j < n; j++)
+        {
+            static_cast<GLint*>(params)[j] = *reinterpret_cast<GLint*>(&d[j]);
+        }
+        break;
+
+    case GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES:
+        if(dstType != GLES_TYPE_INTEGER)
+        {
+            return false;
+        }
+        dgl.glGetDoublev(GL_TEXTURE_MATRIX, d);
+        n = 16;
+        for(int j = 0; j < n; j++)
+        {
+            static_cast<GLint*>(params)[j] = *reinterpret_cast<GLint*>(&d[j]);
+        }
+        break;
+
+    case GL_POINT_SPRITE_OES:
+        b[0] = dgl.glIsEnabled(GL_POINT_SPRITE);
+        srcType = GLES_TYPE_BOOLEAN;
+        break;
+
+    case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
+        i[0] = 10;
+        srcType = GLES_TYPE_INTEGER;
+        break;
+
+    case GL_COMPRESSED_TEXTURE_FORMATS:
+        i[0] = GL_PALETTE4_RGB8_OES;
+        i[1] = GL_PALETTE4_RGBA8_OES;
+        i[2] = GL_PALETTE4_R5_G6_B5_OES;
+        i[3] = GL_PALETTE4_RGBA4_OES;
+        i[4] = GL_PALETTE4_RGB5_A1_OES;
+        i[5] = GL_PALETTE8_RGB8_OES;
+        i[6] = GL_PALETTE8_RGBA8_OES;
+        i[7] = GL_PALETTE8_R5_G6_B5_OES;
+        i[8] = GL_PALETTE8_RGBA4_OES;
+        i[9] = GL_PALETTE8_RGB5_A1_OES;
+        srcType = GLES_TYPE_ENUM;
+        n = 10;
+        break;
+
+    case GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES:
+        i[0] = GL_RGBA;
+        srcType = GLES_TYPE_ENUM;
+        break;
+
+    case GL_IMPLEMENTATION_COLOR_READ_TYPE_OES:
+        i[0] = GL_UNSIGNED_BYTE;
+        srcType = GLES_TYPE_ENUM;
+        break;
+
+    case GL_ALIASED_POINT_SIZE_RANGE:
+    case GL_ALIASED_LINE_WIDTH_RANGE:
+    case GL_DEPTH_RANGE:
+    case GL_SMOOTH_LINE_WIDTH_RANGE:
+    case GL_SMOOTH_POINT_SIZE_RANGE:
+        dgl.glGetDoublev(pname, d);
+        srcType = GLES_TYPE_DOUBLE;
+        n = 2;
+        break;
+    case GL_ALPHA_TEST_FUNC:
+    case GL_STENCIL_FAIL:
+    case GL_STENCIL_FUNC:
+    case GL_STENCIL_PASS_DEPTH_FAIL:
+    case GL_STENCIL_PASS_DEPTH_PASS:
+    case GL_BLEND_DST:
+    case GL_BLEND_SRC:
+    case GL_LOGIC_OP_MODE:
+    case GL_CULL_FACE:
+    case GL_DEPTH_FUNC:
+    case GL_FOG_HINT:
+    case GL_FOG_MODE:
+    case GL_FRONT_FACE:
+    case GL_LINE_SMOOTH_HINT:
+    case GL_MATRIX_MODE:
+    case GL_PERSPECTIVE_CORRECTION_HINT:
+    case GL_POINT_SMOOTH_HINT:
+    case GL_SHADE_MODEL:
+    case GL_GENERATE_MIPMAP_HINT:
+    case GL_CULL_FACE_MODE:
+    case GL_ACTIVE_TEXTURE:
+        dgl.glGetIntegerv(pname, i);
+        srcType = GLES_TYPE_ENUM;
+        break;
+    case GL_ALPHA_BITS:
+    case GL_RED_BITS:
+    case GL_GREEN_BITS:
+    case GL_BLUE_BITS:
+    case GL_DEPTH_BITS:
+    case GL_STENCIL_BITS:
+    case GL_STENCIL_VALUE_MASK:
+    case GL_STENCIL_WRITEMASK:
+    case GL_MODELVIEW_STACK_DEPTH:
+    case GL_PROJECTION_STACK_DEPTH:
+    case GL_TEXTURE_STACK_DEPTH:
+    case GL_PACK_ALIGNMENT:
+    case GL_UNPACK_ALIGNMENT:
+    case GL_TEXTURE_BINDING_2D:
+    case GL_SUBPIXEL_BITS:
+    case GL_SAMPLE_BUFFERS:
+    case GL_SAMPLES:
+    case GL_BUFFER_SIZE:
+    case GL_STENCIL_CLEAR_VALUE:
+    case GL_MAX_MODELVIEW_STACK_DEPTH:
+    case GL_MAX_PROJECTION_STACK_DEPTH:
+    case GL_MAX_TEXTURE_STACK_DEPTH:
+    case GL_MAX_TEXTURE_SIZE:
+        dgl.glGetIntegerv(pname, i);
+        srcType = GLES_TYPE_INTEGER;
+        break;
+    case GL_ALPHA_TEST_REF:
+    case GL_STENCIL_REF:
+    case GL_DEPTH_CLEAR_VALUE:
+    case GL_FOG_DENSITY:
+    case GL_FOG_START:
+    case GL_FOG_END:
+    case GL_LINE_WIDTH:
+    case GL_POINT_SIZE:
+    case GL_POINT_SIZE_MIN:
+    case GL_POINT_SIZE_MAX:
+    case GL_POLYGON_OFFSET_FACTOR:
+    case GL_POLYGON_OFFSET_UNITS:
+    case GL_POINT_FADE_THRESHOLD_SIZE:
+        dgl.glGetDoublev(pname, d);
+        srcType = GLES_TYPE_DOUBLE;
+        break;
+    case GL_CURRENT_NORMAL:
+    case GL_POINT_DISTANCE_ATTENUATION:
+        dgl.glGetDoublev(pname, d);
+        srcType = GLES_TYPE_DOUBLE;
+        n = 3;
+        break;
+    case GL_COLOR_CLEAR_VALUE:
+    case GL_CURRENT_TEXTURE_COORDS:
+    case GL_CURRENT_COLOR:
+    case GL_FOG_COLOR:
+    case GL_LIGHT_MODEL_AMBIENT:
+    case GL_AMBIENT:
+    case GL_DIFFUSE:
+    case GL_SPECULAR:
+    case GL_EMISSION:
+        dgl.glGetDoublev(pname, d);
+        srcType = GLES_TYPE_DOUBLE;
+        n = 4;
+        break;
+    case GL_COLOR_WRITEMASK:
+        dgl.glGetBooleanv(pname, b);
+        srcType = GLES_TYPE_BOOLEAN;
+        n = 4;
+        break;
+    case GL_DEPTH_WRITEMASK:
+    case GL_LIGHT_MODEL_TWO_SIDE:
+        dgl.glGetBooleanv(pname, b);
+        srcType = GLES_TYPE_BOOLEAN;
+        break;
+    case GL_PROJECTION_MATRIX:
+    case GL_MODELVIEW_MATRIX:
+    case GL_TEXTURE_MATRIX:
+        dgl.glGetDoublev(pname, d);
+        srcType = GLES_TYPE_DOUBLE;
+        n = 16;
+        break;
+    case GL_VIEWPORT:
+    case GL_SCISSOR_BOX:
+        dgl.glGetIntegerv(pname, i);
+        srcType = GLES_TYPE_INTEGER;
+        n = 4;
+        break;
+    case GL_MAX_VIEWPORT_DIMS:
+        dgl.glGetIntegerv(pname, i);
+        srcType = GLES_TYPE_INTEGER;
+        n = 2;
+        break;
+
+    default:
+        return false;
+    }
+
+    // Type conversions
+
+    // Special cases
+    if(dstType == GLES_TYPE_INTEGER &&
+       (pname == GL_CURRENT_COLOR || pname == GL_ALPHA_TEST_REF || pname == GL_DEPTH_CLEAR_VALUE))
+    {
+        for(int j = 0; j < n; j++)
+        {
+            static_cast<GLint*>(params)[j] = static_cast<GLint>((UINT_MAX * d[j] - 1) / 2);
+        }
+        return true;
+    }
+
+    for(int j = 0; j < n; j++)
+    {
+        switch(dstType)
+        {
+        case GLES_TYPE_BOOLEAN:
+            switch(srcType)
+            {
+            case GLES_TYPE_BOOLEAN:
+                static_cast<GLboolean*>(params)[j] = b[j];
+                break;
+            case GLES_TYPE_INTEGER:
+            case GLES_TYPE_ENUM:
+                static_cast<GLboolean*>(params)[j] = i[j] ? GL_TRUE : GL_FALSE;
+                break;
+            case GLES_TYPE_DOUBLE:
+                static_cast<GLboolean*>(params)[j] = d[j] ? GL_TRUE : GL_FALSE;
+                break;
+            default:
+                GLES_ASSERT(false);
+            }
+            break;
+
+        case GLES_TYPE_INTEGER:
+            switch(srcType)
+            {
+            case GLES_TYPE_BOOLEAN:
+                static_cast<GLint*>(params)[j] = b[j];
+                break;
+            case GLES_TYPE_INTEGER:
+            case GLES_TYPE_ENUM:
+                static_cast<GLint*>(params)[j] = i[j];
+                break;
+            case GLES_TYPE_DOUBLE:
+                static_cast<GLint*>(params)[j] = static_cast<GLint>(d[j]);
+                break;
+            default:
+                GLES_ASSERT(false);
+            }
+            break;
+
+        case GLES_TYPE_FLOAT:
+            switch(srcType)
+            {
+            case GLES_TYPE_BOOLEAN:
+                static_cast<GLfloat*>(params)[j] = b[j];
+                break;
+            case GLES_TYPE_INTEGER:
+            case GLES_TYPE_ENUM:
+                static_cast<GLfloat*>(params)[j] = static_cast<GLfloat>(i[j]);
+                break;
+            case GLES_TYPE_DOUBLE:
+                static_cast<GLfloat*>(params)[j] = static_cast<GLfloat>(d[j]);
+                break;
+            default:
+                GLES_ASSERT(false);
+            }
+            break;
+
+        case GLES_TYPE_FIXED:
+            switch(srcType)
+            {
+            case GLES_TYPE_BOOLEAN:
+                static_cast<GLfixed*>(params)[j] = F_TO_X(b[j] ? 1.f : 0.f);
+                break;
+            case GLES_TYPE_INTEGER:
+                static_cast<GLfixed*>(params)[j] = I_TO_X(i[j]);
+                break;
+            case GLES_TYPE_ENUM:
+                static_cast<GLfixed*>(params)[j] = i[j];
+                break;
+            case GLES_TYPE_DOUBLE:
+                static_cast<GLfixed*>(params)[j] = D_TO_X(d[j]);
+                break;
+            default:
+                GLES_ASSERT(false);
+            }
+            break;
+
+        default:
+            GLES_ASSERT(false);
+        }
+    }
+
+    return true;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/src/glesOS.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,97 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "glesOS.h"
+#include "glesInternal.h"
+
+namespace
+{
+static bool g_lockInitialized = false;
+static GLES_LOCK g_lock;
+}
+
+#if defined(_WIN32)
+static void initializeLock()
+{
+    GLES_ASSERT(!g_lockInitialized);
+    InitializeCriticalSection(&g_lock);
+    g_lockInitialized = true;
+}
+
+void glesGetLock()
+{
+    if(!g_lockInitialized)
+    {
+        initializeLock();
+    }
+    EnterCriticalSection(&g_lock);
+}
+
+void glesReleaseLock()
+{
+    GLES_ASSERT(g_lockInitialized);
+    LeaveCriticalSection(&g_lock);
+}
+#else // defined(_WIN32)
+static void initializeLock()
+{
+    int ret;
+
+    GLES_ASSERT(!g_lockInitialized);
+
+    pthread_mutexattr_t attr;
+    ret = pthread_mutexattr_init(&attr);	//initially not locked
+    GLES_ASSERT(!ret);	//check that there aren't any errors
+    ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);	//count the number of recursive locks
+    GLES_ASSERT(!ret);	//check that there aren't any errors
+    ret = pthread_mutex_init(&g_lock, &attr);
+    pthread_mutexattr_destroy(&attr);
+    GLES_ASSERT(!ret);	//check that there aren't more errors
+
+    g_lockInitialized = true;
+}
+
+void glesGetLock()
+{
+    if(!g_lockInitialized)
+    {
+        initializeLock();
+    }
+    int ret = pthread_mutex_lock(&g_lock);
+    GLES_ASSERT(!ret);
+}
+
+void glesReleaseLock()
+{
+    GLES_ASSERT(g_lockInitialized);
+    int ret = pthread_mutex_unlock(&g_lock);
+    GLES_ASSERT(!ret);
+}
+#endif // !defined(_WIN32)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles11/src/glesapi.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2227 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include <GLES/gl.h>
+#include <GLES/glplatform.h>
+#include <iostream>
+#include "GLESDesktopGL.h"
+#include "glesInternal.h"
+#include "EGLInterface.h"
+#include "GLESContext.h"
+#include "GLESArray.h"
+#include "GLESTexture.h"
+#include "glesGet.h"
+
+// exit()
+#include <stdlib.h>
+// memcpy
+#include <string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Available only in Common profile */
+GL_API void GL_APIENTRY glAlphaFunc (GLenum func, GLclampf ref)
+{
+    GLES_ENTER();
+    ctx->DGL().glAlphaFunc (func, ref);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+    GLES_ENTER();
+    ctx->DGL().glClearColor (red, green, blue, alpha);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glClearDepthf (GLclampf depth)
+{
+    GLES_ENTER();
+    ctx->DGL().glClearDepth (depth);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glClipPlanef (GLenum plane, const GLfloat *equation)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(plane < GL_CLIP_PLANE0 || plane >= GL_CLIP_PLANE0 + ctx->MaxClipPlanes(), GL_INVALID_ENUM);
+    GLdouble dequation[4];
+    for(int i = 0; i < 4; i++)
+    {
+        dequation[i] = static_cast<GLdouble>(equation[i]);
+    }
+    ctx->DGL().glClipPlane (plane, dequation);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glColor4f (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+    GLES_ENTER();
+    ctx->DGL().glColor4f (red, green, blue, alpha);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glDepthRangef (GLclampf zNear, GLclampf zFar)
+{
+    GLES_ENTER();
+    ctx->DGL().glDepthRange(zNear, zFar);
+    GLES_LEAVE();
+}
+bool isValidSingleValuedFogParamEnum(GLenum pname)
+{
+    switch(pname)
+    {
+    case GL_FOG_MODE:
+    case GL_FOG_DENSITY:
+    case GL_FOG_START:
+    case GL_FOG_END:
+        return true;
+    default:
+        return false;
+    }
+}
+bool isValidFogParamEnum(GLenum pname)
+{
+    return isValidSingleValuedFogParamEnum(pname) || pname == GL_FOG_COLOR;
+}
+GL_API void GL_APIENTRY glFogf (GLenum pname, GLfloat param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidFogParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glFogf (pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glFogfv (GLenum pname, const GLfloat *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidFogParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glFogfv (pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glFrustumf (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar)
+{
+    GLES_ENTER();
+    ctx->DGL().glFrustum (left, right, bottom, top, zNear, zFar);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetClipPlanef (GLenum pname, GLfloat eqn[4])
+{
+    GLES_ENTER();
+    GLdouble deqn[4];
+    ctx->DGL().glGetClipPlane (pname, deqn);
+    for(int i = 0; i < 4; i++)
+    {
+        eqn[i] = static_cast<GLfloat>(deqn[i]);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat *params)
+{
+    GLES_ENTER();
+    if(!glesGetParameter(*ctx, ctx->DGL(), pname, GLES_TYPE_FLOAT, params))
+    {
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetLightfv (GLenum light, GLenum pname, GLfloat *params)
+{
+    GLES_ENTER();
+    ctx->DGL().glGetLightfv (light, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetMaterialfv (GLenum face, GLenum pname, GLfloat *params)
+{
+    GLES_ENTER();
+    ctx->DGL().glGetMaterialfv (face, pname, params);
+    GLES_LEAVE();
+}
+bool isValidTexEnvTargetEnum(GLenum target)
+{
+    switch(target)
+    {
+    case GL_POINT_SPRITE_OES:
+    case GL_TEXTURE_ENV:
+        return true;
+    default:
+        return false;
+    }
+}
+bool isValidSingleValuedTexEnvParamEnum(GLenum pname)
+{
+    switch(pname)
+    {
+    case GL_TEXTURE_ENV_MODE:
+    case GL_COORD_REPLACE_OES:
+    case GL_COMBINE_RGB:
+    case GL_COMBINE_ALPHA:
+    case GL_SRC0_RGB:
+    case GL_SRC1_RGB:
+    case GL_SRC2_RGB:
+    case GL_SRC0_ALPHA:
+    case GL_SRC1_ALPHA:
+    case GL_SRC2_ALPHA:
+    case GL_OPERAND0_RGB:
+    case GL_OPERAND1_RGB:
+    case GL_OPERAND2_RGB:
+    case GL_OPERAND0_ALPHA:
+    case GL_OPERAND1_ALPHA:
+    case GL_OPERAND2_ALPHA:
+    case GL_RGB_SCALE:
+    case GL_ALPHA_SCALE:
+        return true;
+    default:
+        return false;
+    }
+}
+bool isValidTexEnvParamEnum(GLenum pname)
+{
+    return isValidSingleValuedTexEnvParamEnum(pname) || pname == GL_TEXTURE_ENV_COLOR;
+}
+GL_API void GL_APIENTRY glGetTexEnvfv (GLenum env, GLenum pname, GLfloat *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTexEnvTargetEnum(env), GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexEnvParamEnum(pname), GL_INVALID_ENUM);
+    env = env == GL_POINT_SPRITE_OES ? GL_POINT_SPRITE : env;
+    pname = pname == GL_COORD_REPLACE_OES ? GL_COORD_REPLACE : pname;
+    ctx->DGL().glGetTexEnvfv (env, pname, params);
+    GLES_LEAVE();
+}
+bool isValidTexParamEnum(GLenum pname)
+{
+    switch(pname)
+    {
+    case GL_TEXTURE_MIN_FILTER:
+    case GL_TEXTURE_MAG_FILTER:
+    case GL_TEXTURE_WRAP_S:
+    case GL_TEXTURE_WRAP_T:
+    case GL_GENERATE_MIPMAP:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glGetTexParameterfv (target, pname, params);
+    GLES_LEAVE();
+}
+bool isValidLightModelParamEnum(GLenum pname)
+{
+    switch(pname)
+    {
+    case GL_LIGHT_MODEL_AMBIENT:
+    case GL_LIGHT_MODEL_TWO_SIDE:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glLightModelf (GLenum pname, GLfloat param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidLightModelParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glLightModelf (pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLightModelfv (GLenum pname, const GLfloat *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidLightModelParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glLightModelfv (pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLightf (GLenum light, GLenum pname, GLfloat param)
+{
+    GLES_ENTER();
+    ctx->DGL().glLightf (light, pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLightfv (GLenum light, GLenum pname, const GLfloat *params)
+{
+    GLES_ENTER();
+    ctx->DGL().glLightfv (light, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLineWidth (GLfloat width)
+{
+    GLES_ENTER();
+    ctx->DGL().glLineWidth (width);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLoadMatrixf (const GLfloat *m)
+{
+    GLES_ENTER();
+    ctx->DGL().glLoadMatrixf (m);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glMaterialf (GLenum face, GLenum pname, GLfloat param)
+{
+    GLES_ENTER();
+    ctx->DGL().glMaterialf (face, pname, param);
+    GLES_LEAVE();
+}
+bool isValidSingleValuedMaterialParamEnum(GLenum pname)
+{
+    return pname == GL_SHININESS;
+}
+bool isValidMaterialParamEnum(GLenum pname)
+{
+    if(isValidSingleValuedMaterialParamEnum(pname))
+    {
+        return true;
+    }
+    else
+    {
+        switch(pname)
+        {
+        case GL_AMBIENT:
+        case GL_DIFFUSE:
+        case GL_AMBIENT_AND_DIFFUSE:
+        case GL_SPECULAR:
+        case GL_EMISSION:
+        case GL_SHININESS:
+            return true;
+        default:
+            return false;
+        }
+    }
+}
+GL_API void GL_APIENTRY glMaterialfv (GLenum face, GLenum pname, const GLfloat *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidMaterialParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glMaterialfv (face, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glMultMatrixf (const GLfloat *m)
+{
+    GLES_ENTER();
+    ctx->DGL().glMultMatrixf(m);
+    GLES_LEAVE();
+}
+bool isValidTextureTargetEnum(GLenum target, unsigned int maxTextureUnits)
+{
+    return target >= GL_TEXTURE0 && target < GL_TEXTURE0 + maxTextureUnits;
+}
+GL_API void GL_APIENTRY glMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTextureTargetEnum(target, ctx->MaxTextureUnits()), GL_INVALID_ENUM);
+    ctx->DGL().glMultiTexCoord4f(target, s, t, r, q);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glNormal3f (GLfloat nx, GLfloat ny, GLfloat nz)
+{
+    GLES_ENTER();
+    ctx->DGL().glNormal3f(nx, ny, nz);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glOrthof (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar)
+{
+    GLES_ENTER();
+    ctx->DGL().glOrtho(left, right, bottom, top, zNear, zFar);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPointParameterf (GLenum pname, GLfloat param)
+{
+    GLES_ENTER();
+    ctx->DGL().glPointParameterf (pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params)
+{
+    GLES_ENTER();
+    ctx->DGL().glPointParameterfv (pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPointSize (GLfloat size)
+{
+    GLES_ENTER();
+    ctx->DGL().glPointSize (size);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units)
+{
+    GLES_ENTER();
+    ctx->DGL().glPolygonOffset (factor, units);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glRotatef (GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
+{
+    GLES_ENTER();
+    ctx->DGL().glRotatef (angle, x, y, z);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glScalef (GLfloat x, GLfloat y, GLfloat z)
+{
+    GLES_ENTER();
+    ctx->DGL().glScalef (x, y, z);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexEnvf (GLenum target, GLenum pname, GLfloat param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTexEnvTargetEnum(target), GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexEnvParamEnum(pname), GL_INVALID_ENUM);
+    target = target == GL_POINT_SPRITE_OES ? GL_POINT_SPRITE : target;
+    pname = pname == GL_COORD_REPLACE_OES ? GL_COORD_REPLACE : pname;
+    ctx->DGL().glTexEnvf (target, pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexEnvfv (GLenum target, GLenum pname, const GLfloat *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTexEnvTargetEnum(target), GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexEnvParamEnum(pname), GL_INVALID_ENUM);
+    target = target == GL_POINT_SPRITE_OES ? GL_POINT_SPRITE : target;
+    pname = pname == GL_COORD_REPLACE_OES ? GL_COORD_REPLACE : pname;
+    ctx->DGL().glTexEnvfv (target, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    pname = pname == GL_COORD_REPLACE_OES ? GL_COORD_REPLACE : pname;
+    ctx->DGL().glTexParameterf (target, pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    target = target == GL_POINT_SPRITE_OES ? GL_POINT_SPRITE : target;
+    pname = pname == GL_COORD_REPLACE_OES ? GL_COORD_REPLACE : pname;
+    ctx->DGL().glTexParameterfv (target, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTranslatef (GLfloat x, GLfloat y, GLfloat z)
+{
+    GLES_ENTER();
+    ctx->DGL().glTranslatef (x, y, z);
+    GLES_LEAVE();
+}
+
+/* Available in both Common and Common-Lite profiles */
+GL_API void GL_APIENTRY glActiveTexture (GLenum texture)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTextureTargetEnum(texture, ctx->MaxTextureUnits()), GL_INVALID_ENUM);
+    ctx->DGL().glActiveTexture (texture);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glAlphaFuncx (GLenum func, GLclampx ref)
+{
+    GLES_ENTER();
+    ctx->DGL().glAlphaFunc(func, X_TO_F(ref));
+    GLES_LEAVE();
+}
+bool isValidBufferTarget(GLenum target)
+{
+    switch(target)
+    {
+    case GL_ARRAY_BUFFER:
+    case GL_ELEMENT_ARRAY_BUFFER:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidBufferTarget(target), GL_INVALID_ENUM);
+    switch(target)
+    {
+    case GL_ARRAY_BUFFER:
+        if(!ctx->BindArrayBuffer(buffer))
+        {
+            GLES_ERROR(GL_OUT_OF_MEMORY);
+        }
+        break;
+    case GL_ELEMENT_ARRAY_BUFFER:
+        if(!ctx->BindElementArrayBuffer(buffer))
+        {
+            GLES_ERROR(GL_OUT_OF_MEMORY);
+        }
+        break;
+    default:
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glBindTexture (GLenum target, GLuint texture)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    ctx->GetHostError();
+    ctx->DGL().glBindTexture (target, texture);
+    if(ctx->GetHostError() == GL_NO_ERROR)
+    {
+        ctx->BindTexture(texture);
+    }
+    GLES_LEAVE();
+}
+bool isValidSrcBlendFuncEnum(GLenum func)
+{
+    switch(func)
+    {
+    case GL_ZERO:
+    case GL_ONE:
+    case GL_DST_COLOR:
+    case GL_ONE_MINUS_DST_COLOR:
+    case GL_SRC_ALPHA:
+    case GL_ONE_MINUS_SRC_ALPHA:
+    case GL_DST_ALPHA:
+    case GL_ONE_MINUS_DST_ALPHA:
+    case GL_SRC_ALPHA_SATURATE:
+        return true;
+    default:
+        return false;
+    }
+}
+bool isValidDstBlendFuncEnum(GLenum func)
+{
+    switch(func)
+    {
+    case GL_ZERO:
+    case GL_ONE:
+    case GL_SRC_COLOR:
+    case GL_ONE_MINUS_SRC_COLOR:
+    case GL_SRC_ALPHA:
+    case GL_ONE_MINUS_SRC_ALPHA:
+    case GL_DST_ALPHA:
+    case GL_ONE_MINUS_DST_ALPHA:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidSrcBlendFuncEnum(sfactor), GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidDstBlendFuncEnum(dfactor), GL_INVALID_ENUM);
+    ctx->DGL().glBlendFunc (sfactor, dfactor);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(size < 0, GL_INVALID_VALUE);
+    GLES_ERROR_IF(usage != GL_STATIC_DRAW && usage != GL_DYNAMIC_DRAW, GL_INVALID_ENUM);
+
+    GLESBuffer* buffer;
+    switch(target)
+    {
+    case GL_ARRAY_BUFFER:
+        GLES_ERROR_IF(ctx->ArrayBufferBinding() == 0, GL_INVALID_OPERATION);
+        buffer = ctx->ArrayBuffer();
+        break;
+    case GL_ELEMENT_ARRAY_BUFFER:
+        GLES_ERROR_IF(ctx->ElementArrayBufferBinding() == 0, GL_INVALID_OPERATION);
+        buffer = ctx->ElementArrayBuffer();
+        break;
+    default:
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_ASSERT(buffer);
+
+    delete[] buffer->data;
+    buffer->data = GLES_NEW char[size];
+    if(buffer->data == NULL)
+    {
+        GLES_ERROR(GL_OUT_OF_MEMORY);
+    }
+
+    if(data != NULL)
+    {
+        memcpy(buffer->data, data, size);
+    }
+
+    buffer->size = size;
+    buffer->usage = usage;
+
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(offset < 0, GL_INVALID_VALUE);
+    GLES_ERROR_IF(size < 0, GL_INVALID_VALUE);
+
+    GLESBuffer* buffer;
+    switch(target)
+    {
+    case GL_ARRAY_BUFFER:
+        GLES_ERROR_IF(ctx->ArrayBufferBinding() == 0, GL_INVALID_OPERATION);
+        buffer = ctx->ArrayBuffer();
+        break;
+    case GL_ELEMENT_ARRAY_BUFFER:
+        GLES_ERROR_IF(ctx->ElementArrayBufferBinding() == 0, GL_INVALID_OPERATION);
+        buffer = ctx->ElementArrayBuffer();
+        break;
+    default:
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_ASSERT(buffer);
+
+    GLES_ERROR_IF(size + offset > buffer->size, GL_INVALID_VALUE);
+    memcpy(static_cast<char*>(buffer->data) + offset, data, size);
+
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glClear (GLbitfield mask)
+{
+	GLES_ENTER();
+	GLES_LOCK_DRAW_SURFACE();
+	ctx->DGL().glClear (mask);
+	GLES_UNLOCK_SURFACE();
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glClearColorx (GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha)
+{
+    GLES_ENTER();
+    ctx->DGL().glClearColor (X_TO_F(red), X_TO_F(green), X_TO_F(blue), X_TO_F(alpha));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glClearDepthx (GLclampx depth)
+{
+    GLES_ENTER();
+    ctx->DGL().glClearDepth (X_TO_D(depth));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glClearStencil (GLint s)
+{
+    GLES_ENTER();
+    ctx->DGL().glClearStencil (s);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glClientActiveTexture (GLenum texture)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTextureTargetEnum(texture, ctx->MaxTextureUnits()), GL_INVALID_ENUM);
+    ctx->GetHostError();
+    ctx->DGL().glClientActiveTexture (texture);
+    if(ctx->GetHostError() == GL_NO_ERROR)
+    {
+        ctx->SetClientActiveTexture(texture - GL_TEXTURE0);
+    }
+    GLES_LEAVE_NO_ERROR_CHECK();
+}
+GL_API void GL_APIENTRY glClipPlanex (GLenum plane, const GLfixed *equation)
+{
+    GLES_ENTER();
+    GLdouble dequation[4];
+    for(int i = 0; i < 4; i++)
+    {
+        dequation[i] = X_TO_D(equation[i]);
+    }
+    ctx->DGL().glClipPlane (plane, dequation);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glColor4ub (GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha)
+{
+    GLES_ENTER();
+    ctx->DGL().glColor4ub (red, green, blue, alpha);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glColor4x (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha)
+{
+    GLES_ENTER();
+    ctx->DGL().glColor4d(X_TO_D(red), X_TO_D(green), X_TO_D(blue), X_TO_D(alpha));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
+{
+    GLES_ENTER();
+    ctx->DGL().glColorMask (red, green, blue, alpha);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glColorPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(size != 4, GL_INVALID_VALUE);
+    GLES_ERROR_IF(type != GL_UNSIGNED_BYTE && type != GL_FIXED && type != GL_FLOAT, GL_INVALID_ENUM);
+    GLES_ERROR_IF(stride < 0, GL_INVALID_VALUE);
+    ctx->SetColorArray(size, type, stride, pointer);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data)
+{
+	GLES_ENTER();
+	GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+	GLES_ERROR_IF(level > 0, GL_INVALID_VALUE);
+	GLES_ERROR_IF(!glesIsValidCompressedFormat(internalformat), GL_INVALID_ENUM);
+	GLES_ERROR_IF(height < 0, GL_INVALID_VALUE);
+	GLES_ERROR_IF(width < 0, GL_INVALID_VALUE);
+	GLES_ERROR_IF(height > 0 && !glesIsPowerOfTwo(height), GL_INVALID_VALUE);
+	GLES_ERROR_IF(width > 0 && !glesIsPowerOfTwo(width), GL_INVALID_VALUE);
+	GLES_ERROR_IF(imageSize < 0, GL_INVALID_VALUE);
+
+	GLenum baseFormat = glesMapCompressedToBaseFormat(internalformat);
+
+	int numLevels = -level + 1;
+	for(int curLevel = 0; curLevel < numLevels; curLevel++)
+	{
+		if(data != NULL)
+		{
+			void* uncompressedData = glesUncompressImage(curLevel, internalformat, width, height, imageSize, data);
+			if(uncompressedData == NULL)
+			{
+				GLES_ERROR(GL_OUT_OF_MEMORY);
+			}
+			ctx->DGL().glTexImage2D(target, curLevel, baseFormat, width, height, border, baseFormat, GL_UNSIGNED_BYTE, uncompressedData);
+			delete uncompressedData;
+		}
+		else
+		{
+			ctx->DGL().glTexImage2D(target, curLevel, baseFormat, width, height, border, baseFormat, GL_UNSIGNED_BYTE, NULL);
+		}
+
+		if(ctx->GetHostError() == GL_NO_ERROR)
+		{
+			GLESTexture* texture = ctx->Texture(ctx->TextureBinding());
+			GLES_ASSERT(texture != NULL);
+			texture->SetLevel(level, internalformat, width, height);
+
+			if(texture->Level(level)->boundSurface != NULL)
+			{
+				// Texture is respecified. Release the bound EGLSurface.
+				glesReleaseTexImage(texture->Level(level)->boundSurface, texture->Name(), level);
+				texture->Level(level)->boundSurface = NULL;
+			}
+		}
+
+		width /= 2;
+		height /= 2;
+	}
+	
+	GLES_LEAVE();
+}
+static bool isPalettedFormat(GLenum format)
+{
+    switch(format)
+    {
+    case GL_PALETTE4_RGB8_OES:
+    case GL_PALETTE4_RGBA8_OES:
+    case GL_PALETTE4_R5_G6_B5_OES:
+    case GL_PALETTE4_RGBA4_OES:
+    case GL_PALETTE4_RGB5_A1_OES:
+    case GL_PALETTE8_RGB8_OES:
+    case GL_PALETTE8_RGBA8_OES:
+    case GL_PALETTE8_R5_G6_B5_OES:
+    case GL_PALETTE8_RGBA4_OES:
+    case GL_PALETTE8_RGB5_A1_OES:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isPalettedFormat(format), GL_INVALID_ENUM);
+    // Not supported for compressed paletted textures.
+    GLES_ERROR(GL_INVALID_OPERATION);
+    GLES_LEAVE();
+}
+bool isValidPixelFormatEnum(GLenum format)
+{
+    switch(format)
+    {
+    case GL_ALPHA:
+    case GL_LUMINANCE:
+    case GL_LUMINANCE_ALPHA:
+    case GL_RGB:
+    case GL_RGBA:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
+{
+	GLES_ENTER();
+	GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+	GLES_ERROR_IF(!isValidPixelFormatEnum(internalformat), GL_INVALID_ENUM);
+	
+	GLES_LOCK_READ_SURFACE();
+	ctx->DGL().glCopyTexImage2D (target, level, internalformat, x, y, width, height, border);
+	GLES_UNLOCK_SURFACE();
+
+	if(ctx->GetHostError() == GL_NO_ERROR)
+	{
+		GLint genMipmap;
+		ctx->DGL().glGetTexParameteriv(target, GL_GENERATE_MIPMAP, &genMipmap);
+		GLESTexture* texture = ctx->Texture(ctx->TextureBinding());
+		GLES_ASSERT(texture != NULL);
+		if(level == 0 && genMipmap)
+		{
+			texture->GenerateMipmap();
+		}
+
+		if(texture->Level(level)->boundSurface != NULL)
+		{
+			// Texture is respecified. Release the bound EGLSurface.
+			glesReleaseTexImage(texture->Level(level)->boundSurface, texture->Name(), level);
+			texture->Level(level)->boundSurface = NULL;
+		}
+	}
+
+	GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	GLES_ENTER();
+	GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+
+	GLESTexture* texture = ctx->Texture(ctx->TextureBinding());
+	GLES_ASSERT(texture != NULL);
+	const GLESTextureLevel* level_obj = texture->Level(level);
+	if(isPalettedFormat(level_obj->format))
+	{
+		GLES_ERROR(GL_INVALID_OPERATION);
+	}
+
+	GLES_LOCK_READ_SURFACE();
+	ctx->DGL().glCopyTexSubImage2D (target, level, xoffset, yoffset, x, y, width, height);
+	GLES_UNLOCK_SURFACE();
+
+	if(ctx->GetHostError() == GL_NO_ERROR)
+	{
+		GLint genMipmap;
+		ctx->DGL().glGetTexParameteriv(target, GL_GENERATE_MIPMAP, &genMipmap);
+		if(level == 0 && genMipmap)
+		{
+			GLESTexture* texture = ctx->Texture(ctx->TextureBinding());
+			GLES_ASSERT(texture != NULL);
+			texture->GenerateMipmap();
+		}
+	}
+
+	GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glCullFace (GLenum mode)
+{
+    GLES_ENTER();
+    ctx->DGL().glCullFace (mode);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(n < 0, GL_INVALID_VALUE);
+    for(int i = 0; i < n; i++)
+    {
+        ctx->DeleteBuffer(buffers[i]);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(n < 0, GL_INVALID_VALUE);
+    ctx->GetHostError();
+    ctx->DGL().glDeleteTextures (n, textures);
+    if(ctx->GetHostError() == GL_NO_ERROR)
+    {
+        for(int i = 0; i < n; i++)
+        {
+            ctx->DeleteTexture(textures[i]);
+        }
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glDepthFunc (GLenum func)
+{
+    GLES_ENTER();
+    ctx->DGL().glDepthFunc (func);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glDepthMask (GLboolean flag)
+{
+    GLES_ENTER();
+    ctx->DGL().glDepthMask (flag);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glDepthRangex (GLclampx zNear, GLclampx zFar)
+{
+    GLES_ENTER();
+    ctx->DGL().glDepthRange(X_TO_D(zNear), X_TO_D(zFar));
+    GLES_LEAVE();
+}
+bool isValidCapabilityEnum(GLenum cap)
+{
+    switch(cap)
+    {
+    case GL_NORMALIZE:
+    case GL_RESCALE_NORMAL:
+    case GL_CLIP_PLANE0:
+    case GL_CLIP_PLANE1:
+    case GL_CLIP_PLANE2:
+    case GL_CLIP_PLANE3:
+    case GL_CLIP_PLANE4:
+    case GL_CLIP_PLANE5:
+    case GL_FOG:
+    case GL_LIGHTING:
+    case GL_COLOR_MATERIAL:
+    case GL_LIGHT0:
+    case GL_LIGHT1:
+    case GL_LIGHT2:
+    case GL_LIGHT3:
+    case GL_LIGHT4:
+    case GL_LIGHT5:
+    case GL_LIGHT6:
+    case GL_LIGHT7:
+    case GL_POINT_SMOOTH:
+    case GL_POINT_SPRITE_OES:
+    case GL_LINE_SMOOTH:
+    case GL_CULL_FACE:
+    case GL_POLYGON_OFFSET_FILL:
+    case GL_MULTISAMPLE:
+    case GL_SAMPLE_ALPHA_TO_COVERAGE:
+    case GL_SAMPLE_ALPHA_TO_ONE:
+    case GL_SAMPLE_COVERAGE:
+    case GL_TEXTURE_2D:
+    case GL_SCISSOR_TEST:
+    case GL_ALPHA_TEST:
+    case GL_STENCIL_TEST:
+    case GL_DEPTH_TEST:
+    case GL_BLEND:
+    case GL_DITHER:
+    case GL_COLOR_LOGIC_OP:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glDisable (GLenum cap)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidCapabilityEnum(cap), GL_INVALID_ENUM);
+    cap = cap == GL_POINT_SPRITE_OES ? GL_POINT_SPRITE : cap;
+    ctx->DGL().glDisable (cap);
+    GLES_LEAVE();
+}
+static GLESArrayFlag mapArrayType(GLenum type)
+{
+    switch(type)
+    {
+    case GL_VERTEX_ARRAY:
+        return GLES_VERTEX_ARRAY;
+    case GL_NORMAL_ARRAY:
+        return GLES_NORMAL_ARRAY;
+    case GL_COLOR_ARRAY:
+        return GLES_COLOR_ARRAY;
+    case GL_POINT_SIZE_ARRAY_OES:
+        return GLES_POINT_SIZE_ARRAY;
+    case GL_TEXTURE_COORD_ARRAY:
+        return GLES_TEXTURE_COORD_ARRAY;
+    default:
+        return GLES_INVALID_ARRAY;
+    }
+}
+GL_API void GL_APIENTRY glDisableClientState (GLenum array)
+{
+    GLES_ENTER();
+    int flag = static_cast<int>(mapArrayType(array));
+    GLES_ERROR_IF(flag == GLES_INVALID_ARRAY, GL_INVALID_ENUM);
+    if(flag == GLES_TEXTURE_COORD_ARRAY)
+    {
+        flag <<= ctx->ClientActiveTexture();
+    }
+    ctx->DisableArray(static_cast<GLESArrayFlag>(flag));
+    if(array != GL_POINT_SIZE_ARRAY_OES)
+    {
+        ctx->DGL().glDisableClientState(array);
+    }
+    GLES_LEAVE();
+}
+static bool convertArrays(const GLESContext& ctx, GLsizei count, GLESArray** vertexArr, GLESArray** normalArr,
+                          GLESArray** colorArr, GLESArray** texCoordArr)
+{
+    *vertexArr = ctx.VertexArray().Convert(count);
+    if(*vertexArr == NULL)
+    {
+        return false;
+    }
+    ctx.DGL().glVertexPointer((*vertexArr)->Size(), (*vertexArr)->Type(), (*vertexArr)->Stride(), (*vertexArr)->Pointer());
+
+    if(ctx.IsArrayEnabled(GLES_NORMAL_ARRAY))
+    {
+        *normalArr = ctx.NormalArray().Convert(count);
+        if(*normalArr == NULL)
+        {
+            return false;
+        }
+        ctx.DGL().glNormalPointer((*normalArr)->Type(), (*normalArr)->Stride(), (*normalArr)->Pointer());
+    }
+
+    if(ctx.IsArrayEnabled(GLES_COLOR_ARRAY))
+    {
+        *colorArr = ctx.ColorArray().Convert(count);
+        if(*colorArr == NULL)
+        {
+            return false;
+        }
+        ctx.DGL().glColorPointer((*colorArr)->Size(), (*colorArr)->Type(), (*colorArr)->Stride(), (*colorArr)->Pointer());
+    }
+
+    for(unsigned int i = 0; i < ctx.MaxTextureUnits(); i++)
+    {
+        if(ctx.IsArrayEnabled(static_cast<GLESArrayFlag>(GLES_TEXTURE_COORD_ARRAY << i)))
+        {
+            texCoordArr[i] = ctx.TexCoordArray(i).Convert(count);
+            if(texCoordArr[i] == NULL)
+            {
+                return false;
+            }
+            ctx.DGL().glClientActiveTexture(GL_TEXTURE0 + i);
+            ctx.DGL().glTexCoordPointer(texCoordArr[i]->Size(), texCoordArr[i]->Type(),
+                                    texCoordArr[i]->Stride(), texCoordArr[i]->Pointer());
+        }
+    }
+
+    // Reset state
+    ctx.DGL().glClientActiveTexture(GL_TEXTURE0 + ctx.ClientActiveTexture());
+
+    return true;
+}
+void drawPoint(const GLESContext& ctx, int i, GLESArrayPointer& vertexPtr, GLESArrayPointer& normalPtr,
+               GLESArrayPointer& colorPtr, GLESArrayPointer& pointSizePtr,
+               GLESArrayPointer* texCoordPtr)
+{
+    if(normalPtr != NULL)
+    {
+        switch(normalPtr.Type())
+        {
+        case GL_BYTE:
+        case GL_SHORT:
+            ctx.DGL().glNormal3sv(static_cast<const GLshort*>(normalPtr[i]));
+            break;
+        case GL_FIXED:
+        case GL_FLOAT:
+            ctx.DGL().glNormal3fv(static_cast<const GLfloat*>(normalPtr[i]));
+            break;
+        default:
+            GLES_ASSERT(false);
+        }
+    }
+
+    if(colorPtr != NULL)
+    {
+        switch(colorPtr.Type())
+        {
+        case GL_UNSIGNED_BYTE:
+            ctx.DGL().glColor4ubv(static_cast<const GLubyte*>(colorPtr[i]));
+            break;
+        case GL_FIXED:
+        case GL_FLOAT:
+            ctx.DGL().glColor4fv(static_cast<const GLfloat*>(colorPtr[i]));
+            break;
+        default:
+            GLES_ASSERT(false);
+        }
+    }
+
+    GLES_ASSERT(pointSizePtr != NULL);
+    ctx.DGL().glPointSize(*static_cast<const GLfloat*>(pointSizePtr[i]));
+
+    for(unsigned int j = 0; j < ctx.MaxTextureUnits(); j++)
+    {
+        int texture = GL_TEXTURE0 + j;
+		
+        if(texCoordPtr[j] != NULL)
+        {
+            switch(texCoordPtr[j].Type())
+            {
+            case GL_BYTE:
+            case GL_SHORT:
+                switch(texCoordPtr[j].Size())
+                {
+                case 2:
+                    ctx.DGL().glMultiTexCoord2sv(texture, static_cast<const GLshort*>(texCoordPtr[j][i]));
+                    break;
+                case 3:
+                    ctx.DGL().glMultiTexCoord3sv(texture, static_cast<const GLshort*>(texCoordPtr[j][i]));
+                    break;
+                case 4:
+                    ctx.DGL().glMultiTexCoord4sv(texture, static_cast<const GLshort*>(texCoordPtr[j][i]));
+                    break;
+                default:
+                    GLES_ASSERT(false);
+                }
+                break;
+            case GL_FIXED:
+            case GL_FLOAT:
+                switch(texCoordPtr[j].Size())
+                {
+                case 2:
+                    ctx.DGL().glMultiTexCoord2fv(texture, static_cast<const GLfloat*>(texCoordPtr[j][i]));
+                    break;
+                case 3:
+                    ctx.DGL().glMultiTexCoord3fv(texture, static_cast<const GLfloat*>(texCoordPtr[j][i]));
+                    break;
+                case 4:
+                    ctx.DGL().glMultiTexCoord4fv(texture, static_cast<const GLfloat*>(texCoordPtr[j][i]));
+                    break;
+                default:
+                    GLES_ASSERT(false);
+                }
+                break;
+            default:
+                GLES_ASSERT(false);
+            }
+        }
+    }
+
+    GLES_ASSERT(vertexPtr != NULL);
+    ctx.DGL().glBegin(GL_POINTS);
+    switch(vertexPtr.Type())
+    {
+    case GL_BYTE:
+    case GL_SHORT:
+        switch(vertexPtr.Size())
+        {
+        case 2:
+            ctx.DGL().glVertex2sv(static_cast<const GLshort*>(vertexPtr[i]));
+            break;
+        case 3:
+            ctx.DGL().glVertex3sv(static_cast<const GLshort*>(vertexPtr[i]));
+            break;
+        case 4:
+            ctx.DGL().glVertex4sv(static_cast<const GLshort*>(vertexPtr[i]));
+            break;
+        default:
+            GLES_ASSERT(false);
+        }
+        break;
+    case GL_FIXED:
+    case GL_FLOAT:
+        switch(vertexPtr.Size())
+        {
+        case 2:
+            ctx.DGL().glVertex2fv(static_cast<const GLfloat*>(vertexPtr[i]));
+            break;
+        case 3:
+            ctx.DGL().glVertex3fv(static_cast<const GLfloat*>(vertexPtr[i]));
+            break;
+        case 4:
+            ctx.DGL().glVertex4fv(static_cast<const GLfloat*>(vertexPtr[i]));
+            break;
+        default:
+            GLES_ASSERT(false);
+        }
+        break;
+    default:
+        GLES_ASSERT(false);
+    }
+    ctx.DGL().glEnd();
+}
+bool drawPointArrays(const GLESContext& ctx, int first, int count,
+                     GLESArray* vertexArr, GLESArray* normalArr, GLESArray* colorArr, GLESArray** texCoordArr)
+{
+    GLESArray* pointSizeArr = ctx.PointSizeArray().Convert(count);
+    if(pointSizeArr == NULL)
+    {
+        return false;
+    }
+
+    GLES_ASSERT(vertexArr != NULL);
+    GLESArrayPointer vertexPtr = vertexArr->ArrayPointer();
+    GLESArrayPointer normalPtr = normalArr != NULL ? normalArr->ArrayPointer() : GLESArrayPointer();
+    GLESArrayPointer colorPtr = colorArr != NULL ? colorArr->ArrayPointer() : GLESArrayPointer();
+    GLESArrayPointer pointSizePtr = pointSizeArr != NULL ? pointSizeArr->ArrayPointer() : GLESArrayPointer();
+
+    GLESArrayPointer* texCoordPtr = GLES_NEW GLESArrayPointer[ctx.MaxTextureUnits()];
+    if(texCoordPtr == NULL)
+    {
+        delete pointSizeArr;
+        return false;
+    }
+    for(unsigned int i = 0; i < ctx.MaxTextureUnits(); i++)
+    {
+        texCoordPtr[i] = texCoordArr[i] != NULL ? texCoordArr[i]->ArrayPointer() : GLESArrayPointer();
+    }
+
+    // Draw individual points
+
+    for(int i = first; i < first + count; i++)
+    {
+        drawPoint(ctx, i, vertexPtr, normalPtr, colorPtr, pointSizePtr, texCoordPtr);
+    }
+
+    delete[] texCoordPtr;
+    delete pointSizeArr;
+
+    return true;
+}
+bool drawPointElements(const GLESContext& ctx, int count, GLenum type, const void* indices,
+                       GLESArray* vertexArr, GLESArray* normalArr, GLESArray* colorArr, GLESArray** texCoordArr)
+{
+    GLESArray* pointSizeArr = ctx.PointSizeArray().Convert(count);
+    if(pointSizeArr == NULL)
+    {
+        return false;
+    }
+
+    GLES_ASSERT(vertexArr != NULL);
+    GLESArrayPointer vertexPtr = vertexArr->ArrayPointer();
+    GLESArrayPointer normalPtr = normalArr != NULL ? normalArr->ArrayPointer() : GLESArrayPointer();
+    GLESArrayPointer colorPtr = colorArr != NULL ? colorArr->ArrayPointer() : GLESArrayPointer();
+    GLESArrayPointer pointSizePtr = pointSizeArr != NULL ? pointSizeArr->ArrayPointer() : GLESArrayPointer();
+
+    GLESArrayPointer* texCoordPtr = GLES_NEW GLESArrayPointer[ctx.MaxTextureUnits()];
+    if(texCoordPtr == NULL)
+    {
+        delete pointSizeArr;
+        return false;
+    }
+    for(unsigned int i = 0; i < ctx.MaxTextureUnits(); i++)
+    {
+        texCoordPtr[i] = texCoordArr[i] != NULL ? texCoordArr[i]->ArrayPointer() : GLESArrayPointer();
+    }
+
+    // Draw individual points
+
+    for(int i = 0; i < count; i++)
+    {
+        int index;
+        switch(type)
+        {
+        case GL_UNSIGNED_BYTE:
+            index = static_cast<const GLubyte*>(indices)[i];
+            break;
+        case GL_UNSIGNED_SHORT:
+            index = static_cast<const GLushort*>(indices)[i];
+            break;
+        default:
+            GLES_ASSERT(false);
+        }
+        drawPoint(ctx, index, vertexPtr, normalPtr, colorPtr, pointSizePtr, texCoordPtr);
+    }
+
+    delete[] texCoordPtr;
+    delete pointSizeArr;
+
+    return true;
+}
+GL_API void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count)
+{
+	GLES_ENTER();
+	GLES_ERROR_IF(count < 0, GL_INVALID_VALUE);
+
+    if(!ctx->IsArrayEnabled(GLES_VERTEX_ARRAY) || !count)
+    {
+        // Nothing to draw
+        GLES_LEAVE();
+    }
+
+    GLESArray* vertexArr = NULL;
+    GLESArray* normalArr = NULL;
+    GLESArray* colorArr = NULL;
+    GLESArray** texCoordArr = GLES_NEW GLESArray*[ctx->MaxTextureUnits()];
+    for(unsigned int i = 0; i < ctx->MaxTextureUnits(); i++)
+    {
+        texCoordArr[i] = NULL;
+    }
+
+    bool oom = !convertArrays(*ctx, count, &vertexArr, &normalArr, &colorArr, texCoordArr);
+    if(!oom)
+    {
+		GLES_LOCK_DRAW_SURFACE();
+        if(mode == GL_POINTS && ctx->IsArrayEnabled(GLES_POINT_SIZE_ARRAY))
+        {
+            oom = !drawPointArrays(*ctx, first, count, vertexArr, normalArr, colorArr, texCoordArr);
+        }
+        else
+        {
+            ctx->DGL().glDrawArrays (mode, first, count);
+        }
+		GLES_UNLOCK_SURFACE();
+    }
+
+    for(unsigned int i = 0; i < ctx->MaxTextureUnits(); i++)
+    {
+        delete texCoordArr[i];
+    }
+    delete colorArr;
+    delete normalArr;
+    delete vertexArr;
+    delete[] texCoordArr;
+
+    if(oom)
+    {
+        GLES_ERROR(GL_OUT_OF_MEMORY);
+    }
+
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices)
+{
+	GLES_ENTER();
+	GLES_ERROR_IF(count < 0, GL_INVALID_VALUE);
+	GLES_ERROR_IF(type != GL_UNSIGNED_BYTE && type != GL_UNSIGNED_SHORT, GL_INVALID_ENUM);
+
+    if(!ctx->IsArrayEnabled(GLES_VERTEX_ARRAY) || !count)
+    {
+        // Nothing to draw
+        GLES_LEAVE();
+    }
+
+    GLESArray* vertexArr = NULL;
+    GLESArray* normalArr = NULL;
+    GLESArray* colorArr = NULL;
+    GLESArray** texCoordArr = GLES_NEW GLESArray*[ctx->MaxTextureUnits()];
+    for(unsigned int i = 0; i < ctx->MaxTextureUnits(); i++)
+    {
+        texCoordArr[i] = NULL;
+    }
+
+    bool oom = !convertArrays(*ctx, count, &vertexArr, &normalArr, &colorArr, texCoordArr);
+    if(!oom)
+    {
+        if(indices == NULL && ctx->ElementArrayBufferBinding())
+        {
+            indices = ctx->ElementArrayBuffer()->data;
+        }
+
+		GLES_LOCK_DRAW_SURFACE();
+        if(mode == GL_POINTS && ctx->IsArrayEnabled(GLES_POINT_SIZE_ARRAY))
+        {
+            oom = !drawPointElements(*ctx, count, type, indices,
+                                     vertexArr, normalArr, colorArr, texCoordArr);
+        }
+        else
+        {
+            ctx->DGL().glDrawElements (mode, count, type, indices);
+        }
+		GLES_UNLOCK_SURFACE();
+    }
+
+    for(unsigned int i = 0; i < ctx->MaxTextureUnits(); i++)
+    {
+        delete texCoordArr[i];
+    }
+    delete colorArr;
+    delete normalArr;
+    delete vertexArr;
+    delete[] texCoordArr;
+
+    if(oom)
+    {
+        GLES_ERROR(GL_OUT_OF_MEMORY);
+    }
+
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glEnable (GLenum cap)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidCapabilityEnum(cap), GL_INVALID_ENUM);
+    ctx->DGL().glEnable (cap);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glEnableClientState (GLenum array)
+{
+    GLES_ENTER();
+    array = array == GL_POINT_SIZE_ARRAY_OES ? GL_POINT_SIZE_ARRAY : array;
+    int flag = static_cast<int>(mapArrayType(array));
+    GLES_ERROR_IF(flag == GLES_INVALID_ARRAY, GL_INVALID_ENUM);
+    if(flag == GLES_TEXTURE_COORD_ARRAY)
+    {
+        flag <<= ctx->ClientActiveTexture();
+    }
+    ctx->EnableArray(static_cast<GLESArrayFlag>(flag));
+    if(array != GL_POINT_SIZE_ARRAY_OES)
+    {
+        ctx->DGL().glEnableClientState(array);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glFinish (void)
+{
+	GLES_ENTER();
+	ctx->DGL().glFinish();
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glFlush (void)
+{
+	GLES_ENTER();
+	ctx->DGL().glFlush();
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glFogx (GLenum pname, GLfixed param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidSingleValuedFogParamEnum(pname), GL_INVALID_ENUM);
+    if(pname == GL_FOG_MODE)
+    {
+        ctx->DGL().glFogf(pname, static_cast<GLfloat>(param));
+    }
+    else
+    {
+        ctx->DGL().glFogf(pname, X_TO_F(param));
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glFogxv (GLenum pname, const GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidFogParamEnum(pname), GL_INVALID_ENUM);
+    if(pname == GL_FOG_MODE)
+    {
+        GLfloat fparam = static_cast<GLfloat>(params[0]);
+        ctx->DGL().glFogfv (pname, &fparam);
+    }
+    else
+    {
+        GLfloat fparams[4];
+        fparams[0] = X_TO_F(params[0]);
+        if (pname == GL_FOG_COLOR)
+        {
+            fparams[1] = X_TO_F(params[1]);
+            fparams[2] = X_TO_F(params[2]);
+            fparams[3] = X_TO_F(params[3]);
+        }
+        ctx->DGL().glFogfv (pname, fparams);
+    }
+	
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glFrontFace (GLenum mode)
+{
+    GLES_ENTER();
+    ctx->DGL().glFrontFace (mode);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glFrustumx (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar)
+{
+    GLES_ENTER();
+    ctx->DGL().glFrustum (X_TO_D(left), X_TO_D(right), X_TO_D(bottom), X_TO_D(top), X_TO_D(zNear), X_TO_D(zFar));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean *params)
+{
+    GLES_ENTER();
+    if(!glesGetParameter(*ctx, ctx->DGL(), pname, GLES_TYPE_BOOLEAN, params))
+    {
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidBufferTarget(target), GL_INVALID_ENUM);
+	
+    const GLESBuffer* buffer;
+    switch(target)
+    {
+    case GL_ARRAY_BUFFER:
+        buffer = ctx->ArrayBuffer();
+        break;
+    case GL_ELEMENT_ARRAY_BUFFER:
+        buffer = ctx->ElementArrayBuffer();
+        break;
+    default:
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+
+    switch(pname)
+    {
+    case GL_BUFFER_SIZE:
+        *params = buffer->size;
+        break;
+    case GL_BUFFER_USAGE:
+        *params = buffer->usage;
+        break;
+    default:
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetClipPlanex (GLenum pname, GLfixed eqn[4])
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(pname < GL_CLIP_PLANE0 || pname >= GL_CLIP_PLANE0 + ctx->MaxClipPlanes(), GL_INVALID_ENUM);
+    GLdouble deqn[4];
+    ctx->DGL().glGetClipPlane(pname, deqn);
+    for (int i = 0; i < 4; i++)
+    {
+        eqn[i] = D_TO_X(deqn[i]);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGenBuffers (GLsizei n, GLuint *buffers)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(n < 0, GL_INVALID_VALUE);
+    ctx->ReserveBufferNames(n, buffers);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGenTextures (GLsizei n, GLuint *textures)
+{
+    GLES_ENTER();
+    ctx->DGL().glGenTextures (n, textures);
+    GLES_LEAVE();
+}
+GL_API GLenum GL_APIENTRY glGetError (void)
+{
+    GLES_ENTER_RET(GL_INVALID_OPERATION);
+    GLenum error = ctx->Error();
+    ctx->SetError(GL_NO_ERROR);
+    GLES_LEAVE_RET(error);
+}
+GL_API void GL_APIENTRY glGetFixedv (GLenum pname, GLfixed *params)
+{
+    GLES_ENTER();
+    if(!glesGetParameter(*ctx, ctx->DGL(), pname, GLES_TYPE_FIXED, params))
+    {
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetIntegerv (GLenum pname, GLint *params)
+{
+    GLES_ENTER();
+    if(!glesGetParameter(*ctx, ctx->DGL(), pname, GLES_TYPE_INTEGER, params))
+    {
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_LEAVE();
+}
+bool isValidLightEnum(GLenum light, unsigned int maxLights)
+{
+    return light >= GL_LIGHT0 && light < GL_LIGHT0 + maxLights;
+}
+GL_API void GL_APIENTRY glGetLightxv (GLenum light, GLenum pname, GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidLightEnum(light, ctx->MaxLights()), GL_INVALID_ENUM);
+	
+    float fparams[4];
+    ctx->DGL().glGetLightfv(light, pname, fparams);
+
+    switch (pname)
+    {
+    case GL_AMBIENT:
+    case GL_DIFFUSE:
+    case GL_SPECULAR:
+    case GL_POSITION:
+        params[3] = F_TO_X(fparams[3]);
+    case GL_SPOT_DIRECTION:
+        params[2] = F_TO_X(fparams[2]);
+        params[1] = F_TO_X(fparams[1]);
+    case GL_SPOT_EXPONENT:
+    case GL_SPOT_CUTOFF:
+    case GL_CONSTANT_ATTENUATION:
+    case GL_LINEAR_ATTENUATION:
+    case GL_QUADRATIC_ATTENUATION:
+        params[0] = F_TO_X(fparams[0]);
+        break;
+    default:
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+	
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetMaterialxv (GLenum face, GLenum pname, GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidMaterialParamEnum(pname), GL_INVALID_ENUM);
+    GLfloat fparams[4];
+    ctx->DGL().glGetMaterialfv (face, pname, fparams);
+    params[0] = F_TO_X(fparams[0]);
+    if(pname != GL_SHININESS)
+    {
+        params[1] = F_TO_X(fparams[1]);
+        params[2] = F_TO_X(fparams[2]);
+        params[3] = F_TO_X(fparams[3]);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetPointerv (GLenum pname, GLvoid **params)
+{
+    GLES_ENTER();
+    switch(pname)
+    {
+    case GL_VERTEX_ARRAY_POINTER:
+        *params = const_cast<GLvoid*>(ctx->VertexArray().Pointer());
+        break;
+    case GL_NORMAL_ARRAY_POINTER:
+        *params = const_cast<GLvoid*>(ctx->NormalArray().Pointer());
+        break;
+    case GL_COLOR_ARRAY_POINTER:
+        *params = const_cast<GLvoid*>(ctx->ColorArray().Pointer());
+        break;
+    case GL_POINT_SIZE_ARRAY_POINTER_OES:
+        *params = const_cast<GLvoid*>(ctx->PointSizeArray().Pointer());
+        break;
+    case GL_TEXTURE_COORD_ARRAY_POINTER:
+        *params = const_cast<GLvoid*>(ctx->TexCoordArray().Pointer());
+        break;
+    default:
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_LEAVE();
+}
+GL_API const GLubyte * GL_APIENTRY glGetString (GLenum name)
+{
+    GLES_ENTER_RET(NULL);
+    static const GLubyte vendor[] = "Nokia";
+    static const GLubyte renderer[] = "OpenGL ES-CM 1.1";
+    static const GLubyte version[] = "OpenGL ES-CM 1.1";
+    static const GLubyte extensions[] = "GL_OES_read_format GL_OES_compressed_paletted_texture "
+                                        "GL_OES_point_size_array GL_OES_point_sprite";
+    const GLubyte* str = NULL;
+    switch(name)
+    {
+    case GL_VENDOR:
+        str = vendor;
+        break;
+    case GL_RENDERER:
+        str = renderer;
+        break;
+    case GL_VERSION:
+        str = version;
+        break;
+    case GL_EXTENSIONS:
+        str = extensions;
+        break;
+    default:
+        GLES_ERROR_RET(GL_INVALID_ENUM, NULL);
+        break;
+    }
+    GLES_LEAVE_RET(str);
+}
+GL_API void GL_APIENTRY glGetTexEnviv (GLenum env, GLenum pname, GLint *params)
+{
+    GLES_ENTER();
+    pname = pname == GL_COORD_REPLACE_OES ? GL_COORD_REPLACE : pname;
+    ctx->DGL().glGetTexEnviv (env, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetTexEnvxv (GLenum env, GLenum pname, GLfixed *params)
+{
+    GLES_ENTER();
+    GLfloat fparams[4];
+
+    pname = pname == GL_COORD_REPLACE_OES ? GL_COORD_REPLACE : pname;
+
+    switch (pname)
+    {
+    case GL_TEXTURE_ENV_COLOR:
+        ctx->DGL().glGetTexEnvfv(env, pname, fparams);
+        params[0] = F_TO_X(fparams[0]);
+        params[1] = F_TO_X(fparams[1]);
+        params[2] = F_TO_X(fparams[2]);
+        params[3] = F_TO_X(fparams[3]);
+        break;
+    case GL_RGB_SCALE:
+    case GL_ALPHA_SCALE:
+        ctx->DGL().glGetTexEnvfv(env, pname, fparams);
+        params[0] = F_TO_X(fparams[0]);
+        break;
+    case GL_COMBINE_RGB:
+    case GL_COMBINE_ALPHA:
+    case GL_COORD_REPLACE:
+    case GL_TEXTURE_ENV_MODE:
+    case GL_SRC0_RGB:
+    case GL_SRC0_ALPHA:
+    case GL_SRC1_RGB:
+    case GL_SRC1_ALPHA:
+    case GL_SRC2_RGB:
+    case GL_SRC2_ALPHA:
+    case GL_OPERAND0_RGB:
+    case GL_OPERAND0_ALPHA:
+    case GL_OPERAND1_RGB:
+    case GL_OPERAND1_ALPHA:
+    case GL_OPERAND2_RGB:
+    case GL_OPERAND2_ALPHA:
+        {
+            GLint i;
+            ctx->DGL().glGetTexEnviv(env, pname, &i);
+            params[0] = static_cast<GLfixed>(i);
+        }
+        break;
+    default:
+        GLES_ERROR(GL_INVALID_ENUM);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glGetTexParameteriv (target, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glGetTexParameterxv (GLenum target, GLenum pname, GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    // All parameters are enum values, no conversion to be done.
+    ctx->DGL().glGetTexParameteriv (target, pname, params);
+    GLES_LEAVE();
+}
+bool isValidHintEnum(GLenum hint)
+{
+    switch(hint)
+    {
+    case GL_PERSPECTIVE_CORRECTION_HINT:
+    case GL_POINT_SMOOTH_HINT:
+    case GL_LINE_SMOOTH_HINT:
+    case GL_FOG_HINT:
+    case GL_GENERATE_MIPMAP_HINT:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glHint (GLenum target, GLenum mode)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidHintEnum(target), GL_INVALID_ENUM);
+    ctx->DGL().glHint (target, mode);
+    GLES_LEAVE();
+}
+GL_API GLboolean GL_APIENTRY glIsBuffer (GLuint buffer)
+{
+    GLES_ENTER_RET(GL_FALSE);
+    return ctx->Buffer(buffer) != NULL;
+    GLES_LEAVE_RET(GL_FALSE);
+}
+GL_API GLboolean GL_APIENTRY glIsEnabled (GLenum cap)
+{
+    GLES_ENTER_RET(GL_FALSE);
+    switch(cap)
+    {
+    case GL_VERTEX_ARRAY:
+        return ctx->IsArrayEnabled(GLES_VERTEX_ARRAY);
+    case GL_NORMAL_ARRAY:
+        return ctx->IsArrayEnabled(GLES_NORMAL_ARRAY);
+    case GL_COLOR_ARRAY:
+        return ctx->IsArrayEnabled(GLES_COLOR_ARRAY);
+    case GL_POINT_SIZE_ARRAY_OES:
+        return ctx->IsArrayEnabled(GLES_POINT_SIZE_ARRAY);
+    case GL_TEXTURE_COORD_ARRAY:
+        {
+        int flag = static_cast<int>(GLES_TEXTURE_COORD_ARRAY);
+        flag <<= ctx->ClientActiveTexture();
+        return ctx->IsArrayEnabled(static_cast<GLESArrayFlag>(flag));
+        }
+    case GL_POINT_SPRITE_OES:
+        return ctx->DGL().glIsEnabled(GL_POINT_SPRITE);
+    default:
+        GLES_ERROR_IF_RET(!isValidCapabilityEnum(cap), GL_INVALID_ENUM, GL_FALSE);
+        return ctx->DGL().glIsEnabled(cap);
+    }
+    GLES_LEAVE_RET(ctx->DGL().glIsEnabled (cap));
+}
+GL_API GLboolean GL_APIENTRY glIsTexture (GLuint texture)
+{
+    GLES_ENTER_RET(GL_FALSE);
+    GLES_LEAVE_RET(ctx->DGL().glIsTexture (texture));
+}
+GL_API void GL_APIENTRY glLightModelx (GLenum pname, GLfixed param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(pname != GL_LIGHT_MODEL_TWO_SIDE, GL_INVALID_ENUM);
+    ctx->DGL().glLightModelf (pname, static_cast<GLfloat>(param));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLightModelxv (GLenum pname, const GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidLightModelParamEnum(pname), GL_INVALID_ENUM);
+    if(pname == GL_LIGHT_MODEL_TWO_SIDE)
+    {
+        GLfloat fparam = static_cast<GLfloat>(params[0]);
+        ctx->DGL().glLightModelfv (pname, &fparam);
+    }
+    else
+    {
+        GLfloat fparams[4];
+        fparams[0] = X_TO_F(params[0]);
+        if(pname == GL_LIGHT_MODEL_AMBIENT)
+        {
+            fparams[1] = X_TO_F(params[1]);
+            fparams[2] = X_TO_F(params[2]);
+            fparams[3] = X_TO_F(params[3]);
+        }
+        ctx->DGL().glLightModelfv (pname, fparams);
+    }
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLightx (GLenum light, GLenum pname, GLfixed param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidLightEnum(light, ctx->MaxLights()), GL_INVALID_ENUM);
+    ctx->DGL().glLightf (light, pname, X_TO_F(param));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLightxv (GLenum light, GLenum pname, const GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidLightEnum(light, ctx->MaxLights()), GL_INVALID_ENUM);
+    GLfloat fparams[4];
+    switch(pname)
+    {
+    case GL_AMBIENT:
+    case GL_DIFFUSE:
+    case GL_SPECULAR:
+    case GL_POSITION:
+        fparams[3] = X_TO_F(params[3]);
+    case GL_SPOT_DIRECTION:
+        fparams[2] = X_TO_F(params[2]);
+        fparams[1] = X_TO_F(params[1]);
+        break;
+    }
+    fparams[0] = X_TO_F(params[0]);
+    ctx->DGL().glLightfv (light, pname, fparams);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLineWidthx (GLfixed width)
+{
+    GLES_ENTER();
+    ctx->DGL().glLineWidth (X_TO_F(width));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLoadIdentity (void)
+{
+    GLES_ENTER();
+    ctx->DGL().glLoadIdentity ();
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLoadMatrixx (const GLfixed *m)
+{
+    GLES_ENTER();
+    GLfloat fm[16];
+    for(int i = 0; i < 16; i++)
+    {
+        fm[i] = X_TO_F(m[i]);
+    }
+    ctx->DGL().glLoadMatrixf (fm);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glLogicOp (GLenum opcode)
+{
+    GLES_ENTER();
+    ctx->DGL().glLogicOp (opcode);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glMaterialx (GLenum face, GLenum pname, GLfixed param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidSingleValuedMaterialParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glMaterialf (face, pname, X_TO_F(param));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glMaterialxv (GLenum face, GLenum pname, const GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidMaterialParamEnum(pname), GL_INVALID_ENUM);
+    GLfloat fparams[4];
+    for(int i = 0; i < 4; i++)
+    {
+        fparams[i] = X_TO_F(params[i]);
+    }
+    ctx->DGL().glMaterialfv (face, pname, fparams);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glMatrixMode (GLenum mode)
+{
+    GLES_ENTER();
+    ctx->DGL().glMatrixMode (mode);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glMultMatrixx (const GLfixed *m)
+{
+    GLES_ENTER();
+    GLfloat fm[16];
+    for(int i = 0; i < 16; i++)
+    {
+        fm[i] = X_TO_F(m[i]);
+    }
+    ctx->DGL().glMultMatrixf (fm);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glMultiTexCoord4x (GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTextureTargetEnum(target, ctx->MaxTextureUnits()), GL_INVALID_ENUM);
+    ctx->DGL().glMultiTexCoord4f (target, X_TO_F(s), X_TO_F(t), X_TO_F(r), X_TO_F(q));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glNormal3x (GLfixed nx, GLfixed ny, GLfixed nz)
+{
+    GLES_ENTER();
+    ctx->DGL().glNormal3f (X_TO_F(nx), X_TO_F(ny), X_TO_F(nz));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glNormalPointer (GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(type != GL_BYTE && type != GL_SHORT && type != GL_FIXED && type != GL_FLOAT, GL_INVALID_ENUM);
+    GLES_ERROR_IF(stride < 0, GL_INVALID_VALUE);
+    ctx->SetNormalArray(type, stride, pointer);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glOrthox (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar)
+{
+    GLES_ENTER();
+    ctx->DGL().glOrtho (X_TO_D(left), X_TO_D(right), X_TO_D(bottom), X_TO_D(top), X_TO_D(zNear), X_TO_D(zFar));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPixelStorei (GLenum pname, GLint param)
+{
+    GLES_ENTER();
+    ctx->DGL().glPixelStorei (pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPointParameterx (GLenum pname, GLfixed param)
+{
+    GLES_ENTER();
+    ctx->DGL().glPointParameterf (pname, X_TO_F(param));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPointParameterxv (GLenum pname, const GLfixed *params)
+{
+    GLES_ENTER();
+    GLfloat fparams[3];
+    fparams[0] = X_TO_F(params[0]);
+    if(pname == GL_POINT_DISTANCE_ATTENUATION)
+    {
+        fparams[1] = X_TO_F(params[1]);
+        fparams[2] = X_TO_F(params[2]);
+    }
+    ctx->DGL().glPointParameterfv (pname, fparams);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPointSizex (GLfixed size)
+{
+    GLES_ENTER();
+    ctx->DGL().glPointSize (X_TO_F(size));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPolygonOffsetx (GLfixed factor, GLfixed units)
+{
+    GLES_ENTER();
+    ctx->DGL().glPolygonOffset (X_TO_F(factor), X_TO_F(units));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPopMatrix (void)
+{
+    GLES_ENTER();
+    ctx->DGL().glPopMatrix();
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glPushMatrix (void)
+{
+    GLES_ENTER();
+    ctx->DGL().glPushMatrix();
+    GLES_LEAVE();
+}
+bool isValidPixelTypeEnum(GLenum type)
+{
+    switch(type)
+    {
+    case GL_UNSIGNED_BYTE:
+    case GL_UNSIGNED_SHORT_5_6_5:
+    case GL_UNSIGNED_SHORT_4_4_4_4:
+    case GL_UNSIGNED_SHORT_5_5_5_1:
+        return true;
+    default:
+        return false;
+    }
+}
+GL_API void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels)
+{
+	GLES_ENTER();
+	GLES_ERROR_IF(!isValidPixelFormatEnum(format), GL_INVALID_ENUM);
+	GLES_ERROR_IF(!isValidPixelTypeEnum(type), GL_INVALID_ENUM);
+	GLES_LOCK_READ_SURFACE();
+	ctx->DGL().glReadPixels (x, y, width, height, format, type, pixels);
+	GLES_UNLOCK_SURFACE();
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glRotatex (GLfixed angle, GLfixed x, GLfixed y, GLfixed z)
+{
+    GLES_ENTER();
+    ctx->DGL().glRotatef (X_TO_F(angle), X_TO_F(x), X_TO_F(y), X_TO_F(z));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glSampleCoverage (GLclampf value, GLboolean invert)
+{
+    GLES_ENTER();
+    ctx->DGL().glSampleCoverage (value, invert);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glSampleCoveragex (GLclampx value, GLboolean invert)
+{
+    GLES_ENTER();
+    ctx->DGL().glSampleCoverage (X_TO_F(value), invert);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glScalex (GLfixed x, GLfixed y, GLfixed z)
+{
+    GLES_ENTER();
+    ctx->DGL().glScalef (X_TO_F(x), X_TO_F(y), X_TO_F(z));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height)
+{
+    GLES_ENTER();
+    ctx->DGL().glScissor (x, y, width, height);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glShadeModel (GLenum mode)
+{
+    GLES_ENTER();
+    ctx->DGL().glShadeModel (mode);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask)
+{
+    GLES_ENTER();
+    ctx->DGL().glStencilFunc (func, ref, mask);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glStencilMask (GLuint mask)
+{
+    GLES_ENTER();
+    ctx->DGL().glStencilMask (mask);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass)
+{
+    GLES_ENTER();
+    ctx->DGL().glStencilOp (fail,  zfail, zpass);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexCoordPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(size != 2 && size != 3 && size != 4, GL_INVALID_VALUE);
+    GLES_ERROR_IF(type != GL_BYTE && type != GL_SHORT && type != GL_FIXED && type != GL_FLOAT, GL_INVALID_ENUM);
+    GLES_ERROR_IF(stride < 0, GL_INVALID_VALUE);
+    ctx->SetTexCoordArray(size, type, stride, pointer);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexEnvi (GLenum target, GLenum pname, GLint param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTexEnvTargetEnum(target), GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidSingleValuedTexEnvParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glTexEnvi (target, pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexEnvx (GLenum target, GLenum pname, GLfixed param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTexEnvTargetEnum(target), GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidSingleValuedTexEnvParamEnum(pname), GL_INVALID_ENUM);
+    GLfloat fparam;
+    if(target == GL_TEXTURE_ENV && (pname == GL_RGB_SCALE || pname == GL_ALPHA_SCALE))
+    {
+        fparam = X_TO_F(param);
+    }
+    else
+    {
+        fparam = static_cast<GLfloat>(param);
+    }
+    ctx->DGL().glTexEnvf (target, pname, fparam);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexEnviv (GLenum target, GLenum pname, const GLint *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTexEnvTargetEnum(target), GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexEnvParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glTexEnviv (target, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexEnvxv (GLenum target, GLenum pname, const GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(!isValidTexEnvTargetEnum(target), GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexEnvParamEnum(pname), GL_INVALID_ENUM);
+    GLfloat fparams[4];
+    switch(pname)
+    {
+    case GL_TEXTURE_ENV_COLOR:
+        fparams[3] = X_TO_F(params[3]);
+        fparams[2] = X_TO_F(params[2]);
+        fparams[1] = X_TO_F(params[1]);
+        // fall-through
+    case GL_RGB_SCALE:
+    case GL_ALPHA_SCALE:
+        fparams[0] = X_TO_F(params[0]);
+        break;
+    default:
+        fparams[0] = static_cast<GLfloat>(params[0]);
+    }
+    ctx->DGL().glTexEnvfv (target, pname, fparams);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	GLES_ENTER();
+	GLES_ERROR_IF(!isValidPixelFormatEnum(internalformat), GL_INVALID_ENUM);
+	GLES_ERROR_IF(!isValidPixelFormatEnum(format), GL_INVALID_ENUM);
+	GLES_ERROR_IF(!isValidPixelTypeEnum(type), GL_INVALID_ENUM);
+	GLES_ERROR_IF(internalformat != format, GL_INVALID_ENUM);
+	GLES_ERROR_IF(isPalettedFormat(internalformat), GL_INVALID_OPERATION);
+	
+	ctx->DGL().glTexImage2D (target, level, internalformat, width, height, border, format, type, pixels);
+	if(ctx->GetHostError() == GL_NO_ERROR)
+	{
+		GLESTexture* texture = ctx->Texture(ctx->TextureBinding());
+		GLES_ASSERT(texture != NULL);
+		texture->SetLevel(level, internalformat, width, height);
+
+		GLint genMipmap;
+		ctx->DGL().glGetTexParameteriv(target, GL_GENERATE_MIPMAP, &genMipmap);
+		if(level == 0 && genMipmap)
+		{
+			GLESTexture* texture = ctx->Texture(ctx->TextureBinding());
+			GLES_ASSERT(texture != NULL);
+			texture->GenerateMipmap();
+		}
+
+		if(texture->Level(level)->boundSurface != NULL)
+		{
+			// Texture is respecified. Release the bound EGLSurface.
+			glesReleaseTexImage(texture->Level(level)->boundSurface, texture->Name(), level);
+			texture->Level(level)->boundSurface = NULL;
+		}
+	}
+
+	GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glTexParameteri (target, pname, param);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexParameterx (GLenum target, GLenum pname, GLfixed param)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glTexParameterf (target, pname, static_cast<GLfloat>(param));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    ctx->DGL().glTexParameteriv (target, pname, params);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexParameterxv (GLenum target, GLenum pname, const GLfixed *params)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+    GLES_ERROR_IF(!isValidTexParamEnum(pname), GL_INVALID_ENUM);
+    GLfloat fparam = static_cast<GLfloat>(params[0]);
+    ctx->DGL().glTexParameterfv (target, pname, &fparam);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	GLES_ENTER();
+	GLES_ERROR_IF(!isValidPixelFormatEnum(format), GL_INVALID_ENUM);
+	GLES_ERROR_IF(!isValidPixelTypeEnum(type), GL_INVALID_ENUM);
+	
+	ctx->DGL().glTexSubImage2D (target, level, xoffset, yoffset, width, height, format, type, pixels);
+
+	if(ctx->GetHostError() == GL_NO_ERROR)
+	{
+		GLint genMipmap;
+		ctx->DGL().glGetTexParameteriv(target, GL_GENERATE_MIPMAP, &genMipmap);
+		if(level == 0 && genMipmap)
+		{
+			GLESTexture* texture = ctx->Texture(ctx->TextureBinding());
+			GLES_ASSERT(texture != NULL);
+			texture->GenerateMipmap();
+		}
+	}
+
+	GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glTranslatex (GLfixed x, GLfixed y, GLfixed z)
+{
+    GLES_ENTER();
+    ctx->DGL().glTranslatef (X_TO_F(x), X_TO_F(y), X_TO_F(z));
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(size != 2 && size != 3 && size != 4, GL_INVALID_VALUE);
+    GLES_ERROR_IF(type != GL_BYTE && type != GL_SHORT && type != GL_FIXED && type != GL_FLOAT, GL_INVALID_ENUM);
+    GLES_ERROR_IF(stride < 0, GL_INVALID_VALUE);
+    ctx->SetVertexArray(size, type, stride, pointer);
+    GLES_LEAVE();
+}
+GL_API void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height)
+{
+    GLES_ENTER();
+    ctx->DGL().glViewport (x, y, width, height);
+    GLES_LEAVE();
+}
+
+#ifdef GL_OES_point_size_array
+GL_API void GL_APIENTRY glPointSizePointerOES (GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+    GLES_ENTER();
+    GLES_ERROR_IF(type != GL_FIXED && type != GL_FLOAT, GL_INVALID_ENUM);
+    GLES_ERROR_IF(stride < 0, GL_INVALID_VALUE);
+    ctx->SetPointerSizeArray(type, stride, pointer);
+    GLES_LEAVE();
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/CMakeLists.txt	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,96 @@
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+# CMake meta build file for host libGLESv2
+
+set(GLES2_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/GLES2)
+set(GLES2_INC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/include)
+
+if(WIN32)
+	message("*** EGL Win32")
+	set(GLES2_SSE_FLAGS "/arch:SSE2")
+	set(GLES2_PLATFORM_LINK_LIBRARIES "")
+else(WIN32)
+	set(GLES2_SSE_FLAGS "-msse2 -mfpmath=sse -march=pentium4")
+	set(GLES2_PLATFORM_LINK_LIBRARIES m stdc++)
+endif(WIN32)
+
+set(GLES2_SRC_FILES
+    ${GLES2_INC_DIR}/common.h
+    
+    ${GLES2_SRC_DIR}/buffer.h
+    ${GLES2_SRC_DIR}/context.h
+    ${GLES2_SRC_DIR}/degl.h
+    ${GLES2_SRC_DIR}/get.h
+    ${GLES2_SRC_DIR}/half.h
+    ${GLES2_SRC_DIR}/hgl.h
+    ${GLES2_SRC_DIR}/object.h
+    ${GLES2_SRC_DIR}/platform.h
+    ${GLES2_SRC_DIR}/program.h
+    ${GLES2_SRC_DIR}/shader.h
+    ${GLES2_SRC_DIR}/vertex.h
+    ${GLES2_SRC_DIR}/texture.h
+    ${GLES2_SRC_DIR}/util.h
+    ${GLES2_SRC_DIR}/fbo.h	
+    
+    ${GLES2_SRC_DIR}/blend.c
+    ${GLES2_SRC_DIR}/buffer.c
+    ${GLES2_SRC_DIR}/clear.c
+    ${GLES2_SRC_DIR}/context.c
+    ${GLES2_SRC_DIR}/depth.c
+    ${GLES2_SRC_DIR}/draw.c
+    ${GLES2_SRC_DIR}/fbo.c
+    ${GLES2_SRC_DIR}/get.c
+    ${GLES2_SRC_DIR}/half.c
+    ${GLES2_SRC_DIR}/hgl.c
+    ${GLES2_SRC_DIR}/object.c
+    ${GLES2_SRC_DIR}/pixel.c
+    ${GLES2_SRC_DIR}/platform.c
+    ${GLES2_SRC_DIR}/program.c
+    ${GLES2_SRC_DIR}/shader.c
+    ${GLES2_SRC_DIR}/stencil.c
+    ${GLES2_SRC_DIR}/texture.c
+    ${GLES2_SRC_DIR}/vertex.c
+    ${GLES2_SRC_DIR}/util.c
+    ${GLES2_SRC_DIR}/degl.cpp
+  )
+
+include_directories(
+  ${GLES2_SRC_DIR}
+  ${GLES2_INC_DIR}
+  ${COMMON_INC_DIR}
+  )
+
+if (WIN32)
+    add_definitions(-DCONFIG_WIN32 -DBUILD_GLES2)
+else(WIN32)
+    add_definitions(-DCONFIG_X11 -DBUILD_GLES2)
+endif(WIN32)
+
+add_library(${LIBRARY_NAME_PREFIX}GLESv2 SHARED ${GLES2_SRC_FILES})
+
+target_link_libraries(${LIBRARY_NAME_PREFIX}GLESv2 ${GLES2_PLATFORM_LINK_LIBRARIES})
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/blend.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,85 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+static GLboolean dglIsValidBlendMode(GLenum mode)
+{
+	switch(mode)
+	{
+		case GL_FUNC_ADD:
+		case GL_FUNC_SUBTRACT:
+		case GL_FUNC_REVERSE_SUBTRACT:
+			return GL_TRUE;
+
+		default:
+			return GL_FALSE;
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+	DGLES2_ENTER();
+	ctx->hgl.BlendColor(red, green, blue, alpha);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBlendEquation(GLenum mode)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValidBlendMode(mode), GL_INVALID_ENUM);
+	ctx->hgl.BlendEquation(mode);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValidBlendMode(modeRGB), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidBlendMode(modeAlpha), GL_INVALID_ENUM);
+	ctx->hgl.BlendEquationSeparate(modeRGB, modeAlpha);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBlendFunc(GLenum sfactor, GLenum dfactor)
+{
+	DGLES2_ENTER();
+	ctx->hgl.BlendFunc(sfactor, dfactor);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
+{
+	DGLES2_ENTER();
+	ctx->hgl.BlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
+	DGLES2_LEAVE();
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/buffer.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,222 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+DGLBuffer* DGLBuffer_create(GLuint name)
+{
+	DGLBuffer* buffer = malloc(sizeof(DGLBuffer));
+	if(buffer == NULL)
+	{
+		return NULL;
+	}
+
+	buffer->obj.name = name;
+	buffer->obj.next = NULL;
+
+	buffer->data = NULL;
+	buffer->size = 0;
+	buffer->usage = GL_STATIC_DRAW;
+
+	return buffer;
+}
+
+void DGLBuffer_destroy(DGLBuffer *buffer)
+{
+	DGLES2_ASSERT(buffer != NULL);
+	if(buffer->data != NULL)
+	{
+		free(buffer->data);
+		buffer->data = NULL;
+	}
+	free(buffer);
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBindBuffer(GLenum target, GLuint buffer)
+{
+	DGLES2_ENTER();
+
+	DGLContext_getHostError(ctx);
+	
+	// The buffers are stored in both the wrapper and host.
+	ctx->hgl.BindBuffer(target, buffer);
+
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		if(target == GL_ARRAY_BUFFER)
+		{
+			if(!DGLContext_bindBuffer(ctx, buffer))
+			{
+				DGLES2_ERROR(GL_OUT_OF_MEMORY);
+			}
+		}
+		else
+		{
+			DGLES2_ERROR_IF(target != GL_ELEMENT_ARRAY_BUFFER, GL_INVALID_ENUM);
+		}
+	}
+
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBufferData(GLenum target, GLsizeiptr size, const void* data, GLenum usage)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(size < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(usage != GL_STATIC_DRAW && usage != GL_DYNAMIC_DRAW && usage != GL_STREAM_DRAW, GL_INVALID_ENUM);
+	
+	DGLContext_getHostError(ctx);
+
+	// The buffers are stored in both the wrapper and host.
+	ctx->hgl.BufferData(target, size, data, usage);
+
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		if(target == GL_ARRAY_BUFFER)
+		{
+			DGLBuffer* buffer;
+
+			DGLES2_ERROR_IF(ctx->buffer_binding == 0, GL_INVALID_OPERATION);
+			
+			buffer = DGLContext_findBuffer(ctx, ctx->buffer_binding);
+			DGLES2_ASSERT(buffer != NULL);
+			
+			if(buffer->data != NULL)
+			{
+				// Delete old data.
+				free(buffer->data);
+			}
+
+			buffer->data = malloc(size);
+			if(buffer->data == NULL)
+			{
+				DGLES2_ERROR(GL_OUT_OF_MEMORY);
+			}
+
+			if(data != NULL)
+			{
+				// Copy new data.
+				memcpy(buffer->data, data, size);
+			}
+
+			buffer->size = size;
+			buffer->usage = usage;
+		}
+		else
+		{
+			DGLES2_ERROR_IF(target != GL_ELEMENT_ARRAY_BUFFER, GL_INVALID_ENUM);
+		}
+	}
+
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void* data)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(offset < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(size < 0, GL_INVALID_VALUE);
+	
+	DGLContext_getHostError(ctx);
+
+	// The buffers are stored in both the wrapper and host.
+	ctx->hgl.BufferSubData(target, offset, size, data);
+
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		if(target == GL_ARRAY_BUFFER)
+		{
+			DGLBuffer* buffer;
+
+			DGLES2_ERROR_IF(target != GL_ARRAY_BUFFER, GL_INVALID_ENUM);
+			DGLES2_ERROR_IF(ctx->buffer_binding == 0, GL_INVALID_OPERATION);
+
+			buffer = DGLContext_findBuffer(ctx, ctx->buffer_binding);
+			DGLES2_ASSERT(buffer != NULL);
+
+			memcpy((char*)buffer->data + offset, data, size);
+		}
+		else
+		{
+			DGLES2_ERROR_IF(target != GL_ELEMENT_ARRAY_BUFFER, GL_INVALID_ENUM);
+		}
+	}
+
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDeleteBuffers(GLsizei n, const GLuint* buffers)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(n < 0, GL_INVALID_VALUE);
+	
+	DGLContext_getHostError(ctx);
+
+	// The buffers are stored in both the wrapper and host.
+	ctx->hgl.DeleteBuffers(n, buffers);
+
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		int i;
+		for(i = 0; i < n; i++)
+		{
+			DGLContext_destroyBuffer(ctx, buffers[i]);
+		}
+	}
+
+	DGLES2_LEAVE();
+}
+
+
+GL_APICALL_BUILD void GL_APIENTRY glGenBuffers(GLsizei n, GLuint* buffers)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(n < 0, GL_INVALID_VALUE);
+
+	// The buffers are stored in both the wrapper and host.
+	// Let the host come up with free buffer names. 
+	ctx->hgl.GenBuffers(n, buffers);
+
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetBufferParameteriv(GLenum target, GLenum pname, GLint* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(pname != GL_BUFFER_USAGE && pname != GL_BUFFER_SIZE, GL_INVALID_ENUM);
+	ctx->hgl.GetBufferParameteriv(target, pname, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD GLboolean GL_APIENTRY glIsBuffer(GLuint buffer)
+{
+	DGLES2_ENTER_RET(GL_FALSE);
+	DGLES2_LEAVE_RET(ctx->hgl.IsBuffer(buffer));
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/buffer.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,47 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef BUFFER_H_
+#define BUFFER_H_
+
+#include "object.h"
+
+typedef struct DGLBuffer
+{
+	DGLObject obj;
+
+	void* data;
+
+	GLsizeiptr size;
+	GLenum usage;
+} DGLBuffer;
+
+DGLBuffer*	DGLBuffer_create(GLuint name);
+void		DGLBuffer_destroy(DGLBuffer* buffer);
+
+#endif /* BUFFER_H_ */
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/clear.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,53 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+GL_APICALL_BUILD void GL_APIENTRY glClear(GLbitfield mask)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF((mask &
+					 ~(GL_COLOR_BUFFER_BIT |
+					   GL_DEPTH_BUFFER_BIT |
+					   GL_STENCIL_BUFFER_BIT)) != 0,
+				    GL_INVALID_VALUE);
+	DGLES2_BEGIN_DRAWING();
+	ctx->hgl.Clear(mask);
+	DGLES2_END_DRAWING();
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+	DGLES2_ENTER();
+	ctx->hgl.ClearColor(red, green, blue, alpha);
+	DGLES2_LEAVE();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/context.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,804 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "context.h"
+#include "util.h"
+
+DGLContext* DGLContext_create(void* native_context)
+{
+    DGLContext* ctx = malloc(sizeof(DGLContext));
+    if(ctx == NULL)
+    {
+        return NULL;
+    }
+
+    ctx->native_context = native_context;
+    ctx->initialized = GL_FALSE;
+
+    return ctx;
+}
+
+GLboolean DGLContext_initialize(DGLContext* ctx)
+{
+    GLint temp;
+
+    DGLES2_ASSERT(ctx != NULL);
+    DGLES2_ASSERT(!ctx->initialized);
+
+    hglLoad(&ctx->hgl);
+
+    ctx->buffers = NULL;
+    ctx->shaders = NULL;
+    ctx->programs = NULL;
+    ctx->textures = NULL;
+	ctx->renderbuffers = NULL;
+
+    ctx->hgl.GetIntegerv(GL_MAX_VERTEX_ATTRIBS, &temp);
+    ctx->max_vertex_attribs = temp;
+
+    ctx->vertex_arrays = malloc(ctx->max_vertex_attribs * sizeof(DGLVertexArray));
+    if(ctx->vertex_arrays == NULL)
+    {
+        return GL_FALSE;
+    }
+
+    {
+        int max_texture_size;
+        ctx->hgl.GetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
+        ctx->max_texture_level = dglLog2(max_texture_size);
+    }
+
+    // Initialize state.
+    ctx->error = GL_NO_ERROR;
+    ctx->buffer_binding = 0;
+	ctx->framebuffer_binding = 0;
+	ctx->renderbuffer_binding = 0;
+
+    DGLContext_bindTexture(ctx, GL_TEXTURE_2D, 0);
+    DGLContext_bindTexture(ctx, GL_TEXTURE_CUBE_MAP, 0);
+
+    ctx->attrib_zero[0] = 0;
+    ctx->attrib_zero[1] = 0;
+    ctx->attrib_zero[2] = 0;
+    ctx->attrib_zero[3] = 1;
+
+    // Initialize vertex arrays.
+    {
+        unsigned int i;
+        for(i = 0; i < ctx->max_vertex_attribs; i++)
+        {
+            DGLVertexArray* va = &ctx->vertex_arrays[i];
+
+            va->size = 4;
+            va->type = GL_FLOAT;
+            va->normalized = 0;
+            va->stride = 0;
+            va->ptr = NULL;
+
+            va->enabled = 0;
+            va->floatptr = NULL;
+            va->buffer = NULL;
+        }
+    }
+
+    ctx->initialized = GL_TRUE;
+
+    return GL_TRUE;
+}
+
+void DGLContext_destroy(DGLContext *ctx)
+{
+    DGLES2_ASSERT(ctx != NULL);
+
+    if(ctx->vertex_arrays != NULL)
+    {
+        unsigned int i;
+        for(i = 0; i < ctx->max_vertex_attribs; i++)
+        {
+            if(ctx->vertex_arrays[i].floatptr != NULL)
+            {
+                free(ctx->vertex_arrays[i].floatptr);
+                ctx->vertex_arrays[i].floatptr = NULL;
+            }
+        }
+        free(ctx->vertex_arrays);
+        ctx->vertex_arrays = NULL;
+    }
+
+    // Destroy buffers
+    {
+        DGLBuffer* buffer = ctx->buffers;
+        DGLBuffer* next;
+        while(buffer != NULL)
+        {
+            next = (DGLBuffer*)buffer->obj.next;
+            DGLBuffer_destroy(buffer);
+            buffer = next;
+        }
+        ctx->buffers = NULL;
+    }
+
+    // Destroy shaders
+    {
+        DGLShader* shader = ctx->shaders;
+        DGLShader* next;
+        while(shader != NULL)
+        {
+            next = (DGLShader*)shader->obj.next;
+            DGLShader_destroy(shader);
+            shader = next;
+        }
+        ctx->shaders = NULL;
+    }
+
+    // Destroy programs
+    {
+        DGLProgram* program = ctx->programs;
+        DGLProgram* next;
+        while(program != NULL)
+        {
+            next = (DGLProgram*)program->obj.next;
+            DGLProgram_destroy(program);
+            program = next;
+        }
+        ctx->programs = NULL;
+    }
+
+    // Destroy textures
+    {
+        DGLTexture* texture = ctx->textures;
+        DGLTexture* next;
+        while(texture != NULL)
+        {
+            next = (DGLTexture*)texture->obj.next;
+            DGLTexture_destroy(texture);
+            texture = next;
+        }
+        ctx->textures = NULL;
+    }
+
+	// Destroy renderbuffers
+    {
+        DGLRenderbuffer* buffer = ctx->renderbuffers;
+        DGLRenderbuffer* next;
+        while(buffer != NULL)
+        {
+            next = (DGLRenderbuffer*)buffer->obj.next;
+            DGLRenderbuffer_destroy(buffer);
+            buffer = next;
+        }
+        ctx->renderbuffers = NULL;
+    }
+
+    free(ctx);
+}
+
+void DGLContext_loadGL(DGLContext* ctx)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    hglLoad(&ctx->hgl);
+}
+
+void DGLContext_setError(DGLContext* ctx, GLenum error)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    ctx->error = error;
+}
+
+/* This function should be called before calling state-changing
+   host GL functions to clear the host GL error flag. After calling
+   the host GL functions, this function should be called again
+   to verify the success of the state change. Only then should
+   the wrapper state be modified to reflect the changes made
+   in the host state. */
+GLenum DGLContext_getHostError(DGLContext* ctx)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    {
+        GLenum host_error = ctx->hgl.GetError();
+        if(host_error != GL_NO_ERROR)
+        {
+            DGLContext_setError(ctx, host_error);
+        }
+        return host_error;
+    }
+}
+
+GLboolean DGLContext_createBuffer(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    DGLES2_ASSERT(DGLContext_findBuffer(ctx, name) == NULL);
+    DGLES2_ASSERT(name != 0);
+
+    {
+        DGLBuffer* buffer = DGLBuffer_create(name);
+        if(buffer == NULL)
+        {
+            return GL_FALSE;
+        }
+        DGLObject_insert((DGLObject**)&ctx->buffers, (DGLObject*)buffer);
+    }
+
+    return GL_TRUE;
+}
+
+void DGLContext_destroyBuffer(DGLContext *ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    if(name == 0)
+    {
+        return;
+    }
+
+    // Release buffer from the vertex arrays and context.
+    {
+        unsigned int i;
+        for(i = 0; i < ctx->max_vertex_attribs; i++)
+        {
+            DGLVertexArray* va = &ctx->vertex_arrays[i];
+            if(va->buffer != NULL && va->buffer->obj.name == name)
+            {
+                va->buffer = NULL;
+            }
+        }
+
+        if(ctx->buffer_binding == name)
+        {
+            ctx->buffer_binding = 0;
+        }
+    }
+
+    {
+        DGLBuffer* removed = (DGLBuffer*)DGLObject_remove((DGLObject**)&ctx->buffers, name);
+        if(removed != NULL)
+        {
+            DGLBuffer_destroy(removed);
+        }
+    }
+}
+
+DGLBuffer* DGLContext_findBuffer(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    return (DGLBuffer*)DGLObject_find((DGLObject*)ctx->buffers, name);
+}
+
+GLboolean DGLContext_bindBuffer(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    if(name != 0 && DGLContext_findBuffer(ctx, name) == NULL)
+    {
+        // A new buffer must be created.
+        if(!DGLContext_createBuffer(ctx, name))
+        {
+            return GL_FALSE;
+        }
+    }
+    ctx->buffer_binding = name;
+
+    return GL_TRUE;
+}
+
+GLboolean DGLContext_createShader(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    DGLES2_ASSERT(DGLContext_findShader(ctx, name) == NULL);
+    DGLES2_ASSERT(name != 0);
+
+    {
+        DGLShader* shader = DGLShader_create(name);
+        if(shader == NULL)
+        {
+            return GL_FALSE;
+        }
+        DGLObject_insert((DGLObject**)&ctx->shaders, (DGLObject*)shader);
+    }
+
+    return GL_TRUE;
+}
+
+void DGLContext_destroyShader(DGLContext *ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    if(name == 0)
+    {
+        return;
+    }
+
+    {
+        DGLShader* removed = (DGLShader*)DGLObject_remove((DGLObject**)&ctx->shaders, name);
+        if(removed != NULL)
+        {
+            DGLShader_destroy(removed);
+        }
+    }
+}
+
+DGLShader* DGLContext_findShader(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    return (DGLShader*)DGLObject_find((DGLObject*)ctx->shaders, name);
+}
+
+GLboolean DGLContext_setShaderSource(DGLContext* ctx, GLuint name, const char* source, int length)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    {
+        DGLShader* shader = DGLContext_findShader(ctx, name);
+        DGLES2_ASSERT(shader != NULL);
+
+        // Erase the previous source.
+        if(shader->source != NULL)
+        {
+            free(shader->source);
+            shader->source = NULL;
+        }
+        shader->length = 0;
+
+        DGLES2_ASSERT(source != NULL);
+        DGLES2_ASSERT(length >= 0);
+
+        shader->source = malloc(length + 1);
+        if(shader->source == NULL)
+        {
+            return GL_FALSE;
+        }
+        strncpy(shader->source, source, length);
+        shader->source[length] = 0;
+        shader->length = length;
+
+        return GL_TRUE;
+    }
+}
+
+GLboolean DGLContext_createProgram(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    DGLES2_ASSERT(DGLContext_findProgram(ctx, name) == NULL);
+    DGLES2_ASSERT(name != 0);
+
+    {
+        DGLProgram* program = DGLProgram_create(name);
+        if(program == NULL)
+        {
+            return GL_FALSE;
+        }
+        DGLObject_insert((DGLObject**)&ctx->programs, (DGLObject*)program);
+    }
+
+    return GL_TRUE;
+}
+
+void DGLContext_destroyProgram(DGLContext *ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    if(name == 0)
+    {
+        return;
+    }
+
+    {
+        DGLProgram* removed = (DGLProgram*)DGLObject_remove((DGLObject**)&ctx->programs, name);
+        if(removed != NULL)
+        {
+            DGLProgram_destroy(removed);
+        }
+    }
+}
+
+DGLProgram* DGLContext_findProgram(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    return (DGLProgram*)DGLObject_find((DGLObject*)ctx->programs, name);
+}
+
+GLboolean DGLContext_createTexture(DGLContext* ctx, GLuint name, DGLTextureType type)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    DGLES2_ASSERT(DGLContext_findTexture(ctx, name) == NULL);
+
+    {
+        DGLTexture* texture = DGLTexture_create(name, type, ctx->max_texture_level + 1);
+        if(texture == NULL)
+        {
+            return GL_FALSE;
+        }
+        DGLObject_insert((DGLObject**)&ctx->textures, (DGLObject*)texture);
+    }
+
+    return GL_TRUE;
+}
+
+void DGLContext_destroyTexture(DGLContext *ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    if(name == 0)
+    {
+        // The texture named zero cannot be destroyed.
+        return;
+    }
+
+    // Unbind texture.
+    if(ctx->texture_binding_2d == name)
+    {
+        ctx->texture_binding_2d = 0;
+    }
+    if(ctx->texture_binding_cube_map == name)
+    {
+        ctx->texture_binding_cube_map = 0;
+    }
+
+    {
+        DGLTexture* removed = (DGLTexture*)DGLObject_remove((DGLObject**)&ctx->textures, name);
+        if(removed != NULL)
+        {
+            DGLTexture_destroy(removed);
+        }
+    }
+}
+
+DGLTexture* DGLContext_findTexture(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    return (DGLTexture*)DGLObject_find((DGLObject*)ctx->textures, name);
+}
+
+GLboolean DGLContext_bindTexture(DGLContext* ctx, GLenum target, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    if(target == GL_TEXTURE_2D)
+    {
+        if(DGLContext_findTexture(ctx, name) == NULL)
+        {
+            // A new texture must be created.
+            if(!DGLContext_createTexture(ctx, name, DGLES2_TEXTURE_2D))
+            {
+                return GL_FALSE;
+            }
+        }
+        ctx->texture_binding_2d = name;
+    }
+    else if(target == GL_TEXTURE_CUBE_MAP)
+    {
+        if(DGLContext_findTexture(ctx, name) == NULL)
+        {
+            // A new texture must be created.
+            if(!DGLContext_createTexture(ctx, name, DGLES2_TEXTURE_CUBE_MAP))
+            {
+                return GL_FALSE;
+            }
+        }
+        ctx->texture_binding_cube_map = name;
+    }
+    else
+    {
+        DGLES2_ASSERT(GL_FALSE);
+    }
+
+    return GL_TRUE;
+}
+
+GLuint DGLContext_getTextureBinding(const DGLContext* ctx, GLenum target)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    switch(target)
+    {
+        case GL_TEXTURE_2D:
+            return ctx->texture_binding_2d;
+
+        case GL_TEXTURE_CUBE_MAP:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+        case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+        case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
+            return ctx->texture_binding_cube_map;
+
+        default:
+            DGLES2_ASSERT(GL_FALSE);
+    }
+
+    // No reached.
+    return 0;
+}
+
+DGLTexture* DGLContext_getTexture(DGLContext* ctx, GLenum target)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    {
+        GLuint binding = DGLContext_getTextureBinding(ctx, target);
+        return DGLContext_findTexture(ctx, binding);
+    }
+}
+
+DGLTextureLevel* DGLContext_getTextureLevel(DGLContext* ctx, GLenum target, GLint level)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    {
+        DGLTexture* texture = DGLContext_getTexture(ctx, target);
+        DGLES2_ASSERT(texture != NULL);
+
+        DGLES2_ASSERT(level < ctx->max_texture_level);
+        return DGLTexture_getLevel(texture, target, level);
+    }
+}
+
+GLboolean DGLContext_specifyTextureFromEGLImage(DGLContext* ctx, GLeglImageOES image, GLenum target)
+{
+	DGLES2_ASSERT(ctx != NULL);
+	{
+		DGLTexture* texture;
+		GLenum internal_format;
+		GLsizei width, height;
+		GLsizei stride;
+		GLenum data_format;
+		GLenum data_type;
+		void* data;
+		GLenum error;
+
+		DGLContext_getHostError(ctx);
+
+		texture = DGLContext_getTexture(ctx, target);
+		DGLES2_ASSERT(texture != NULL);
+
+		deglGetImageInfo(image, &internal_format, &width, &height, &stride, &data_format, &data_type);
+		data = deglGetImageData(image);
+		
+		ctx->hgl.TexImage2D(target, 0, internal_format, width, height, 0, data_format, data_type, data);
+
+		error = ctx->hgl.GetError();
+		if(error == GL_NO_ERROR)
+		{
+			DGLTexture_setLevel(texture, target, 0, internal_format, width, height);
+			DGLTexture_setEGLImage(texture, target, image);
+			deglRegisterImageTarget(image, target, texture->obj.name);
+			return GL_TRUE;
+		}
+		else
+		{
+			return GL_FALSE;
+		}
+	}
+}
+
+GLboolean DGLContext_createRenderbuffer(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    DGLES2_ASSERT(DGLContext_findRenderbuffer(ctx, name) == NULL);
+    DGLES2_ASSERT(name != 0);
+
+    {
+        DGLRenderbuffer* buffer = DGLRenderbuffer_create(name);
+        if(buffer == NULL)
+        {
+            return GL_FALSE;
+        }
+        DGLObject_insert((DGLObject**)&ctx->renderbuffers, (DGLObject*)buffer);
+    }
+
+    return GL_TRUE;
+}
+
+void DGLContext_destroyRenderbuffer(DGLContext *ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    if(name == 0)
+    {
+        return;
+    }
+
+    {
+        DGLRenderbuffer* removed = (DGLRenderbuffer*)DGLObject_remove((DGLObject**)&ctx->renderbuffers, name);
+        if(removed != NULL)
+        {
+            DGLRenderbuffer_destroy(removed);
+        }
+    }
+}
+
+DGLRenderbuffer* DGLContext_getColorRenderbuffer(DGLContext* ctx)
+{
+	DGLES2_ASSERT(ctx != NULL);
+	
+	if(ctx->framebuffer_binding == 0)
+	{
+		return NULL;
+	}
+
+	{
+		GLint type;
+		GLint name;
+		DGLRenderbuffer* buffer;
+
+		ctx->hgl.GetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
+
+		if(type != GL_RENDERBUFFER)
+		{
+			return NULL;
+		}
+
+		ctx->hgl.GetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
+		buffer = DGLContext_findRenderbuffer(ctx, name);
+		DGLES2_ASSERT(buffer != NULL);
+		return buffer;
+	}
+}
+
+DGLRenderbuffer* DGLContext_findRenderbuffer(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    return (DGLRenderbuffer*)DGLObject_find((DGLObject*)ctx->renderbuffers, name);
+}
+
+GLboolean DGLContext_bindRenderbuffer(DGLContext* ctx, GLuint name)
+{
+    DGLES2_ASSERT(ctx != NULL);
+    if(name != 0 && DGLContext_findRenderbuffer(ctx, name) == NULL)
+    {
+        // A new renderbuffer must be created.
+        if(!DGLContext_createRenderbuffer(ctx, name))
+        {
+            return GL_FALSE;
+        }
+    }
+    ctx->renderbuffer_binding = name;
+
+    return GL_TRUE;
+}
+
+GLboolean DGLContext_specifyRenderbufferFromEGLImage(DGLContext* ctx, GLeglImageOES image)
+{
+	GLenum imageFormat;
+	GLenum storageFormat;
+	GLsizei width, height;
+	GLint max_renderbuffer_size;
+	GLsizei stride;
+	GLenum dataFormat;
+	GLenum dataType;
+	void* data;
+
+	deglGetImageInfo(image, &imageFormat, &width, &height, &stride, &dataFormat, &dataType);
+
+	ctx->hgl.GetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &max_renderbuffer_size);
+	if(width > max_renderbuffer_size || width > max_renderbuffer_size)
+	{
+		return GL_FALSE;
+	}
+	
+	data = deglGetImageData(image);
+
+	// Map optimum format to available formats.
+	switch(imageFormat)
+	{
+#ifndef DGLES2_NO_SRGB
+		case GL_SRGB8:
+		case GL_SLUMINANCE8:
+#endif
+		case GL_RGB8:
+		case GL_LUMINANCE8:
+			storageFormat = GL_RGB8;
+			break;
+
+#ifndef DGLES2_NO_SRGB
+		case GL_SRGB8_ALPHA8:
+#endif
+		case GL_RGBA8:
+		case GL_ALPHA8:
+			storageFormat = GL_RGBA8;
+			break;
+			
+		default:
+			DGLES2_ASSERT(GL_FALSE);
+	}
+	
+	{
+		// Use a temporary FBO to set the renderbuffer contents.
+
+		GLint renderbuffer_binding;
+		GLint unpack_alignment;
+		GLuint fbo;
+
+		ctx->hgl.GetIntegerv(GL_RENDERBUFFER_BINDING, &renderbuffer_binding);
+		ctx->hgl.GetIntegerv(GL_UNPACK_ALIGNMENT, &unpack_alignment);
+
+		ctx->hgl.GenFramebuffersEXT(1, &fbo);
+		ctx->hgl.BindFramebufferEXT(GL_FRAMEBUFFER, fbo);
+		ctx->hgl.FramebufferRenderbufferEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer_binding);
+
+		ctx->hgl.RenderbufferStorageEXT(GL_RENDERBUFFER, storageFormat, width, height);
+		DGLES2_ASSERT(ctx->hgl.CheckFramebufferStatusEXT(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
+		ctx->hgl.PixelStorei(GL_UNPACK_ALIGNMENT, 1);
+		ctx->hgl.DrawPixels(width, height, dataFormat, dataType, data);
+
+		// Restore state.
+		ctx->hgl.PixelStorei(GL_UNPACK_ALIGNMENT, unpack_alignment);
+		ctx->hgl.BindFramebufferEXT(GL_FRAMEBUFFER, ctx->framebuffer_binding);
+		ctx->hgl.DeleteFramebuffersEXT(1, &fbo);
+	}
+
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		DGLRenderbuffer* buffer = DGLContext_findRenderbuffer(ctx, ctx->renderbuffer_binding);
+		DGLES2_ASSERT(buffer != NULL);
+		buffer->egl_image = image;
+		deglRegisterImageTarget(image, GL_RENDERBUFFER, buffer->obj.name);
+	}
+	else
+	{
+		return GL_FALSE;
+	}
+
+	return GL_TRUE;
+}
+
+void DGLContext_updateFBOAttachmentSiblings(DGLContext* ctx)
+{
+	DGLES2_ASSERT(ctx != NULL);
+
+	if(ctx->framebuffer_binding != 0)
+	{
+		GLenum type;
+		GLuint name;
+
+		ctx->hgl.GetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, (GLint*)&type);
+
+		if(type == GL_RENDERBUFFER)
+		{
+			DGLRenderbuffer* buffer;
+			ctx->hgl.GetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, (GLint*)&name);
+			buffer = DGLContext_findRenderbuffer(ctx, name);
+			if(buffer != NULL && buffer->egl_image != NULL)
+			{
+				deglUpdateImageSiblings(buffer->egl_image, GL_RENDERBUFFER, buffer->obj.name);
+			}
+		}
+		else if(type == GL_TEXTURE)
+		{
+			DGLTexture* texture;
+			ctx->hgl.GetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, (GLint*)&name);
+			texture = DGLContext_findTexture(ctx, name);
+			if(texture != NULL)
+			{
+				GLeglImageOES image;
+
+				GLenum target = GL_TEXTURE_2D;
+				if(texture->type == DGLES2_TEXTURE_CUBE_MAP)
+				{
+					ctx->hgl.GetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, (GLint*)&target);
+				}
+
+				image = DGLTexture_getEGLImage(texture, target);
+				if(image != NULL)
+				{
+					deglUpdateImageSiblings(image, target, texture->obj.name);
+				}
+			}
+		}
+	}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/context.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,113 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLESCONTEXT_H_
+#define _GLESCONTEXT_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "platform.h"
+#include "degl.h"
+#include "vertex.h"
+#include "buffer.h"
+#include "shader.h"
+#include "program.h"
+#include "texture.h"
+#include "fbo.h"
+
+typedef struct DGLContext
+{
+    GLboolean	initialized;
+    void*		native_context;
+    HGL			hgl;	// Extension procedure addresses are context-specific on WGL.
+
+    unsigned int max_vertex_attribs;
+    int max_texture_level;
+
+    GLenum error;
+    GLuint buffer_binding;
+    GLuint texture_binding_2d;
+    GLuint texture_binding_cube_map;
+	GLuint framebuffer_binding;
+	GLuint renderbuffer_binding;
+
+    GLfloat attrib_zero[4];	// Attribute zero can't be set in desktop GL.
+
+    DGLVertexArray*		vertex_arrays;
+    DGLBuffer*			buffers;
+    DGLShader*			shaders;
+    DGLProgram*			programs;
+    DGLTexture*			textures;
+	DGLRenderbuffer*	renderbuffers;
+} DGLContext;
+
+DGLContext* DGLContext_create(void* native_context);
+GLboolean	DGLContext_initialize(DGLContext* ctx);
+void		DGLContext_destroy(DGLContext* ctx);
+
+void		DGLContext_setError(DGLContext* ctx, GLenum error);
+GLenum		DGLContext_getHostError(DGLContext* ctx);
+
+GLboolean	DGLContext_createBuffer(DGLContext* ctx, GLuint buffer);
+void		DGLContext_destroyBuffer(DGLContext* ctx, GLuint buffer);
+DGLBuffer*	DGLContext_findBuffer(DGLContext* ctx, GLuint buffer);
+GLboolean	DGLContext_bindBuffer(DGLContext* ctx, GLuint buffer);
+
+GLboolean	DGLContext_createShader(DGLContext* ctx, GLuint shader);
+void		DGLContext_destroyShader(DGLContext* ctx, GLuint shader);
+DGLShader*	DGLContext_findShader(DGLContext* ctx, GLuint shader);
+GLboolean	DGLContext_setShaderSource(DGLContext* ctx, GLuint shader, const char* source, int length);
+
+GLboolean	DGLContext_createProgram(DGLContext* ctx, GLuint program);
+void		DGLContext_destroyProgram(DGLContext* ctx, GLuint program);
+DGLProgram*	DGLContext_findProgram(DGLContext* ctx, GLuint program);
+
+GLboolean			DGLContext_createTexture(DGLContext* ctx, GLuint texture, DGLTextureType type);
+void				DGLContext_destroyTexture(DGLContext* ctx, GLuint texture);
+DGLTexture*			DGLContext_findTexture(DGLContext* ctx, GLuint texture);
+GLboolean			DGLContext_bindTexture(DGLContext* ctx, GLenum target, GLuint name);
+DGLTexture*			DGLContext_getTexture(DGLContext* ctx, GLenum target);
+DGLTextureLevel*	DGLContext_getTextureLevel(DGLContext* ctx, GLenum target, GLint level);
+GLboolean			DGLContext_specifyTextureFromEGLImage(DGLContext* ctx, GLeglImageOES image, GLenum target);
+
+GLboolean			DGLContext_createRenderbuffer(DGLContext* ctx, GLuint buffer);
+void				DGLContext_destroyRenderbuffer(DGLContext* ctx, GLuint buffer);
+DGLRenderbuffer*	DGLContext_getColorRenderbuffer(DGLContext* ctx);
+DGLRenderbuffer*	DGLContext_findRenderbuffer(DGLContext* ctx, GLuint buffer);
+GLboolean			DGLContext_bindRenderbuffer(DGLContext* ctx, GLuint buffer);
+GLboolean			DGLContext_specifyRenderbufferFromEGLImage(DGLContext* ctx, GLeglImageOES image);
+
+void	DGLContext_updateFBOAttachmentSiblings(DGLContext* ctx);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _GLESCONTEXT_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/degl.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,923 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "degl.h"
+#include "context.h"
+#include "ColorDescriptor.h"
+#include "ImageTarget.h"
+
+void* deglGetHostProcAddress(char const* proc)
+{
+	return EGLtoGLES2Interface::GetEGLInterface()->GetHostProcAddress(proc);
+}
+
+DGLContext* deglGetCurrentContext(void)
+{
+	DGLContext* ctx = static_cast<DGLContext*>(EGLtoGLES2Interface::GetEGLInterface()->GetGLESContext());
+	return ctx;
+}
+
+int deglLockSurface(int read, int draw)
+{
+	return EGLtoGLES2Interface::GetEGLInterface()->LockGLESSurface(!!read, !!draw);
+}
+
+int deglUnlockSurface(void)
+{
+	return EGLtoGLES2Interface::GetEGLInterface()->UnlockGLESSurface();
+}
+
+static EImageTarget dglGLenumToImageTarget(GLenum target)
+{
+	switch(target)
+	{
+		case GL_TEXTURE_2D:
+			return IMAGE_TARGET_TEXTURE_2D;
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_X;
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_X;
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Y;
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Y;
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Z;
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
+			return IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Z;
+		case GL_RENDERBUFFER:
+			return IMAGE_TARGET_RENDERBUFFER;
+		default:
+			DGLES2_ASSERT(false);
+	}
+
+	// Not reached.
+	return (EImageTarget)-1;
+}
+
+void deglRegisterImageTarget(GLeglImageOES image, GLenum target, GLuint name)
+{
+	EGLtoGLES2Interface::GetEGLInterface()->RegisterImageTarget(image, dglGLenumToImageTarget(target), (void*)name);
+}
+
+void deglUnregisterImageTarget(GLeglImageOES image, GLenum target, GLuint name)
+{
+	EGLtoGLES2Interface::GetEGLInterface()->UnregisterImageTarget(image, dglGLenumToImageTarget(target), (void*)name);
+}
+
+void deglUpdateImageSiblings(GLeglImageOES image, GLenum target, GLuint name)
+{
+	EGLtoGLES2Interface::GetEGLInterface()->UpdateImageSiblings(image, dglGLenumToImageTarget(target), (void*)name);
+}
+
+void deglReleaseTexImage(void* surface, int name, int level)
+{
+	EGLtoGLES2Interface::GetEGLInterface()->ReleaseTexImage(surface, name, level);
+}
+
+static SurfaceDescriptor dglCreateSurfaceDescriptor(int redBits, int redShift, int greenBits, int greenShift, int blueBits, int blueShift, int alphaBits, int alphaShift, int luminanceBits, int luminanceShift, CColorDescriptor::ColorFormat format, int bpp)
+{
+	SurfaceDescriptor desc;
+	desc.m_colorDescriptor.m_redSize = redBits;
+	desc.m_colorDescriptor.m_greenSize = greenBits;
+	desc.m_colorDescriptor.m_blueSize = blueBits;
+	desc.m_colorDescriptor.m_alphaSize = alphaBits;
+	desc.m_colorDescriptor.m_luminanceSize = luminanceBits;
+	desc.m_redShift = redShift;
+	desc.m_greenShift = greenShift;
+	desc.m_blueShift = blueShift;
+	desc.m_alphaShift = alphaShift;
+	desc.m_luminanceShift = luminanceShift;
+	desc.m_colorDescriptor.m_format = format;
+	desc.m_colorDescriptor.m_bpp = bpp;
+	return desc;
+}
+
+typedef struct
+{
+	SurfaceDescriptor desc;
+	GLenum internal_format;
+	GLenum data_format;
+	GLenum data_type;
+} DescToEnumMapping;
+
+static bool dglIsDescEqualToMapping(const SurfaceDescriptor& desc, const DescToEnumMapping& mapping)
+{
+    if ((desc.m_colorDescriptor.m_redSize == mapping.desc.m_colorDescriptor.m_redSize) &&
+		(desc.m_colorDescriptor.m_greenSize == mapping.desc.m_colorDescriptor.m_greenSize) &&
+        (desc.m_colorDescriptor.m_blueSize == mapping.desc.m_colorDescriptor.m_blueSize) &&
+		(desc.m_colorDescriptor.m_alphaSize == mapping.desc.m_colorDescriptor.m_alphaSize) &&
+		(desc.m_colorDescriptor.m_luminanceSize == mapping.desc.m_colorDescriptor.m_luminanceSize) &&
+        (desc.m_redShift == mapping.desc.m_redShift) &&
+        (desc.m_greenShift == mapping.desc.m_greenShift) &&
+        (desc.m_blueShift == mapping.desc.m_blueShift) &&
+        (desc.m_alphaShift == mapping.desc.m_alphaShift) &&
+        (desc.m_luminanceShift == mapping.desc.m_luminanceShift) &&
+        (desc.m_colorDescriptor.m_format == mapping.desc.m_colorDescriptor.m_format) &&
+		(desc.m_colorDescriptor.m_bpp == mapping.desc.m_colorDescriptor.m_bpp))
+        return true;
+
+    return false;
+}
+
+static void dglSurfaceDescriptorToGLEnums(const SurfaceDescriptor& desc, GLenum& internal_format, GLenum& data_format, GLenum& data_type)
+{
+	static const DescToEnumMapping map[] = {
+		/* RGB{A,X} channel ordering */
+		 // sRGBX_8888
+		{dglCreateSurfaceDescriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8, GL_RGBA, GL_UNSIGNED_BYTE},
+		 // sRGBA_8888
+		{dglCreateSurfaceDescriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // sRGBA_8888_PRE
+        {dglCreateSurfaceDescriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, CColorDescriptor::sRGBA_PRE, 32), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // sRGB_565
+        {dglCreateSurfaceDescriptor(5, 11, 6, 5, 5, 0, 0, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8, GL_RGB, GL_UNSIGNED_SHORT_5_6_5},
+         // sRGBA_5551
+        {dglCreateSurfaceDescriptor(5, 11, 5, 6, 5, 1, 1, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1},
+         // sRGBA_4444
+        {dglCreateSurfaceDescriptor(4, 12, 4, 8, 4, 4, 4, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4},
+         // sL_8
+        {dglCreateSurfaceDescriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, CColorDescriptor::sLA, 8), GL_SLUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE},
+         // lRGBX_8888
+        {dglCreateSurfaceDescriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGB8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // lRGBA_8888
+        {dglCreateSurfaceDescriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // lRGBA_8888_PRE
+        {dglCreateSurfaceDescriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, CColorDescriptor::lRGBA_PRE, 32), GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE},
+         // lL_8
+        {dglCreateSurfaceDescriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, CColorDescriptor::lLA, 8), GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE},
+         // A_8
+        {dglCreateSurfaceDescriptor(0, 0, 0, 0, 0, 0, 8, 0, 0, 0, CColorDescriptor::lRGBA, 8), GL_ALPHA8, GL_ALPHA, GL_UNSIGNED_BYTE},
+		// These should be converted to a compatible format by VG.
+		/*
+         // BW_1
+        {dglCreateSurfaceDescriptor(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, CColorDescriptor::lLA, 1), GL_NONE, GL_NONE, GL_NONE},
+         // A_1
+        {dglCreateSurfaceDescriptor(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, CColorDescriptor::lRGBA, 1), GL_NONE, GL_NONE, GL_NONE},
+         // A_4
+        {dglCreateSurfaceDescriptor(0, 0, 0, 0, 0, 0, 4, 0, 0, 0, CColorDescriptor::lRGBA, 4), GL_NONE, GL_NONE, GL_NONE},
+		*/
+
+		/* {A,X}RGB channel ordering */
+         // sXRGB_8888
+        {dglCreateSurfaceDescriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sARGB_8888
+        {dglCreateSurfaceDescriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sARGB_8888_PRE
+        {dglCreateSurfaceDescriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, CColorDescriptor::sRGBA_PRE, 32), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sARGB_1555
+        {dglCreateSurfaceDescriptor(5, 10, 5, 5, 5, 0, 1, 15, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV},
+         // sARGB_4444
+        {dglCreateSurfaceDescriptor(4, 8, 4, 4, 4, 0, 4, 12, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV},
+         // lXRGB_8888
+        {dglCreateSurfaceDescriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGB8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // lARGB_8888
+        {dglCreateSurfaceDescriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // lARGB_8888_PRE
+        {dglCreateSurfaceDescriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, CColorDescriptor::lRGBA_PRE, 32), GL_RGBA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV},
+
+		/* BGR{A,X} channel ordering */
+         // sBGRX_8888
+		{dglCreateSurfaceDescriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // sBGRA_8888
+        {dglCreateSurfaceDescriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // sBGRA_8888_PRE
+        {dglCreateSurfaceDescriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, CColorDescriptor::sRGBA_PRE, 32), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // sBGR_565
+        {dglCreateSurfaceDescriptor(5, 0, 6, 5, 5, 11, 0, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8, GL_BGR, GL_UNSIGNED_SHORT_5_6_5},
+         // sBGRA_5551
+        {dglCreateSurfaceDescriptor(5, 1, 5, 6, 5, 11, 1, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_SHORT_5_5_5_1},
+         // sBGRA_4444
+        {dglCreateSurfaceDescriptor(4, 4, 4, 8, 4, 12, 4, 0, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4},
+         // lBGRX_8888
+        {dglCreateSurfaceDescriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGB8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // lBGRA_8888
+        {dglCreateSurfaceDescriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE},
+         // lBGRA_8888_PRE
+        {dglCreateSurfaceDescriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, CColorDescriptor::lRGBA_PRE, 32), GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE},
+
+		/* {A,X}BGR channel ordering */
+         // sXBGR_8888
+        {dglCreateSurfaceDescriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sABGR_8888
+        {dglCreateSurfaceDescriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, CColorDescriptor::sRGBA, 32), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sABGR_8888_PRE
+        {dglCreateSurfaceDescriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, CColorDescriptor::sRGBA_PRE, 32), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // sABGR_1555
+        {dglCreateSurfaceDescriptor(5, 0, 5, 5, 5, 10, 1, 15, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV},
+         // sABGR_4444
+		{dglCreateSurfaceDescriptor(4, 0, 4, 4, 4, 8, 4, 12, 0, 0, CColorDescriptor::sRGBA, 16), GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV},
+         // lXBGR_8888
+        {dglCreateSurfaceDescriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGB8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+         // lABGR_8888
+        {dglCreateSurfaceDescriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, CColorDescriptor::lRGBA, 32), GL_RGBA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV},
+		 // lABGR_8888_PRE:
+		{dglCreateSurfaceDescriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, CColorDescriptor::lRGBA_PRE, 32), GL_RGBA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV}};
+
+    for (size_t i = 0; i < sizeof(map)/sizeof(map[0]); i++)
+    {
+        if (dglIsDescEqualToMapping(desc, map[i]))
+		{
+			internal_format = map[i].internal_format;
+			data_format = map[i].data_format;
+			data_type = map[i].data_type;
+			DGLES2_ASSERT(internal_format != GL_NONE && data_format != GL_NONE && data_type != GL_NONE);
+			return;
+		}
+    }
+    DGLES2_ASSERT(GL_FALSE);
+    return;
+}
+
+void deglGetImageInfo(GLeglImageOES image, GLenum* internal_format, GLsizei* width, GLsizei* height, GLsizei* stride, GLenum* data_format, GLenum* data_type)
+{
+	DGLES2_ASSERT(image != NULL);
+	DGLES2_ASSERT(internal_format != NULL);
+	DGLES2_ASSERT(width != NULL);
+	DGLES2_ASSERT(height != NULL);
+	DGLES2_ASSERT(stride != NULL);
+	DGLES2_ASSERT(data_format != NULL);
+	DGLES2_ASSERT(data_type != NULL);
+
+	SurfaceDescriptor desc;
+	EGLtoGLES2Interface::GetEGLInterface()->GetDescForImage(image, desc);
+
+	*width = desc.m_width;
+	*height = desc.m_height;
+	*stride = desc.m_stride;
+	dglSurfaceDescriptorToGLEnums(desc, *internal_format, *data_format, *data_type);
+}
+
+void* deglGetImageData(GLeglImageOES image)
+{
+	DGLES2_ASSERT(image != NULL);
+	return EGLtoGLES2Interface::GetEGLInterface()->GetDataForImage(image);
+}
+
+namespace
+{
+EGLtoGLES2Interface g_EGLtoGLES2Interface;
+}
+
+IEGLtoGLES2Interface* getGLES2Interface(void)
+{
+	return &g_EGLtoGLES2Interface;
+}
+
+#include <new>
+
+EGLtoGLES2Interface::EGLtoGLES2Interface() :
+    m_egl(NULL)
+{
+}
+
+void EGLtoGLES2Interface::SetEGLInterface( IGLEStoEGLInterface* egl )
+{
+    DGLES2_ASSERT(!m_egl);
+    m_egl = egl;
+}
+
+void* EGLtoGLES2Interface::CreateContext(void* nativeContext)
+{
+	DGLContext* newContext = NULL;
+
+	newContext = DGLContext_create(nativeContext);
+	if(newContext == NULL)
+	{
+		return NULL;
+    }
+	m_contexts.insert(newContext);
+    return newContext;
+}
+
+bool EGLtoGLES2Interface::ReleaseContext(void* context)
+{
+	DGLES2_ASSERT(context != NULL);
+	DGLContext* ctx = static_cast<DGLContext*>(context);
+	if(m_contexts.find(ctx) == m_contexts.end())
+	{
+		return false;
+	}
+
+	DGLContext_destroy(ctx);
+	m_contexts.erase(ctx);
+	
+	return true;
+}
+
+void* EGLtoGLES2Interface::GetNativeContext(void* context)
+{
+	DGLES2_ASSERT(context != NULL);
+	DGLContext* ctx = static_cast<DGLContext*>(context);
+	if(m_contexts.find(ctx) == m_contexts.end())
+	{
+		return false;
+	}
+	
+	return ctx->native_context;
+}
+
+extern "C"
+{
+GL_APICALL void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image);
+GL_APICALL void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image);
+}
+
+fpGLProc EGLtoGLES2Interface::GetGLProcAddress(const char *procname)
+{
+	if(strcmp(procname, "glEGLImageTargetTexture2DOES") == 0)
+	{
+		return (fpGLProc)glEGLImageTargetTexture2DOES;
+	}
+	else if(strcmp(procname, "glEGLImageTargetRenderbufferStorageOES") == 0)
+	{
+		return (fpGLProc)glEGLImageTargetRenderbufferStorageOES;
+	}
+	else
+	{
+		return NULL;
+	}
+}
+
+int EGLtoGLES2Interface::BindTexImage( void* surface, int level, bool generate_mipmap, const SurfaceDescriptor* desc, void* buffer )
+{
+	DGLES2_ENTER_RET(NULL);
+
+	GLuint ret = 0;
+
+	// Store the current error and clear the error flag.
+	DGLContext_getHostError(ctx);
+
+	if(level < 0)
+	{
+		level = 0;
+	}
+	else if(level > ctx->max_texture_level)
+	{
+		level = ctx->max_texture_level;
+	}
+
+	// Clear all mipmap levels.
+	{
+		int i;
+		for(i = 0; i < ctx->max_texture_level; i++)
+		{
+			ctx->hgl.TexImage2D(GL_TEXTURE_2D, level, GL_RGBA, 0, 0, 0,
+				GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+		}
+	}
+
+	{
+		GLenum internal_format, data_format, data_type;
+		dglSurfaceDescriptorToGLEnums(*desc, internal_format, data_format, data_type);
+		ctx->hgl.TexImage2D(GL_TEXTURE_2D, level, internal_format, desc->m_width, desc->m_height, 0,
+			data_format, data_type, buffer);
+	}
+
+	if(generate_mipmap && level == 0)
+	{
+		ctx->hgl.GenerateMipmapEXT(GL_TEXTURE_2D);
+	}
+
+	// Clear any possible error flag.
+	if(ctx->hgl.GetError() == GL_NO_ERROR)
+	{
+		DGLTexture* texture;
+		GLeglImageOES image;
+		
+		texture = DGLContext_findTexture(ctx, ctx->texture_binding_2d);
+		DGLES2_ASSERT(texture != NULL);
+		DGLTexture_setLevel(texture, GL_TEXTURE_2D, level, GL_RGBA, desc->m_width, desc->m_height);
+
+		if(generate_mipmap && level == 0)
+		{
+			DGLTexture_generateMipmap(texture);
+		}
+
+		image = DGLTexture_getEGLImage(texture, GL_TEXTURE_2D);
+		if(image != NULL)
+		{
+			// Texture is respecified. It is no longer an EGLImage sibling.
+			deglUnregisterImageTarget(image, GL_TEXTURE_2D, texture->obj.name);
+			DGLTexture_setEGLImage(texture, GL_TEXTURE_2D, NULL);
+		}
+
+		{
+			DGLTextureLevel* level_obj = DGLTexture_getLevel(texture, GL_TEXTURE_2D, level);
+			if(level_obj->bound_surface != NULL)
+			{
+				// Texture is respecified. Release the bound EGLSurface.
+				deglReleaseTexImage(level_obj->bound_surface, texture->obj.name, level);
+			}
+			level_obj->bound_surface = surface;
+		}
+
+		ret = texture->obj.name;
+	}
+
+	DGLES2_LEAVE_NO_ERROR_CHECK_RET(ret);
+}
+
+bool EGLtoGLES2Interface::ReleaseTexImage( int name, int level )
+{
+	DGLES2_ENTER_RET(false);
+
+	DGLContext_getHostError(ctx);
+		
+	GLuint binding;
+	ctx->hgl.GetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&binding);
+	ctx->hgl.BindTexture(GL_TEXTURE_2D, (GLuint)name);
+	ctx->hgl.TexImage2D(GL_TEXTURE_2D, level, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+	ctx->hgl.BindTexture(GL_TEXTURE_2D, binding);
+
+	bool ret = false;
+
+	if(ctx->hgl.GetError() == GL_NO_ERROR)
+	{
+		DGLTexture* texture;
+		DGLTextureLevel* level_obj;
+
+		texture = DGLContext_findTexture(ctx, name);
+		level_obj = DGLTexture_getLevel(texture, GL_TEXTURE_2D, level);
+		level_obj->bound_surface = NULL;
+
+		ret = true;
+	}
+
+	DGLES2_LEAVE_NO_ERROR_CHECK_RET(ret);
+}
+
+static GLenum dglImageTargetToGLenum(EImageTarget target)
+{
+	switch(target)
+	{
+		case IMAGE_TARGET_TEXTURE_2D:
+			return GL_TEXTURE_2D;
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_X:
+			return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_X:
+			return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Y:
+			return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+			return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Z:
+			return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Z:
+			return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
+		default:
+			DGLES2_ASSERT(false);
+	}
+
+	// Not reached.
+	return -1;
+}
+
+static bool dglPrepareState(DGLContext& ctx, GLuint name, EImageTarget target, GLint level, GLenum& query_target, GLenum& bind_target, GLint& binding)
+{
+	if(name == 0)
+	{
+		return false;
+	}
+	
+	// Store the current error and clear the error flag.
+	DGLContext_getHostError(&ctx);
+
+	query_target = dglImageTargetToGLenum(target);
+	switch(query_target)
+	{
+		case GL_TEXTURE_2D:
+			bind_target = GL_TEXTURE_2D;
+			ctx.hgl.GetIntegerv(GL_TEXTURE_BINDING_2D, &binding);
+			break;
+
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
+			bind_target = GL_TEXTURE_CUBE_MAP;
+			ctx.hgl.GetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &binding);
+			break;
+	}
+
+	const DGLTexture* texture = DGLContext_findTexture(&ctx, name);
+	if(texture == NULL)
+	{
+		return false;
+	}
+
+	if(!DGLTexture_isComplete(texture))
+	{
+		if(level != 0)
+		{
+			return false;
+		}
+		else
+		{
+			if(!DGLTexture_hasLevelZero(texture))
+			{
+				return false;
+			}
+
+			if(DGLTexture_hasLevelsOtherThanZero(texture))
+			{
+				return false;
+			}
+		}
+	}
+
+	ctx.hgl.BindTexture(bind_target, name);
+	// Clear any possible error flag.
+	if(ctx.hgl.GetError() == GL_INVALID_OPERATION)
+	{
+		// Texture was not created with the requested target.
+		return false;
+	}
+
+	return true;
+}
+
+static void dglResetState(DGLContext& ctx, GLenum target, GLint binding)
+{
+	// Reset state.
+	ctx.hgl.BindTexture(target, binding);
+
+	DGLES2_ASSERT(ctx.hgl.GetError() == GL_NO_ERROR);
+}
+
+EStatus EGLtoGLES2Interface::GetTextureInfo(void* context, EImageTarget target, void* texture, GLint texture_level, SurfaceDescriptor& surfDesc)
+{
+	DGLES2_ASSERT(context != NULL);
+
+	DGLContext* ctx = (DGLContext*)context;
+	GLuint name = (GLuint)texture;
+
+	dglGetLock();
+
+	GLenum query_target;
+	GLenum bind_target;
+	GLint binding;
+	if(!dglPrepareState(*ctx, name, target, texture_level, query_target, bind_target, binding))
+	{
+		dglReleaseLock();
+		return DGLES2_BAD_PARAMETER;
+	}
+
+	CColorDescriptor& colDesc = surfDesc.m_colorDescriptor;
+	GLenum format;
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_WIDTH, &surfDesc.m_width);
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_HEIGHT, &surfDesc.m_height);
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_RED_SIZE, &colDesc.m_redSize);
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_GREEN_SIZE, &colDesc.m_greenSize);
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_BLUE_SIZE, &colDesc.m_blueSize);
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_ALPHA_SIZE, &colDesc.m_alphaSize);
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_LUMINANCE_SIZE, &colDesc.m_luminanceSize);
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_INTERNAL_FORMAT, (GLint*)&format);
+	if(format == GL_RGB || format == GL_RGB8)
+	{
+		// Convert RGB888 to RGBA8888 to make VG interop easier.
+		format = GL_RGBA;
+	}
+	if(ctx->hgl.GetError() == GL_INVALID_VALUE)
+	{
+		// Invalid level.
+		dglReleaseLock();
+		return DGLES2_BAD_MATCH;
+	}
+
+	surfDesc.m_redShift = 0;
+	surfDesc.m_greenShift = 0;
+	surfDesc.m_blueShift = 0;
+	surfDesc.m_luminanceShift = 0;
+	surfDesc.m_alphaShift = 0;
+	int bpp = 0;
+	switch(format)
+	{
+#ifndef DGLES2_NO_SRGB
+		case GL_SRGB8:
+			surfDesc.m_redShift = 16;
+			surfDesc.m_greenShift = 8;
+			surfDesc.m_blueShift = 0;
+			colDesc.m_format = CColorDescriptor::sRGBA;
+			colDesc.m_bpp = 24;
+			break;
+
+		case GL_SRGB8_ALPHA8:
+			surfDesc.m_redShift = 24;
+			surfDesc.m_greenShift = 16;
+			surfDesc.m_blueShift = 8;
+			surfDesc.m_alphaShift = 0;
+			colDesc.m_format = CColorDescriptor::sRGBA;
+			colDesc.m_bpp = 32;
+			break;
+
+		case GL_SLUMINANCE8:
+			surfDesc.m_luminanceShift = 0;
+			colDesc.m_format = CColorDescriptor::sLA;
+			colDesc.m_bpp = 8;
+			break;
+#endif
+
+		case GL_RGB:
+		case GL_RGB8:
+			surfDesc.m_redShift = 16;
+			surfDesc.m_greenShift = 8;
+			surfDesc.m_blueShift = 0;
+			colDesc.m_format = CColorDescriptor::lRGBA;
+			colDesc.m_bpp = 24;
+			break;
+
+		case GL_RGBA:
+		case GL_RGBA8:
+			surfDesc.m_redShift = 24;
+			surfDesc.m_greenShift = 16;
+			surfDesc.m_blueShift = 8;
+			surfDesc.m_alphaShift = 0;
+			colDesc.m_format = CColorDescriptor::lRGBA;
+			colDesc.m_bpp = 32;
+			break;
+
+		case GL_LUMINANCE_ALPHA:
+			surfDesc.m_luminanceShift = 8;
+			surfDesc.m_alphaShift = 0;
+			colDesc.m_format = CColorDescriptor::lLA;
+			colDesc.m_bpp = 16;
+			break;
+
+		case GL_ALPHA:
+		case GL_ALPHA8:
+			surfDesc.m_alphaShift = 0;
+			colDesc.m_format = CColorDescriptor::lRGBA;
+			colDesc.m_bpp = 8;
+			break;
+
+		case GL_LUMINANCE:
+		case GL_LUMINANCE8:
+			surfDesc.m_luminanceShift = 0;
+			colDesc.m_format = CColorDescriptor::lLA;
+			colDesc.m_bpp = 8;
+			break;
+			
+		default:
+			DGLES2_ASSERT(GL_FALSE);
+	}
+
+	surfDesc.m_stride = colDesc.m_bpp / 8 * surfDesc.m_width;
+
+	dglResetState(*ctx, bind_target, binding);
+	dglReleaseLock();
+	return DGLES2_SUCCESS;
+}
+
+EStatus EGLtoGLES2Interface::GetTextureData( void* context, EImageTarget target, void* texture, EGLint texture_level, void* data )
+{
+	DGLES2_ASSERT(context != NULL);
+
+	DGLContext* ctx = (DGLContext*)context;
+	GLuint name = (GLuint)texture;
+
+	dglGetLock();
+
+	GLenum query_target;
+	GLenum bind_target;
+	GLint binding;
+	if(!dglPrepareState(*ctx, name, target, texture_level, query_target, bind_target, binding))
+	{
+		dglReleaseLock();
+		return DGLES2_BAD_PARAMETER;
+	}
+
+	GLenum format;
+	GLint pack_alignment;
+	ctx->hgl.GetTexLevelParameteriv(query_target, texture_level, GL_TEXTURE_INTERNAL_FORMAT, (GLint*)&format);
+	if(format == GL_RGB || format == GL_RGB8)
+	{
+		// Convert RGB888 to RGBA8888 to make VG interop easier.
+		format = GL_RGBA;
+	}
+	ctx->hgl.GetIntegerv(GL_PACK_ALIGNMENT, &pack_alignment);
+	ctx->hgl.PixelStorei(GL_PACK_ALIGNMENT, 1);
+	ctx->hgl.GetTexImage(query_target, texture_level, format, GL_UNSIGNED_BYTE, data);
+	ctx->hgl.PixelStorei(GL_PACK_ALIGNMENT, pack_alignment);
+
+	if(ctx->hgl.GetError() == GL_INVALID_VALUE)
+	{
+		// Invalid level.
+		dglReleaseLock();
+		return DGLES2_BAD_MATCH;
+	}
+
+	dglResetState(*ctx, bind_target, binding);
+	dglReleaseLock();
+	return DGLES2_SUCCESS;
+}
+
+bool EGLtoGLES2Interface::CopyBuffers( void* buf, const SurfaceDescriptor* desc )
+{
+	DGLES2_ENTER_RET(false);
+
+	// Store the current error and clear the error flag.
+	DGLContext_getHostError(ctx);
+
+	{
+		GLint framebuffer_binding;
+		GLint pack_alignment;
+		GLenum internal_format, data_format, data_type;
+
+		ctx->hgl.GetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer_binding);
+		ctx->hgl.GetIntegerv(GL_PACK_ALIGNMENT, &pack_alignment);
+
+		dglSurfaceDescriptorToGLEnums(*desc, internal_format, data_format, data_type);
+
+		ctx->hgl.BindFramebufferEXT(GL_FRAMEBUFFER, 0);
+		ctx->hgl.PixelStorei(GL_PACK_ALIGNMENT, 1);
+		ctx->hgl.ReadPixels(0, 0, desc->m_width, desc->m_height, data_format, data_type, buf);
+
+		// Restore state.
+		ctx->hgl.PixelStorei(GL_PACK_ALIGNMENT, pack_alignment);
+		ctx->hgl.BindFramebufferEXT(GL_FRAMEBUFFER, framebuffer_binding);
+	}
+
+	DGLES2_LEAVE_NO_ERROR_CHECK_RET(ctx->hgl.GetError() == GL_NO_ERROR);
+}
+
+bool EGLtoGLES2Interface::UpdateBuffers( void* buf, const SurfaceDescriptor* desc )
+{
+	DGLES2_ENTER_RET(false);
+
+	// Store the current error and clear the error flag.
+	DGLContext_getHostError(ctx);
+
+	{
+		GLint framebuffer_binding;
+		GLint unpack_alignment;
+		GLenum internal_format, data_format, data_type;
+
+		ctx->hgl.GetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer_binding);
+		ctx->hgl.GetIntegerv(GL_UNPACK_ALIGNMENT, &unpack_alignment);
+
+		dglSurfaceDescriptorToGLEnums(*desc, internal_format, data_format, data_type);
+
+		ctx->hgl.BindFramebufferEXT(GL_FRAMEBUFFER, 0);
+		ctx->hgl.PixelStorei(GL_UNPACK_ALIGNMENT, 1);
+		ctx->hgl.DrawPixels( desc->m_width, desc->m_height, data_format, data_type, buf );
+		
+		// Restore state.
+		ctx->hgl.PixelStorei(GL_UNPACK_ALIGNMENT, unpack_alignment);
+		ctx->hgl.BindFramebufferEXT(GL_FRAMEBUFFER, framebuffer_binding);
+	}
+
+	DGLES2_LEAVE_NO_ERROR_CHECK_RET(ctx->hgl.GetError() == GL_NO_ERROR);
+}
+
+bool EGLtoGLES2Interface::UpdateImageSibling( EImageTarget imageTarget, void* name )
+{
+	DGLES2_ENTER_RET(false);
+	DGLContext_getHostError(ctx);
+	{
+		bool success = true;
+		bool cubeMap = false;
+
+		switch(imageTarget)
+		{
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_X:
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_X:
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Y:
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Z:
+		case IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Z:
+			cubeMap = true;
+			// fall through
+
+		case IMAGE_TARGET_TEXTURE_2D:
+			{
+				DGLTexture* texture;
+				GLenum textureTarget;
+				GLeglImageOES image;
+				GLint binding;
+
+				texture = DGLContext_findTexture(ctx, (GLuint)name);
+				if(texture == NULL)
+				{
+					success = false;
+					break;
+				}
+
+				textureTarget = dglImageTargetToGLenum(imageTarget);
+				image = DGLTexture_getEGLImage(texture, textureTarget);
+				if(image == NULL)
+				{
+					success = false;
+					break;
+				}
+
+				ctx->hgl.GetIntegerv(cubeMap ? GL_TEXTURE_BINDING_CUBE_MAP : GL_TEXTURE_BINDING_2D, &binding);
+				ctx->hgl.BindTexture(cubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, texture->obj.name);
+				success = !!DGLContext_specifyTextureFromEGLImage(ctx, image, textureTarget);
+
+				// Reset state.
+				ctx->hgl.BindTexture(cubeMap ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D, binding);
+
+				if(!success)
+				{
+					success = false;
+					break;
+				}
+
+				break;
+			}
+
+		case IMAGE_TARGET_RENDERBUFFER:
+			{
+				DGLRenderbuffer* buffer;
+				GLint binding;
+
+				buffer = DGLContext_findRenderbuffer(ctx, (GLuint)name);
+				if(buffer == NULL)
+				{
+					success = false;
+					break;
+				}
+
+				if(buffer->egl_image == NULL)
+				{
+					success = false;
+					break;
+				}
+				
+				ctx->hgl.GetIntegerv(GL_RENDERBUFFER_BINDING, &binding);
+				ctx->hgl.BindRenderbufferEXT(GL_RENDERBUFFER, buffer->obj.name);
+				success = !!DGLContext_specifyRenderbufferFromEGLImage(ctx, buffer->egl_image);
+
+				// Reset state.
+				ctx->hgl.BindRenderbufferEXT(GL_RENDERBUFFER, binding);
+
+				if(!success)
+				{
+					success = false;
+					break;
+				}
+
+				break;
+			}
+
+		default:
+			DGLES2_ASSERT(false);
+			success = false;
+			break;
+		}
+	
+		if(ctx->hgl.GetError() != GL_NO_ERROR)
+		{
+			success = false;
+		}
+		
+		DGLES2_LEAVE_NO_ERROR_CHECK_RET(success);
+	}
+}
+
+void EGLtoGLES2Interface::Flush()
+{
+	DGLES2_ENTER();
+	ctx->hgl.Flush();
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+void EGLtoGLES2Interface::Finish()
+{
+	DGLES2_ENTER();
+	ctx->hgl.Finish();
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+/*static*/ IGLEStoEGLInterface* EGLtoGLES2Interface::GetEGLInterface()
+{
+    return g_EGLtoGLES2Interface.m_egl;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/degl.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,91 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef DEGL_H_
+#define DEGL_H_
+
+#include "common.h"
+
+#ifdef __cplusplus
+
+#include "GLES2Interface.h"
+
+#include <set>
+
+extern "C"
+{
+#endif /* __cplusplus */
+
+struct DGLContext;
+
+void* deglGetHostProcAddress(char const* proc);
+struct DGLContext* deglGetCurrentContext(void);
+int deglLockSurface(int read, int draw);
+int deglUnlockSurface(void);
+void deglGetImageInfo(GLeglImageOES image, GLenum* internalformat, GLsizei* width, GLsizei* height, GLsizei* stride, GLenum* dataformat, GLenum* datatype);
+void* deglGetImageData(GLeglImageOES image);
+void deglRegisterImageTarget(GLeglImageOES image, GLenum target, GLuint name);
+void deglUnregisterImageTarget(GLeglImageOES image, GLenum target, GLuint name);
+void deglUpdateImageSiblings(GLeglImageOES image, GLenum target, GLuint name);
+void deglReleaseTexImage(void* surface, int name, int level);
+
+#ifdef __cplusplus
+DGLES2_EXPORT IEGLtoGLES2Interface* getGLES2Interface(void);
+}
+
+class EGLtoGLES2Interface : public IEGLtoGLES2Interface
+{
+public:
+    EGLtoGLES2Interface();
+
+	void SetEGLInterface( IGLEStoEGLInterface* );
+	void* CreateContext( void* nativeContext );
+	bool ReleaseContext( void* context );
+	void* GetNativeContext( void* context );
+	fpGLProc GetGLProcAddress( const char *procname );
+	int BindTexImage( void* surface, int level, bool generateMipmap, const SurfaceDescriptor* desc, void* buffer );
+	bool ReleaseTexImage( int name, int level );
+    EStatus GetTextureInfo( void* context, EImageTarget target, void* texture, GLint textureLevel, SurfaceDescriptor& desc );
+    EStatus GetTextureData( void* context, EImageTarget target, void* texture, GLint textureLevel, void* data );
+    bool CopyBuffers( void* buf, const SurfaceDescriptor* desc );
+    bool UpdateBuffers( void* buf, const SurfaceDescriptor* desc );
+	bool UpdateImageSibling( EImageTarget target, void* name );
+    void Flush();
+    void Finish();
+
+	// Methods for local OpenGL ES -implementation. To be called only from OpenGL ES internals.
+    static IGLEStoEGLInterface* GetEGLInterface();
+
+private:
+    IGLEStoEGLInterface* m_egl;
+	std::set<DGLContext*> m_contexts;
+};
+
+#endif /* __cplusplus */
+
+#endif /* DEGL_H */
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/depth.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,60 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+GL_APICALL_BUILD void GL_APIENTRY glDepthFunc(GLenum func)
+{
+	DGLES2_ENTER();
+	ctx->hgl.DepthFunc(func);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDepthMask(GLboolean flag)
+{
+	DGLES2_ENTER();
+	ctx->hgl.DepthMask(flag);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDepthRangef(GLclampf zNear, GLclampf zFar)
+{
+	DGLES2_ENTER();
+	ctx->hgl.DepthRange(zNear, zFar);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glClearDepthf(GLclampf depth)
+{
+	DGLES2_ENTER();
+	ctx->hgl.ClearDepth(depth);
+	DGLES2_LEAVE();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/draw.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,158 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+static GLboolean dglIsValidCapability(GLenum cap)
+{
+	switch(cap)
+	{
+		case GL_TEXTURE_2D:
+		case GL_CULL_FACE:
+		case GL_POLYGON_OFFSET_FILL:
+		case GL_SAMPLE_ALPHA_TO_COVERAGE:
+		case GL_SAMPLE_COVERAGE:
+		case GL_SCISSOR_TEST:
+		case GL_STENCIL_TEST:
+		case GL_DEPTH_TEST:
+		case GL_BLEND:
+		case GL_DITHER:
+			return GL_TRUE;
+
+		default:
+			return GL_FALSE;
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
+{
+	DGLES2_ENTER();
+	ctx->hgl.ColorMask(red, green, blue, alpha);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glCullFace(GLenum mode)
+{
+	DGLES2_ENTER();
+	ctx->hgl.CullFace(mode);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDisable(GLenum cap)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValidCapability(cap), GL_INVALID_ENUM);
+	ctx->hgl.Disable(cap);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glEnable(GLenum cap)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValidCapability(cap), GL_INVALID_ENUM);
+	ctx->hgl.Enable(cap);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glFinish(void)
+{
+	DGLES2_ENTER();
+	DGLES2_BEGIN_DRAWING();
+	ctx->hgl.Finish();
+	DGLES2_END_DRAWING();
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glFlush(void)
+{
+	DGLES2_ENTER();
+	DGLES2_BEGIN_DRAWING();
+	ctx->hgl.Flush();
+	DGLES2_END_DRAWING();
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glFrontFace(GLenum mode)
+{
+	DGLES2_ENTER();
+	ctx->hgl.FrontFace(mode);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD GLboolean GL_APIENTRY glIsEnabled(GLenum cap)
+{
+	DGLES2_ENTER_RET(GL_FALSE);
+	DGLES2_ERROR_IF_RET(!dglIsValidCapability(cap), GL_INVALID_ENUM, GL_FALSE);
+	DGLES2_LEAVE_RET(ctx->hgl.IsEnabled(cap));
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glHint(GLenum target, GLenum mode)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_GENERATE_MIPMAP_HINT, GL_INVALID_ENUM);
+	ctx->hgl.Hint(target, mode);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glLineWidth (GLfloat width)
+{
+	DGLES2_ENTER();
+	ctx->hgl.LineWidth(width);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glPolygonOffset(GLfloat factor, GLfloat units)
+{
+	DGLES2_ENTER();
+	ctx->hgl.PolygonOffset(factor, units);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glSampleCoverage(GLclampf value, GLboolean invert)
+{
+	DGLES2_ENTER();
+	ctx->hgl.SampleCoverage(value, invert);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glScissor(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Scissor(x, y, width, height);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glViewport(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Viewport(x, y, width, height);
+	DGLES2_LEAVE();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/fbo.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,264 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+DGLRenderbuffer* DGLRenderbuffer_create(GLuint name)
+{
+	DGLRenderbuffer* buffer = malloc(sizeof(DGLRenderbuffer));
+	if(buffer == NULL)
+	{
+		return NULL;
+	}
+
+	buffer->obj.name = name;
+	buffer->obj.next = NULL;
+
+	buffer->egl_image = NULL;
+
+	return buffer;
+}
+
+void DGLRenderbuffer_destroy(DGLRenderbuffer *buffer)
+{
+	DGLES2_ASSERT(buffer != NULL);
+	if(buffer->egl_image != NULL)
+	{
+		deglUnregisterImageTarget(buffer->egl_image, GL_RENDERBUFFER, buffer->obj.name);
+		buffer->egl_image = NULL;
+	}
+	free(buffer);
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBindFramebuffer(GLenum target, GLuint framebuffer)
+{
+	DGLES2_ENTER();
+	DGLContext_getHostError(ctx);
+	ctx->hgl.BindFramebufferEXT(target, framebuffer);
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		ctx->framebuffer_binding = framebuffer;
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBindRenderbuffer(GLenum target, GLuint renderbuffer)
+{
+	DGLES2_ENTER();
+	DGLContext_getHostError(ctx);
+	ctx->hgl.BindRenderbufferEXT(target, renderbuffer);
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		if(!DGLContext_bindRenderbuffer(ctx, renderbuffer))
+		{
+			DGLES2_ERROR(GL_OUT_OF_MEMORY);
+		}
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+GL_APICALL_BUILD GLenum GL_APIENTRY glCheckFramebufferStatus(GLenum target)
+{
+	DGLES2_ENTER_RET(GL_FALSE);
+	DGLES2_LEAVE_RET(ctx->hgl.CheckFramebufferStatusEXT(target));
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDeleteFramebuffers(GLsizei n, const GLuint* framebuffers)
+{
+	DGLES2_ENTER();
+	DGLContext_getHostError(ctx);
+	ctx->hgl.DeleteFramebuffersEXT(n, framebuffers);
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		// Unbind framebuffer when deleted.
+		int i;
+		for(i = 0; i < n; i++)
+		{
+			if(ctx->framebuffer_binding == framebuffers[i])
+			{
+				ctx->framebuffer_binding = 0;
+				break;
+			}
+		}
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers)
+{
+	DGLES2_ENTER();
+	DGLContext_getHostError(ctx);
+	ctx->hgl.DeleteRenderbuffersEXT(n, renderbuffers);
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		int i;
+		for(i = 0; i < n; i++)
+		{
+			DGLContext_destroyRenderbuffer(ctx, renderbuffers[n]);
+		}
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glFramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(attachment != GL_COLOR_ATTACHMENT0 &&
+					attachment != GL_DEPTH_ATTACHMENT &&
+					attachment != GL_STENCIL_ATTACHMENT,
+					GL_INVALID_ENUM);
+	ctx->hgl.FramebufferRenderbufferEXT(target, attachment, renderbuffertarget, renderbuffer);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(attachment != GL_COLOR_ATTACHMENT0 &&
+					attachment != GL_DEPTH_ATTACHMENT &&
+					attachment != GL_STENCIL_ATTACHMENT,
+					GL_INVALID_ENUM);
+	ctx->hgl.FramebufferTexture2DEXT(target, attachment, textarget, texture, level);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGenFramebuffers(GLsizei n, GLuint* framebuffers)
+{
+	DGLES2_ENTER();
+	ctx->hgl.GenFramebuffersEXT(n, framebuffers);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGenRenderbuffers(GLsizei n, GLuint* renderbuffers)
+{
+	DGLES2_ENTER();
+	ctx->hgl.GenRenderbuffersEXT(n, renderbuffers);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(attachment != GL_COLOR_ATTACHMENT0 &&
+					attachment != GL_DEPTH_ATTACHMENT &&
+					attachment != GL_STENCIL_ATTACHMENT,
+					GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(pname != GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE &&
+					pname != GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME &&
+					pname != GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL &&
+					pname != GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
+					GL_INVALID_ENUM);
+	ctx->hgl.GetFramebufferAttachmentParameterivEXT(target, attachment, pname, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params)
+{
+	DGLES2_ENTER();
+	ctx->hgl.GetRenderbufferParameterivEXT(target, pname, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD GLboolean GL_APIENTRY glIsFramebuffer(GLuint framebuffer)
+{
+	DGLES2_ENTER_RET(GL_FALSE);
+	ctx->hgl.IsFramebufferEXT(framebuffer);
+	DGLES2_LEAVE_RET(GL_FALSE);
+}
+
+GL_APICALL_BUILD GLboolean    GL_APIENTRY glIsRenderbuffer(GLuint renderbuffer)
+{
+	DGLES2_ENTER_RET(GL_FALSE);
+	ctx->hgl.IsRenderbufferEXT(renderbuffer);
+	DGLES2_LEAVE_RET(GL_FALSE);
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glRenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height)
+{
+	DGLES2_ENTER();
+	
+	switch(internalformat)
+	{
+		case GL_DEPTH_COMPONENT16:
+		case GL_RGBA4:
+		case GL_RGB5_A1:
+		case GL_STENCIL_INDEX8:
+			break;
+
+		case GL_RGB565:	// RGB565 is not supported in desktop GL.
+			internalformat = GL_RGB8;
+			break;
+
+		case GL_DEPTH_COMPONENT24_OES: // extension GL_OES_depth24
+			internalformat = GL_DEPTH_COMPONENT24;
+			break;
+
+		case GL_DEPTH_COMPONENT32_OES: // extension GL_OES_depth32
+			internalformat = GL_DEPTH_COMPONENT32;
+			break;
+
+		case GL_RGB8_OES: // extension GL_OES_rgb8_rgba8
+			internalformat = GL_RGB8;
+			break;
+
+		case GL_RGBA8_OES: // extension GL_OES_rgb8_rgba8
+			internalformat = GL_RGBA8;
+			break;
+	}
+	
+	DGLContext_getHostError(ctx);
+	ctx->hgl.RenderbufferStorageEXT(target, internalformat, width, height);
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		DGLRenderbuffer* buffer = DGLContext_findRenderbuffer(ctx, ctx->renderbuffer_binding);
+		DGLES2_ASSERT(buffer != NULL);
+		if(buffer->egl_image != NULL)
+		{
+			// Renderbuffer is respecified. It is no longer an EGLImage sibling.
+			deglUnregisterImageTarget(buffer->egl_image, GL_RENDERBUFFER, buffer->obj.name);
+			buffer->egl_image = NULL;
+		}
+	}
+
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES(GLenum target, GLeglImageOES image)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_RENDERBUFFER, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(image == NULL, GL_INVALID_OPERATION);
+	DGLContext_getHostError(ctx);
+	if(!DGLContext_specifyRenderbufferFromEGLImage(ctx, image))
+	{
+		DGLES2_ERROR(GL_INVALID_OPERATION);
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/fbo.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,42 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef FBO_H_
+#define FBO_H_
+
+typedef struct DGLRenderbuffer
+{
+	struct DGLObject obj;
+
+	GLeglImageOES egl_image; // EGLimage this renderbuffer is a sibling of.
+} DGLRenderbuffer;
+
+DGLRenderbuffer*	DGLRenderbuffer_create(GLuint name);
+void				DGLRenderbuffer_destroy(DGLRenderbuffer* buffer);
+
+#endif // FBO_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/get.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,257 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+#include "get.h"
+
+static GLboolean dglGet(const DGLContext* ctx, GLenum pname, DGLType dstType, void* params)
+{
+	int j;
+	DGLType srcType;
+	GLboolean b[1];
+	GLint i[11];
+
+	int n = 1;
+
+	switch(pname)
+	{
+		case GL_SHADER_COMPILER:
+			srcType = DGLES2_TYPE_BOOL;
+			b[0] = GL_TRUE;
+			break;
+
+		case GL_NUM_SHADER_BINARY_FORMATS:
+			srcType = DGLES2_TYPE_INT;
+			i[0] = 0;
+			break;
+
+		case GL_SHADER_BINARY_FORMATS:
+			// None.
+			return GL_TRUE;
+
+		case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
+			srcType = DGLES2_TYPE_INT;
+			i[0] = 11;
+			break;
+
+		case GL_COMPRESSED_TEXTURE_FORMATS:
+			srcType = DGLES2_TYPE_ENUM;
+			i[0] = GL_PALETTE4_RGB8_OES;
+			i[1] = GL_PALETTE4_RGBA8_OES;
+			i[2] = GL_PALETTE4_R5_G6_B5_OES;
+			i[3] = GL_PALETTE4_RGBA4_OES;
+			i[4] = GL_PALETTE4_RGB5_A1_OES;
+			i[5] = GL_PALETTE8_RGB8_OES;
+			i[6] = GL_PALETTE8_RGBA8_OES;
+			i[7] = GL_PALETTE8_R5_G6_B5_OES;
+			i[8] = GL_PALETTE8_RGBA4_OES;
+			i[9] = GL_PALETTE8_RGB5_A1_OES;
+			i[10] = GL_ETC1_RGB8_OES;
+			n = 11;
+			break;
+
+		case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
+			i[0] = GL_RGBA;
+			srcType = DGLES2_TYPE_ENUM;
+			break;
+
+		case GL_IMPLEMENTATION_COLOR_READ_TYPE:
+			i[0] = GL_UNSIGNED_BYTE;
+			srcType = DGLES2_TYPE_ENUM;
+			break;
+
+		case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
+			ctx->hgl.GetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, i);
+			i[0] /= 4;
+			srcType = DGLES2_TYPE_INT;
+			break;
+
+		case GL_MAX_VERTEX_UNIFORM_VECTORS:
+			ctx->hgl.GetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, i);
+			i[0] /= 4;
+			srcType = DGLES2_TYPE_INT;
+			break;
+
+		case GL_MAX_VARYING_VECTORS:
+			ctx->hgl.GetIntegerv(GL_MAX_VARYING_FLOATS, i);
+			i[0] /= 4;
+			srcType = DGLES2_TYPE_INT;
+			break;
+
+		default:
+			// Let the host GL handle this case.
+			return GL_FALSE;
+	}
+
+	// Type conversions.
+	for(j = 0; j < n; j++)
+	{
+		switch(dstType)
+		{
+			case DGLES2_TYPE_FLOAT:
+				switch(srcType)
+				{
+					case DGLES2_TYPE_BOOL:
+						((GLfloat*)params)[j] = b[j] ? 1.f : 0.f;
+						break;
+
+					case DGLES2_TYPE_INT:
+					case DGLES2_TYPE_ENUM:
+						((GLfloat*)params)[j] = (GLfloat)i[j];
+						break;
+
+					default:
+						DGLES2_ASSERT(GL_FALSE);
+				}
+				break;
+
+			case DGLES2_TYPE_BOOL:
+				switch(srcType)
+				{
+					case DGLES2_TYPE_BOOL:
+						((GLboolean*)params)[j] = b[j];
+						break;
+
+					case DGLES2_TYPE_INT:
+					case DGLES2_TYPE_ENUM:
+						((GLboolean*)params)[j] = i[j] ? GL_TRUE : GL_FALSE;
+						break;
+
+					default:
+						DGLES2_ASSERT(GL_FALSE);
+				}
+				break;
+
+			case DGLES2_TYPE_INT:
+				switch(srcType)
+				{
+					case DGLES2_TYPE_BOOL:
+						((GLint*)params)[j] = b[j] ? 1 : 0;
+						break;
+
+					case DGLES2_TYPE_INT:
+					case DGLES2_TYPE_ENUM:
+						((GLint*)params)[j] = i[j];
+						break;
+
+					default:
+						DGLES2_ASSERT(GL_FALSE);
+				}
+				break;
+
+			default:
+				DGLES2_ASSERT(GL_FALSE);
+		}
+	}
+
+	return GL_TRUE;
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetBooleanv(GLenum pname, GLboolean* params)
+{
+	DGLES2_ENTER();
+	if(!dglGet(ctx, pname, DGLES2_TYPE_BOOL, params))
+	{
+		ctx->hgl.GetBooleanv(pname, params);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD GLenum GL_APIENTRY glGetError(void)
+{
+	DGLES2_ENTER_RET(GL_NO_ERROR);
+	{
+		GLenum host_error = ctx->hgl.GetError();
+		GLenum wrapper_error = ctx->error;
+		ctx->error = GL_NO_ERROR;
+		DGLES2_LEAVE_RET(host_error != GL_NO_ERROR ? host_error : wrapper_error);
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetFloatv(GLenum pname, GLfloat* params)
+{
+	DGLES2_ENTER();
+	if(!dglGet(ctx, pname, DGLES2_TYPE_FLOAT, params))
+	{
+		ctx->hgl.GetFloatv(pname, params);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetIntegerv(GLenum pname, GLint* params)
+{
+	DGLES2_ENTER();
+	if(!dglGet(ctx, pname, DGLES2_TYPE_INT, params))
+	{
+		ctx->hgl.GetIntegerv(pname, params);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD const GLubyte* GL_APIENTRY glGetString(GLenum name)
+{
+	DGLES2_ENTER_RET(NULL);
+	{
+		static const GLubyte vendor[] = "Nokia";
+		static const GLubyte renderer[] = "OpenGL ES 2.0";
+		static const GLubyte version[] = "OpenGL ES 2.0";
+		static const GLubyte slversion[] = "OpenGL ES GLSL ES 1.0";
+		static const GLubyte extensions[] = "GL_OES_depth24 GL_OES_depth32 GL_OES_rgb8_rgba8 "
+											"GL_OES_vertex_half_float GL_OES_texture_half_float "
+											"GL_OES_texture_half_float_linear GL_OES_texture_npot "
+											"GL_OES_compressed_paletted_texture "
+											"GL_OES_compressed_ETC1_RGB8_texture "
+											"GL_OES_EGL_image";
+		const GLubyte* str = NULL;
+		switch(name)
+		{
+		case GL_VENDOR:
+			str = vendor;
+			break;
+		case GL_RENDERER:
+			str = renderer;
+			break;
+		case GL_VERSION:
+			str = version;
+			break;
+		case GL_SHADING_LANGUAGE_VERSION:
+			str = slversion;
+			break;
+		case GL_EXTENSIONS:
+			str = extensions;
+			break;
+		default:
+			DGLES2_ERROR_RET(GL_INVALID_ENUM, NULL);
+			break;
+		}
+		DGLES2_LEAVE_RET(str);
+	}
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/get.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,40 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef GET_H_
+#define GET_H_
+
+typedef enum DGLType
+{
+	DGLES2_TYPE_FLOAT,
+	DGLES2_TYPE_INT,
+	DGLES2_TYPE_ENUM,
+	DGLES2_TYPE_BOOL
+} DGLType;
+
+#endif /* GET_H_ */
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/half.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,57 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "half.h"
+
+GLfloat dglConvertHalfToFloat(khronos_int16_t half)
+{
+	// INF and NaN are mapped to floating point values.
+
+	khronos_int32_t exponent = half & 0x7c00;
+	khronos_int16_t mantissa = half & 0x03ff;
+	if(!exponent)
+	{
+		if(mantissa)
+		{
+			// Subnormals are mapped to zero.
+			mantissa = 0;
+		}
+	}
+	else
+	{
+		// Convert bias.
+		exponent += 0x1c000;
+	}
+
+	{
+		khronos_int32_t conv = ((half & 0x8000) << 16) |
+							   (exponent << 13) |
+							   (mantissa << 13);
+		return *(GLfloat*)&conv;
+	}
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/half.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,36 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef HALF_H_
+#define HALF_H_
+
+#include "common.h"
+
+GLfloat dglConvertHalfToFloat(khronos_int16_t half);
+
+#endif /* HALF_H_ */
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/hgl.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,66 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "degl.h"
+
+// Load the host renderer OpenGL functions.
+int hglLoad(HGL* hgl)
+{
+    Dprintf("Loading GL functions...\n", 0);
+
+#if(CONFIG_STATIC == 1)
+#	define HGL_FUNC(ret, name, attr) \
+        if(degl_handle == (void*)-1) \
+        { \
+            extern ret GL_APIENTRY mgl##name attr; \
+            hgl->name = &mgl##name; \
+        } \
+        else if((hgl->name = deglGetHostProcAddress("gl" #name)) == NULL) \
+        { \
+            fprintf(stderr, "Function gl" #name " not found!\n"); \
+        }
+#else
+#	define HGL_FUNC(ret, name, attr) \
+        { \
+        union {void *ptr; ret(GL_APIENTRY* fptr)attr;} ass; \
+        ass.ptr = deglGetHostProcAddress("gl" #name); \
+        if((hgl->name = ass.fptr) == NULL) \
+        { \
+            fprintf(stderr, "Function gl" #name " not found!\n"); \
+        }\
+        }
+#endif // CONFIG_STATIC != 1
+
+    HGL_FUNCS
+
+#undef HGL_FUNC
+
+    return 1;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/hgl.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,225 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef HGL_H_
+#define HGL_H_
+
+#include <GLES2/gl2.h>
+
+// Things that desktop GL has, but GL ES doesn't.
+
+#define GL_BGR                              0x80E0
+#define GL_BGRA                             0x80E1
+#define GL_RGB8                             0x8051
+#define GL_RGBA8                            0x8058
+#ifndef DGLES2_NO_SRGB
+#define GL_SRGB8							0x8C41
+#define GL_SRGB8_ALPHA8						0x8C43
+#define GL_SLUMINANCE8						0x8C47
+#else
+// No sRGB support in OpenGL 2.0.
+#define GL_SRGB8							GL_RGB8
+#define GL_SRGB8_ALPHA8						GL_RGBA8
+#define GL_SLUMINANCE8						GL_LUMINANCE8
+#endif
+#define GL_LUMINANCE8                       0x8040
+#define GL_ALPHA8                           0x803C
+#define GL_DEPTH_COMPONENT24				0x81A6
+#define GL_DEPTH_COMPONENT32				0x81A7
+#define GL_UNSIGNED_INT_8_8_8_8_REV         0x8367
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV       0x8366
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV       0x8365
+#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS	0x8B49
+#define GL_MAX_VARYING_FLOATS				0x8B4B
+#define GL_MAX_VERTEX_UNIFORM_COMPONENTS	0x8B4A
+#define GL_TEXTURE_WIDTH                    0x1000
+#define GL_TEXTURE_HEIGHT					0x1001
+#define GL_TEXTURE_RED_SIZE                 0x805C
+#define GL_TEXTURE_GREEN_SIZE               0x805D
+#define GL_TEXTURE_BLUE_SIZE                0x805E
+#define GL_TEXTURE_ALPHA_SIZE               0x805F
+#define GL_TEXTURE_LUMINANCE_SIZE           0x8060
+#define GL_TEXTURE_INTERNAL_FORMAT          0x1003
+typedef char GLchar;		/* native character */
+typedef double GLclampd;    /* double precision float in [0,1] */
+
+#define HGL_FUNCS \
+	HGL_FUNC(GLenum, GetError, (void)) \
+	HGL_FUNC(GLuint, CreateShader, (GLenum)) \
+	HGL_FUNC(void, ShaderSource, (GLuint, GLsizei, const GLchar* *, const GLint *)) \
+	HGL_FUNC(void, CompileShader, (GLuint)) \
+	HGL_FUNC(void, GetShaderiv, (GLuint, GLenum, GLint *)) \
+	HGL_FUNC(void, GetShaderInfoLog, (GLuint, GLsizei, GLsizei *, GLchar *)) \
+	HGL_FUNC(GLuint, CreateProgram, (void)) \
+	HGL_FUNC(void, AttachShader, (GLuint, GLuint)) \
+	HGL_FUNC(void, BindAttribLocation, (GLuint, GLuint, const GLchar *)) \
+	HGL_FUNC(void, LinkProgram, (GLuint)) \
+	HGL_FUNC(void, UseProgram, (GLuint)) \
+	HGL_FUNC(void, GetProgramiv, (GLuint, GLenum, GLint *)) \
+	HGL_FUNC(void, GetProgramInfoLog, (GLuint, GLsizei, GLsizei *, GLchar *)) \
+	HGL_FUNC(GLint, GetUniformLocation, (GLuint, const GLchar *)) \
+	HGL_FUNC(void, Uniform1f, (GLint, GLfloat)) \
+	HGL_FUNC(void, Uniform2f, (GLint, GLfloat, GLfloat)) \
+	HGL_FUNC(void, Uniform3f, (GLint, GLfloat, GLfloat, GLfloat)) \
+	HGL_FUNC(void, Uniform4f, (GLint, GLfloat, GLfloat, GLfloat, GLfloat)) \
+	HGL_FUNC(void, Uniform1i, (GLint, GLint)) \
+	HGL_FUNC(void, Uniform2i, (GLint, GLint, GLint)) \
+	HGL_FUNC(void, Uniform3i, (GLint, GLint, GLint, GLint)) \
+	HGL_FUNC(void, Uniform4i, (GLint, GLint, GLint, GLint, GLint)) \
+	HGL_FUNC(void, Uniform1fv, (GLint, GLsizei, const GLfloat *)) \
+	HGL_FUNC(void, Uniform2fv, (GLint, GLsizei, const GLfloat *)) \
+	HGL_FUNC(void, Uniform3fv, (GLint, GLsizei, const GLfloat *)) \
+	HGL_FUNC(void, Uniform4fv, (GLint, GLsizei, const GLfloat *)) \
+	HGL_FUNC(void, Uniform1iv, (GLint, GLsizei, const GLint *)) \
+	HGL_FUNC(void, Uniform2iv, (GLint, GLsizei, const GLint *)) \
+	HGL_FUNC(void, Uniform3iv, (GLint, GLsizei, const GLint *)) \
+	HGL_FUNC(void, Uniform4iv, (GLint, GLsizei, const GLint *)) \
+	HGL_FUNC(void, UniformMatrix2fv, (GLint, GLsizei, GLboolean, const GLfloat *)) \
+	HGL_FUNC(void, UniformMatrix3fv, (GLint, GLsizei, GLboolean, const GLfloat *)) \
+	HGL_FUNC(void, UniformMatrix4fv, (GLint, GLsizei, GLboolean, const GLfloat *)) \
+	HGL_FUNC(void, Clear, (GLbitfield mask )) \
+	HGL_FUNC(void, ClearColor, (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha )) \
+	HGL_FUNC(void, EnableVertexAttribArray, (GLuint)) \
+	HGL_FUNC(void, DisableVertexAttribArray, (GLuint)) \
+	HGL_FUNC(void, VertexAttribPointer, (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *)) \
+	HGL_FUNC(void, DrawArrays, (GLenum mode, GLint first, GLsizei count )) \
+	HGL_FUNC(void, GenBuffers, (GLsizei, GLuint *)) \
+	HGL_FUNC(void, BindBuffer, (GLenum, GLuint)) \
+	HGL_FUNC(void, BufferData, (GLenum, GLsizeiptr, const GLvoid *, GLenum)) \
+	HGL_FUNC(void, GenTextures, (GLsizei n, GLuint *textures)) \
+	HGL_FUNC(void, DeleteTextures, (GLsizei n, const GLuint *textures)) \
+	HGL_FUNC(void, BindTexture, (GLenum target, GLuint texture)) \
+	HGL_FUNC(void, TexImage2D, (GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels)) \
+	HGL_FUNC(void, TexParameterf, (GLenum target, GLenum pname, GLfloat param)) \
+	HGL_FUNC(void, TexParameteri, (GLenum target, GLenum pname, GLint param)) \
+	HGL_FUNC(void, TexParameterfv, (GLenum target, GLenum pname, const GLfloat *params)) \
+	HGL_FUNC(void, TexParameteriv, (GLenum target, GLenum pname, const GLint *params)) \
+	HGL_FUNC(const GLubyte*, GetString, (GLenum name)) \
+	HGL_FUNC(void, GetBooleanv, (GLenum pname, GLboolean *params)) \
+	HGL_FUNC(void, GetFloatv, (GLenum pname, GLfloat *params)) \
+	HGL_FUNC(void, GetIntegerv, (GLenum pname, GLint *params)) \
+	HGL_FUNC(void, BlendFunc, (GLenum sfactor, GLenum dfactor)) \
+	HGL_FUNC(void, ColorMask, (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)) \
+	HGL_FUNC(void, CullFace, (GLenum mode)) \
+	HGL_FUNC(void, Enable, (GLenum cap)) \
+	HGL_FUNC(void, Disable, (GLenum cap)) \
+	HGL_FUNC(void, Viewport, (GLint x, GLint y, GLsizei width, GLsizei height)) \
+	HGL_FUNC(void, PixelStorei, (GLenum pname, GLint param)) \
+	HGL_FUNC(void, TexSubImage2D, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)) \
+	HGL_FUNC(void, VertexAttrib1f, (GLuint, GLfloat)) \
+	HGL_FUNC(void, VertexAttrib1fv, (GLuint, const GLfloat *)) \
+	HGL_FUNC(void, VertexAttrib2f, (GLuint, GLfloat, GLfloat)) \
+	HGL_FUNC(void, VertexAttrib2fv, (GLuint, const GLfloat *)) \
+	HGL_FUNC(void, VertexAttrib3f, (GLuint, GLfloat, GLfloat, GLfloat)) \
+	HGL_FUNC(void, VertexAttrib3fv, (GLuint, const GLfloat *)) \
+	HGL_FUNC(void, VertexAttrib4f, (GLuint, GLfloat, GLfloat, GLfloat, GLfloat)) \
+	HGL_FUNC(void, VertexAttrib4fv, (GLuint, const GLfloat *)) \
+	HGL_FUNC(void, DeleteProgram, (GLuint)) \
+	HGL_FUNC(void, DeleteShader, (GLuint)) \
+	HGL_FUNC(void, DetachShader, (GLuint, GLuint)) \
+	HGL_FUNC(void, Hint, (GLenum target, GLenum mode)) \
+	HGL_FUNC(void, Scissor, (GLint x, GLint y, GLsizei width, GLsizei height)) \
+	HGL_FUNC(void, ReadPixels, (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels)) \
+	HGL_FUNC(void, GenerateMipmapEXT, (GLenum)) \
+	HGL_FUNC(void, BlendEquation, (GLenum mode)) \
+	HGL_FUNC(void, BlendColor, (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)) \
+	HGL_FUNC(void, BlendFuncSeparate, (GLenum, GLenum, GLenum, GLenum)) \
+	HGL_FUNC(void, BlendEquationSeparate, (GLenum, GLenum)) \
+	HGL_FUNC(void, BindFramebufferEXT, (GLenum, GLuint)) \
+	HGL_FUNC(void, DeleteFramebuffersEXT, (GLsizei, const GLuint *)) \
+	HGL_FUNC(void, GenFramebuffersEXT, (GLsizei, GLuint *)) \
+	HGL_FUNC(void, BindRenderbufferEXT, (GLenum, GLuint)) \
+	HGL_FUNC(void, DeleteRenderbuffersEXT, (GLsizei, const GLuint *)) \
+	HGL_FUNC(void, GenRenderbuffersEXT, (GLsizei, GLuint *)) \
+	HGL_FUNC(GLboolean, IsEnabled, (GLenum cap)) \
+	HGL_FUNC(void, ActiveTexture, (GLenum texture)) \
+	HGL_FUNC(void, GetTexParameterfv, (GLenum target, GLenum pname, const GLfloat *params)) \
+	HGL_FUNC(void, GetTexParameteriv, (GLenum target, GLenum pname, const GLint *params)) \
+	HGL_FUNC(GLboolean, IsTexture, (GLuint texture)) \
+	HGL_FUNC(GLboolean, IsProgram, (GLuint program)) \
+	HGL_FUNC(GLboolean, IsShader, (GLuint shader)) \
+	HGL_FUNC(void, BufferSubData, (GLenum, GLintptr, GLsizeiptr, const GLvoid *)) \
+	HGL_FUNC(void, DeleteBuffers, (GLsizei, const GLuint *)) \
+	HGL_FUNC(GLboolean, IsBuffer, (GLuint)) \
+	HGL_FUNC(void, DrawElements, (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices)) \
+	HGL_FUNC(GLint, GetAttribLocation, (GLuint, const GLchar *)) \
+	HGL_FUNC(void, StencilFunc, (GLenum func, GLint ref, GLuint mask)) \
+	HGL_FUNC(void, StencilMask, (GLuint mask)) \
+	HGL_FUNC(void, StencilOp, (GLenum fail, GLenum zfail, GLenum zpass)) \
+	HGL_FUNC(void, ClearStencil, (GLint s)) \
+	HGL_FUNC(void, FramebufferTexture2DEXT, (GLenum, GLenum, GLenum, GLuint, GLint)) \
+	HGL_FUNC(void, RenderbufferStorageEXT, (GLenum, GLenum, GLsizei, GLsizei)) \
+	HGL_FUNC(void, FramebufferRenderbufferEXT, (GLenum, GLenum, GLenum, GLuint)) \
+	HGL_FUNC(GLenum, CheckFramebufferStatusEXT, (GLenum)) \
+	HGL_FUNC(void, Finish, (void)) \
+	HGL_FUNC(void, Flush, (void)) \
+	HGL_FUNC(void, DepthFunc, (GLenum func)) \
+	HGL_FUNC(void, DepthMask, (GLboolean flag)) \
+	HGL_FUNC(void, DepthRange, (GLclampd zNear, GLclampd zFar)) \
+	HGL_FUNC(void, ClearDepth, (GLclampd depth)) \
+	HGL_FUNC(void, GetBufferParameteriv, (GLenum target, GLenum pname, GLint* params)) \
+	HGL_FUNC(void, GetActiveAttrib, (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name)) \
+	HGL_FUNC(void, GetActiveUniform, (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name)) \
+	HGL_FUNC(void, GetAttachedShaders, (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj)) \
+	HGL_FUNC(void, GetUniformfv, (GLuint program, GLint location, GLfloat *params)) \
+	HGL_FUNC(void, GetUniformiv, (GLuint program, GLint location, GLint *params)) \
+	HGL_FUNC(void, ValidateProgram, (GLuint program)) \
+	HGL_FUNC(void, GetShaderSource, (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source)) \
+	HGL_FUNC(void, LineWidth, (GLfloat width)) \
+	HGL_FUNC(void, FrontFace, (GLenum mode)) \
+	HGL_FUNC(void, PolygonOffset, (GLfloat factor, GLfloat units)) \
+	HGL_FUNC(void, SampleCoverage, (GLclampf value, GLboolean invert)) \
+	HGL_FUNC(void, StencilMaskSeparate, (GLenum face, GLuint mask)) \
+	HGL_FUNC(void, StencilFuncSeparate, (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask)) \
+	HGL_FUNC(void, StencilOpSeparate, (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)) \
+	HGL_FUNC(void, CopyTexImage2D, (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)) \
+	HGL_FUNC(void, GetFramebufferAttachmentParameterivEXT, (GLenum target, GLenum attachment, GLenum pname, GLint *params)) \
+	HGL_FUNC(void, GetRenderbufferParameterivEXT, (GLenum target, GLenum pname, GLint *params)) \
+	HGL_FUNC(void, CopyTexSubImage2D, (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)) \
+	HGL_FUNC(void, IsRenderbufferEXT, (GLuint renderbuffer)) \
+	HGL_FUNC(void, IsFramebufferEXT, (GLuint framebuffer)) \
+	HGL_FUNC(void, GetVertexAttribiv, (GLuint index, GLenum pname, GLint *params)) \
+	HGL_FUNC(void, GetVertexAttribfv, (GLuint index, GLenum pname, GLfloat *params)) \
+	HGL_FUNC(void, GetTexLevelParameteriv, (GLenum target, GLint level, GLenum pname, GLint *params)) \
+	HGL_FUNC(void, GetTexImage, (GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels)) \
+	HGL_FUNC(void, DrawPixels, (GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels))
+
+typedef struct HGL
+{
+#define HGL_FUNC(ret, name, attr) ret (GL_APIENTRY *name)attr;
+	HGL_FUNCS
+#undef HGL_FUNC
+} HGL;
+
+#ifndef HGL_NO_VARIABLES
+extern HGL hgl;
+
+extern int hglLoad();
+#endif // HGL_NO_VARIABLES
+
+#endif // HGL_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/object.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,110 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "object.h"
+
+void DGLObject_insert(DGLObject** root, DGLObject* object)
+{
+	// Insert the object into the linked list while maintaining the ordering by name.
+
+	DGLES2_ASSERT(root != NULL);
+	DGLES2_ASSERT(object != NULL);
+
+	if(*root == NULL)
+	{
+		// This is the first object.
+		*root = object;
+	}
+	else if((*root)->name > object->name)
+	{
+		// Insert in the front.
+		object->next = *root;
+		*root = object;
+	}
+	else
+	{
+		DGLObject* prev = *root;
+		while(prev->next != NULL && prev->next->name < object->name)
+		{
+			prev = prev->next;
+		}
+		
+		object->next = prev->next;
+		prev->next = object;
+	}
+}
+
+DGLObject* DGLObject_remove(DGLObject** root, GLuint name)
+{
+	DGLES2_ASSERT(root != NULL);
+	{
+		DGLObject* object = *root;
+
+		if(object == NULL)
+		{
+			// There are no buffers.
+			return NULL;
+		}
+
+		if(object->name == name)
+		{
+			// The first buffer is to be destroyed.
+			*root = object->next;
+			return object;
+		}
+		else
+		{
+			DGLObject* removed = NULL;
+
+			while(object->next != NULL && object->next->name != name)
+			{
+				object = object->next;
+			}
+
+			if(object->next != NULL)
+			{
+				// The buffer to be destroyed was found.
+				DGLObject* newNext = object->next->next;
+				removed = object->next;
+				object->next = newNext;
+			}
+
+			return removed;
+		}
+	}
+}
+
+DGLObject* DGLObject_find(DGLObject* root, GLuint name)
+{
+	DGLObject* object = root;
+	while(object != NULL && object->name != name)
+	{
+		object = object->next;
+	}
+	return object;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/object.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,44 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef OBJECT_H_
+#define OBJECT_H_
+
+#include "common.h"
+
+typedef struct DGLObject
+{
+	GLuint name;
+	struct DGLObject* next;
+} DGLObject;
+
+void		DGLObject_insert(DGLObject** root, DGLObject* object);
+DGLObject*	DGLObject_remove(DGLObject** root, GLuint name);
+DGLObject*	DGLObject_find(DGLObject* root, GLuint name);
+
+#endif /* OBJECT_H_ */
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/pixel.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,51 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+GL_APICALL_BUILD void GL_APIENTRY glPixelStorei(GLenum pname, GLint param)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(pname != GL_UNPACK_ALIGNMENT && pname != GL_PACK_ALIGNMENT, GL_INVALID_ENUM);
+	ctx->hgl.PixelStorei(pname, param);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(format != GL_RGBA, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(type != GL_UNSIGNED_BYTE, GL_INVALID_ENUM);
+	DGLES2_BEGIN_READING();
+	ctx->hgl.ReadPixels(x, y, width, height, format, type, pixels);
+	DGLES2_END_READING();
+	DGLES2_LEAVE();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/platform.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,91 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "platform.h"
+
+static int dgl_lock_initialized = 0;
+static DGLES2_LOCK dgl_lock;
+
+#ifdef _WIN32
+static void dglInitializeLock(void)
+{
+    InitializeCriticalSection(&dgl_lock);
+    dgl_lock_initialized = 1;
+}
+
+void dglGetLock(void)
+{
+    if(!dgl_lock_initialized)
+    {
+        dglInitializeLock();
+    }
+    EnterCriticalSection(&dgl_lock);
+}
+
+void dglReleaseLock(void)
+{
+    DGLES2_ASSERT(dgl_lock_initialized);
+    LeaveCriticalSection(&dgl_lock);
+}
+#else /* _WIN32 */
+static void initializeLock()
+{
+    int ret;
+
+    DGLES2_ASSERT(!dgl_lock_initialized);
+
+    pthread_mutexattr_t attr;
+    ret = pthread_mutexattr_init(&attr);	//initially not locked
+    DGLES2_ASSERT(!ret);	//check that there aren't any errors
+    ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);	//count the number of recursive locks
+    DGLES2_ASSERT(!ret);	//check that there aren't any errors
+    ret = pthread_mutex_init(&dgl_lock, &attr);
+    pthread_mutexattr_destroy(&attr);
+    DGLES2_ASSERT(!ret);	//check that there aren't more errors
+
+    dgl_lock_initialized = 1;
+}
+
+void glesGetLock()
+{
+    if(!dgl_lock_initialized)
+    {
+        initializeLock();
+    }
+    int ret = pthread_mutex_lock(&dgl_lock);
+    DGLES2_ASSERT(!ret);
+}
+
+void glesReleaseLock()
+{
+    DGLES2_ASSERT(dgl_lock_initialized);
+    int ret = pthread_mutex_unlock(&dgl_lock);
+    DGLES2_ASSERT(!ret);
+}
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/platform.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,47 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef PLATFORM_H_
+#define PLATFORM_H_
+
+#if defined(_WIN32)
+#	ifndef WIN32_LEAN_AND_MEAN
+#		define WIN32_LEAN_AND_MEAN 1
+#	endif
+#	include <windows.h>
+	typedef CRITICAL_SECTION DGLES2_LOCK;
+#else
+	#include <pthread.h>
+	typedef pthread_mutex_t DGLES2_LOCK;
+#endif
+
+void dglGetLock(void);
+void dglReleaseLock(void);
+
+#endif /* PLATFORM_H_ */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/program.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,501 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+const char* const DGLES2_INFO_LOG_INVALID_SHADERS = \
+	"A program must have exactly one vertex shader and one fragment shader.";
+
+DGLProgram* DGLProgram_create(GLuint name)
+{
+	DGLProgram* program = malloc(sizeof(DGLProgram));
+	if(program == NULL)
+	{
+		return NULL;
+	}
+
+	program->obj.name = name;
+	program->obj.next = NULL;
+
+	// Defer everything to the host GL by default.
+	program->link_status = GL_TRUE;
+	program->validate_status = GL_TRUE;
+
+	return program;
+}
+
+void DGLProgram_destroy(DGLProgram *program)
+{
+	DGLES2_ASSERT(program != NULL);
+	free(program);
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glAttachShader (GLuint program, GLuint shader)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(ctx->hgl.IsProgram(shader), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsShader(shader), GL_INVALID_VALUE);
+    ctx->hgl.AttachShader(program, shader);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBindAttribLocation(GLuint program, GLuint index, const char* name)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(index >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(strncmp(name, "gl_", 3) == 0, GL_INVALID_OPERATION);
+    ctx->hgl.BindAttribLocation(program, index, name);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD GLuint GL_APIENTRY glCreateProgram(void)
+{
+	DGLES2_ENTER_RET(0);
+	{
+		GLuint name;
+		DGLContext_getHostError(ctx);
+		name = ctx->hgl.CreateProgram();
+		if(DGLContext_getHostError(ctx) == GL_NO_ERROR && name != 0)
+		{
+			DGLContext_createProgram(ctx, name);
+		}
+
+		DGLES2_LEAVE_RET(name);
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDeleteProgram(GLuint program)
+{
+	DGLES2_ENTER();
+	if(program != 0)
+	{
+		DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+		DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+		ctx->hgl.DeleteProgram(program);
+		if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+		{
+			DGLContext_destroyProgram(ctx, program);
+		}
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDetachShader(GLuint program, GLuint shader)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(ctx->hgl.IsProgram(shader), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsShader(shader), GL_INVALID_VALUE);
+	ctx->hgl.DetachShader(program, shader);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	ctx->hgl.GetActiveAttrib(program, index, bufsize, length, size, type, name);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	ctx->hgl.GetActiveUniform(program, index, bufsize, length, size, type, name);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	ctx->hgl.GetAttachedShaders(program, maxcount, count, shaders);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD int GL_APIENTRY glGetAttribLocation (GLuint program, const char* name)
+{
+	DGLES2_ENTER_RET(-1);
+	DGLES2_ERROR_IF_RET(ctx->hgl.IsShader(program), GL_INVALID_OPERATION, -1);
+	DGLES2_ERROR_IF_RET(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE, -1);
+	DGLES2_LEAVE_RET(ctx->hgl.GetAttribLocation(program, name););
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetProgramiv(GLuint program, GLenum pname, GLint* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	switch(pname)
+	{
+		case GL_LINK_STATUS:
+			{
+				const DGLProgram* program_obj = DGLContext_findProgram(ctx, program);
+				DGLES2_ASSERT(program_obj != NULL);
+				if(program_obj->link_status)
+				{
+					// Our requirement for linking was fulfilled, ask the host.
+					ctx->hgl.GetProgramiv(program, GL_LINK_STATUS, params);
+				}
+				else
+				{
+					*params = GL_FALSE;
+				}
+			}
+			break;
+
+		case GL_VALIDATE_STATUS:
+			{
+				const DGLProgram* program_obj = DGLContext_findProgram(ctx, program);
+				DGLES2_ASSERT(program_obj != NULL);
+				if(program_obj->validate_status)
+				{
+					// Our requirement for validation was fulfilled, ask the host.
+					ctx->hgl.GetProgramiv(program, GL_VALIDATE_STATUS, params);
+				}
+				else
+				{
+					*params = GL_FALSE;
+				}
+			}
+			break;
+
+		case GL_INFO_LOG_LENGTH:
+			{
+				const DGLProgram* program_obj = DGLContext_findProgram(ctx, program);
+				DGLES2_ASSERT(program_obj != NULL);
+				if(!program_obj->link_status || !program_obj->validate_status)
+				{
+					// Use our own info log.
+					*params = strlen(DGLES2_INFO_LOG_INVALID_SHADERS);
+				}
+				else
+				{
+					ctx->hgl.GetProgramiv(program, GL_INFO_LOG_LENGTH, params);
+				}
+			}
+			break;
+
+		default:
+			ctx->hgl.GetProgramiv(program, pname, params);
+			break;
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, char* infolog)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	{
+		const DGLProgram* program_obj = DGLContext_findProgram(ctx, program);
+		DGLES2_ASSERT(program_obj != NULL);
+		if(!program_obj->link_status || !program_obj->validate_status)
+		{
+			// Use our own info log.
+
+			if(length != NULL)
+			{
+				*length = 0;
+			}
+
+			if(infolog != NULL)
+			{
+				int log_length = strlen(DGLES2_INFO_LOG_INVALID_SHADERS);
+				int num_chars = log_length < bufsize - 1 ? log_length : bufsize - 1;
+
+				strncpy(infolog, DGLES2_INFO_LOG_INVALID_SHADERS, num_chars);
+				infolog[num_chars] = 0;
+
+				if(length != NULL)
+				{
+					*length = num_chars;
+				}
+			}
+		}
+		else
+		{
+			ctx->hgl.GetProgramInfoLog(program, bufsize, length, infolog);
+		}
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetUniformfv(GLuint program, GLint location, GLfloat* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	ctx->hgl.GetUniformfv(program, location, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetUniformiv(GLuint program, GLint location, GLint* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	ctx->hgl.GetUniformiv(program, location, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD int GL_APIENTRY glGetUniformLocation(GLuint program, const char* name)
+{
+	DGLES2_ENTER_RET(-1);
+	DGLES2_ERROR_IF_RET(ctx->hgl.IsShader(program), GL_INVALID_OPERATION, -1);
+	DGLES2_ERROR_IF_RET(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE, -1);
+	DGLES2_LEAVE_RET(ctx->hgl.GetUniformLocation(program, name));
+}
+
+GL_APICALL_BUILD GLboolean GL_APIENTRY glIsProgram(GLuint program)
+{
+	DGLES2_ENTER_RET(GL_FALSE);
+	DGLES2_LEAVE_RET(ctx->hgl.IsProgram(program));
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glLinkProgram(GLuint program)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	{
+		GLint num_shaders;
+
+		DGLProgram* program_obj = DGLContext_findProgram(ctx, program);
+		DGLES2_ASSERT(program_obj != NULL);
+
+		ctx->hgl.GetProgramiv(program, GL_ATTACHED_SHADERS, &num_shaders);
+
+		// Linked programs must have both a vertex and a fragment shader in GL ES.
+		// Multiple shaders of the same type may not be attached to a single program object.
+		if(num_shaders != 2)
+		{
+			program_obj->link_status = GL_FALSE;
+		}
+		else
+		{
+			// Check that the shaders are of different type.
+
+			GLuint shaders[2];
+			GLint types[2];
+			ctx->hgl.GetAttachedShaders(program, 2, NULL, shaders);
+			ctx->hgl.GetShaderiv(shaders[0], GL_SHADER_TYPE, &types[0]);
+			ctx->hgl.GetShaderiv(shaders[1], GL_SHADER_TYPE, &types[1]);
+			
+			if(types[0] == types[1])
+			{
+				program_obj->link_status = GL_FALSE;
+			}
+			else
+			{
+				program_obj->link_status = GL_TRUE;
+				ctx->hgl.LinkProgram(program);
+			}
+		}
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform1f (GLint location, GLfloat x)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform1f(location, x);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat* v)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform1fv(location, count, v);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform1i (GLint location, GLint x)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform1i(location, x);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint* v)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform1iv(location, count, v);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform2f (GLint location, GLfloat x, GLfloat y)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform2f(location, x, y);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat* v)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform2fv(location, count, v);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform2i (GLint location, GLint x, GLint y)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform2i(location, x, y);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint* v)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform2iv(location, count, v);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform3f (GLint location, GLfloat x, GLfloat y, GLfloat z)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform3f(location, x, y, z);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat* v)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform3fv(location, count, v);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform3i (GLint location, GLint x, GLint y, GLint z)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform3i(location, x, y, z);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint* v)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform3iv(location, count, v);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform4f (GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform4f(location, x, y, z, w);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat* v)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform4fv(location, count, v);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform4i (GLint location, GLint x, GLint y, GLint z, GLint w)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform4i(location, x, y, z, w);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint* v)
+{
+	DGLES2_ENTER();
+	ctx->hgl.Uniform4iv(location, count, v);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+{
+	DGLES2_ENTER();
+	ctx->hgl.UniformMatrix2fv(location, count, transpose, value);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+{
+	DGLES2_ENTER();
+	ctx->hgl.UniformMatrix3fv(location, count, transpose, value);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value)
+{
+	DGLES2_ENTER();
+	ctx->hgl.UniformMatrix4fv(location, count, transpose, value);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glUseProgram (GLuint program)
+{
+	DGLES2_ENTER();
+	ctx->hgl.UseProgram(program);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glValidateProgram (GLuint program)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsShader(program), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsProgram(program), GL_INVALID_VALUE);
+	{
+		GLint num_shaders;
+
+		DGLProgram* program_obj = DGLContext_findProgram(ctx, program);
+		DGLES2_ASSERT(program_obj != NULL);
+
+		// The program must no be empty.
+		ctx->hgl.GetProgramiv(program, GL_ATTACHED_SHADERS, &num_shaders);
+		if(num_shaders == 0)
+		{
+			program_obj->validate_status = GL_FALSE;
+		}
+		else
+		{
+			program_obj->validate_status = GL_TRUE;
+			ctx->hgl.ValidateProgram(program);
+		}
+	}
+	DGLES2_LEAVE();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/program.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,43 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef PROGRAM_H_
+#define PROGRAM_H_
+
+typedef struct DGLProgram
+{
+	struct DGLObject obj;
+
+	GLboolean	link_status;
+	GLboolean	validate_status;
+} DGLProgram;
+
+DGLProgram*	DGLProgram_create(GLuint name);
+void		DGLProgram_destroy(DGLProgram* program);
+
+#endif // PROGRAM_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/shader.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,554 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+#include <string.h>
+
+DGLShader* DGLShader_create(GLuint name)
+{
+	DGLShader* shader = malloc(sizeof(DGLShader));
+	if(shader == NULL)
+	{
+		return NULL;
+	}
+
+	shader->obj.name = name;
+	shader->obj.next = NULL;
+
+	shader->source = NULL;
+	shader->length = 0;
+
+	return shader;
+}
+
+void DGLShader_destroy(DGLShader *shader)
+{
+	DGLES2_ASSERT(shader != NULL);
+	if(shader->source != NULL)
+	{
+		free(shader->source);
+		shader->source = NULL;
+	}
+	free(shader);
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glCompileShader(GLuint shader)
+{
+	DGLES2_ENTER();
+	ctx->hgl.CompileShader(shader);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD GLuint GL_APIENTRY glCreateShader(GLenum type)
+{
+	DGLES2_ENTER_RET(0);
+	DGLES2_ERROR_IF_RET(type != GL_VERTEX_SHADER && type != GL_FRAGMENT_SHADER, GL_INVALID_ENUM, 0);
+	{
+		GLuint name = ctx->hgl.CreateShader(type);
+		if(DGLContext_getHostError(ctx) == GL_NO_ERROR && name != 0)
+		{
+			DGLContext_createShader(ctx, name);
+		}
+
+		DGLES2_LEAVE_RET(name);
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDeleteShader(GLuint shader)
+{
+	DGLES2_ENTER();
+	if(shader != 0)
+	{
+		DGLES2_ERROR_IF(ctx->hgl.IsProgram(shader), GL_INVALID_OPERATION);
+		DGLES2_ERROR_IF(!ctx->hgl.IsShader(shader), GL_INVALID_VALUE);
+		ctx->hgl.DeleteShader(shader);
+		if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+		{
+			DGLContext_destroyShader(ctx, shader);
+		}
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetShaderiv(GLuint shader, GLenum pname, GLint* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsProgram(shader), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsShader(shader), GL_INVALID_VALUE);
+	if(pname == GL_SHADER_SOURCE_LENGTH)
+	{
+		DGLShader* shader_obj = DGLContext_findShader(ctx, shader);
+		DGLES2_ASSERT(shader_obj != NULL);
+		*params = shader_obj->length + 1;
+	}
+	else
+	{
+		ctx->hgl.GetShaderiv(shader, pname, params);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsProgram(shader), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsShader(shader), GL_INVALID_VALUE);
+	ctx->hgl.GetShaderInfoLog(shader, bufsize, length, infolog);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(shadertype != GL_VERTEX_SHADER && shadertype != GL_FRAGMENT_SHADER, GL_INVALID_ENUM);
+	// Values from the GL ES and GLSL specifications.
+	switch(precisiontype)
+	{
+		case GL_LOW_FLOAT:
+		case GL_MEDIUM_FLOAT:
+		case GL_HIGH_FLOAT:
+			range[0] = 127;
+			range[1] = 127;
+			*precision = 23;
+			break;
+
+		case GL_LOW_INT:
+		case GL_MEDIUM_INT:
+		case GL_HIGH_INT:
+			range[0] = 15;
+			range[1] = 14;
+			*precision = 0;
+			break;
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetShaderSource(GLuint shader, GLsizei bufsize, GLsizei* length, char* source)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsProgram(shader), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsShader(shader), GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(bufsize < 0, GL_INVALID_VALUE);
+	{
+		DGLShader* shader_obj = DGLContext_findShader(ctx, shader);
+		DGLES2_ASSERT(shader_obj != NULL);
+		
+		if(length != NULL)
+		{
+			*length = 0;
+		}
+
+		if(source != NULL)
+		{
+			GLsizei num_chars = shader_obj->length < bufsize - 1 ? shader_obj->length : bufsize - 1;
+			if(num_chars > 0)
+			{
+				strncpy(source, shader_obj->source, num_chars);
+				source[num_chars] = 0;
+				if(length != NULL)
+				{
+					*length = num_chars;
+				}
+			}
+		}
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD GLboolean GL_APIENTRY glIsShader(GLuint shader)
+{
+	DGLES2_ENTER_RET(GL_FALSE);
+	DGLES2_LEAVE_RET(ctx->hgl.IsShader(shader));
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glReleaseShaderCompiler(void)
+{
+	DGLES2_ENTER();
+	// No-op.
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glShaderBinary(GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length)
+{
+	DGLES2_ENTER();
+	// No supported formats.
+	DGLES2_ERROR(GL_INVALID_ENUM);
+	DGLES2_LEAVE();
+}
+
+static const char *opengl_strtok(const char *s, int *n)
+{
+    static char *buffer = 0;
+    static int buffersize = -1;
+    static const char *delim = " \t\n\r()[]{},;:";
+    static const char *prev = 0;
+    int cComment = 0;
+    int cppComment = 0;
+
+    if (!s) {
+        if (!*prev || !*n) {
+            if (buffer) {
+                free(buffer);
+                buffer = 0;
+                buffersize = -1;
+            }
+            prev = 0;
+            return 0;
+        }
+        s = prev;
+    } else {
+        if (buffer) {
+            free(buffer);
+            buffer = 0;
+            buffersize = -1;
+        }
+		prev = s;
+    }
+
+    if( *n && *s == '/') {
+        if(*(s+1) == '*') cComment = 1;
+        if(*(s+1) == '/') cppComment = 1;        
+    }
+    if( cComment == 1 || cppComment == 1) {
+        for(; *n && (cComment == 1 || cppComment == 1); s++, (*n)--) {
+            if(cComment == 1 && *s == '*' && *(s+1) == '/' ) {
+                cComment = 0;
+            }
+            if(cppComment == 1 && *s == '\n') {
+                cppComment = 0;
+            }
+        }
+    } else {
+        for (; *n && strchr(delim, *s); s++, (*n)--);
+    }
+
+	if(s - prev > 0) {
+		if (buffersize < s - prev) {
+			buffersize = s - prev;
+			if (buffer) {
+				free(buffer);
+			}
+			buffer = malloc(buffersize + 1);
+		}
+		memcpy(buffer, prev, s - prev);
+		buffer[s - prev] = 0;
+		prev = s;
+	} else {
+		const char *e = s;
+		for (; *n && *e && !strchr(delim, *e); e++, (*n)--);
+		prev = e;
+		if (buffersize < e - s) {
+			buffersize = e - s;
+			if (buffer) {
+				free(buffer);
+			}
+			buffer = malloc(buffersize + 1);
+		}
+		memcpy(buffer, s, e - s);
+		buffer[e - s] = 0;
+	}
+    return buffer;
+}
+
+static char* do_eglShaderPatch(char *source, int len, int *patched_len)
+{
+    /* DISCLAIMER: this is not a full-blown shader parser but a simple
+     * implementation which tries to remove the OpenGL ES shader
+     * "precision" statements and precision qualifiers "lowp", "mediump"
+     * and "highp" from the specified shader source, replace built-in
+	 * constants that were renamed in GLSL ES ("gl_MaxVertexUniformVectors",
+	 * "gl_MaxFragmentUniformVectors" and "gl_MaxVaryingVectors")
+	 * and insert a "#version 120" directive in the beginning of the source
+	 * or replace an existing "#version 100" directive. */
+	DGLES2_ASSERT(source != NULL);
+	DGLES2_ASSERT(len >= 0);
+	{
+#ifndef DGLES2_ALLOW_GLSL_110
+		GLboolean version_found = GL_FALSE;
+#endif
+		int buffer_size;
+		char *patched;
+		const char *p;
+		
+		*patched_len = 0;
+		buffer_size = len;
+		patched = malloc(buffer_size + 1);
+		if(patched == NULL)	{
+			return NULL;
+		}
+
+		p = opengl_strtok(source, &len);
+		for (; p; p = opengl_strtok(0, &len)) {
+			if (!strcmp(p, "lowp") || !strcmp(p, "mediump") || !strcmp(p, "highp")) {
+				continue;
+			} else if (!strcmp(p, "precision")) {
+				do {
+					p = opengl_strtok(0, &len);
+				} while(p && !strchr(p, ';'));
+			} else {
+				int tok_len;
+				if (!strcmp(p, "gl_MaxVertexUniformVectors")) {
+					p = "(gl_MaxVertexUniformComponents / 4)";
+				} else if (!strcmp(p, "gl_MaxFragmentUniformVectors")) {
+					p = "(gl_MaxFragmentUniformComponents / 4)";
+				} else if (!strcmp(p, "gl_MaxVaryingVectors")) {
+					p = "(gl_MaxVaryingFloats / 4)";
+				}
+#ifndef DGLES2_ALLOW_GLSL_110
+				else if (!strcmp(p, "#version")) {
+					p = opengl_strtok(0, &len);
+					if (!strcmp(p, "100")) {
+						p = "#version 120";
+						version_found = GL_TRUE;
+					}
+				} else if (!strcmp(p, "#")) {
+					p = opengl_strtok(0, &len);
+					if (!strcmp(p, "version")) {
+						p = opengl_strtok(0, &len);
+						if (!strcmp(p, "100")) {
+							p = "#version 120";
+							version_found = GL_TRUE;
+						}
+					}
+				} 
+#endif // !DGLES2_ALLOW_GLSL_110
+				tok_len = strlen(p);
+				if(*patched_len + tok_len > buffer_size) {
+					buffer_size *= 2;
+					patched = realloc(patched, buffer_size + 1);
+					if(patched == NULL) {
+						return NULL;
+					}
+				}
+				memcpy(patched + *patched_len, p, tok_len);
+				*patched_len += tok_len;
+			}
+		}
+		patched[*patched_len] = 0;
+#ifndef DGLES2_ALLOW_GLSL_110
+		/* add version directive is one was not found */
+		if (!version_found) {
+			char* new_patched;
+			*patched_len += strlen("#version 120\n");
+			new_patched = malloc(*patched_len + 1);
+			if (new_patched == NULL) {
+				return NULL;
+			}
+			strcpy(new_patched, "#version 120\n");
+			strcat(new_patched, patched);
+			free(patched);
+			patched = new_patched;
+		}
+#endif // !DGLES2_ALLOW_GLSL_110
+		{
+			/* check that we don't leave dummy preprocessor lines */
+			char *sp;
+			for (sp = patched; *sp;) {
+				for (; *sp == ' ' || *sp == '\t'; sp++);
+				if (!strncmp(sp, "#define", 7)) {
+					for (p = sp + 7; *p == ' ' || *p == '\t'; p++);
+					if (*p == '\n' || *p == '\r' || *p == '/') {
+						memset(sp, 0x20, 7);
+					}
+				}
+				for (; *sp && *sp != '\n' && *sp != '\r'; sp++);
+				for (; *sp == '\n' || *sp == '\r'; sp++);
+			}
+		}
+
+		return patched;
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glShaderSource(GLuint shader, GLsizei count, const char** string, const GLint* length)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(ctx->hgl.IsProgram(shader), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!ctx->hgl.IsShader(shader), GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(count < 0, GL_INVALID_VALUE);
+/*
+#if(CONFIG_DEBUG == 1)
+	Dprintf("Editing shader:\n--ORIGINAL-SHADER--\n");
+	for(unsigned i = 0; i < count; ++i)
+	{
+		if(length)
+			Dprintf("%*s", length[i], string[i]);
+		else
+			Dprintf("%s", string[i]);
+	}
+	Dprintf("---END-ORIGINAL-SHADER---\n");
+#endif // !NDEBUG
+	char** string_dgl = malloc(sizeof(char*)*count);
+	GLint* length_dgl = malloc(sizeof(GLint)*count);
+
+	// Remove the non OpenGL 2.x compilant keywords.
+	for(unsigned i = 0; i < count; ++i)
+	{
+		static const char* removables[] =
+		{
+			"precision highp float;",
+			"precision mediump float;",
+			"precision lowp float;",
+			"highp",
+			"lowp",
+			"mediump",
+			"precision"
+		};
+
+		length_dgl[i] = length ? length[i] : strlen(string[i]);
+		string_dgl[i] = malloc(length_dgl[i] + 1);
+		memcpy(string_dgl[i], string[i], length_dgl[i]);
+		string_dgl[i][length_dgl[i]] = 0;
+
+		for(unsigned j = 0; j < sizeof(removables)/sizeof(removables[0]); ++j)
+		{
+			char const* p;
+			while((p = strstr(string_dgl[i], removables[j])))
+			{
+				memmove(p, p + strlen(removables[j]), strlen(p + strlen(removables[j])) + 1);
+			}
+		}
+	}
+#if(CONFIG_DEBUG == 1)
+	Dprintf("Loading shader:\n--DESKTOP-GL-SHADER--\n");
+	for(unsigned i = 0; i < count; ++i)
+	{
+		Dprintf("%*s", length_dgl[i], string_dgl[i]);
+	}
+	Dprintf("---END-DESKTOP-GL-SHADER---\n");
+#endif // !NDEBUG
+    
+	ctx->hgl.ShaderSource(shader, count, string_dgl, length_dgl);
+
+	for(unsigned i = 0; i < count; ++i)
+		free(string_dgl[i]);
+	free(string_dgl);
+	free(length_dgl);
+ */
+
+	if(count > 0 && string != NULL)
+	{
+		char* source = NULL;
+		int total_len = 0;
+
+		if(count > 1)
+		{
+			int i;
+
+			// Concatenate the passed strings into one source string.
+			for(i = 0; i < count; i++)
+			{
+				int len;
+
+				if(string[i] == NULL)
+				{
+					continue;
+				}
+
+				if(length == NULL || length[i] < 0)
+				{
+					len = strlen(string[i]);
+				}
+				else
+				{
+					len = length[i];
+				}
+
+				if(len > 0)
+				{
+					total_len += len;
+
+					if(source == NULL)
+					{
+						source = malloc(total_len + 1);
+						if(source == NULL)
+						{
+							DGLES2_ERROR(GL_OUT_OF_MEMORY);
+						}
+						source[0] = 0;
+					}
+					else
+					{
+						source = realloc(source, total_len + 1);
+						if(source == NULL)
+						{
+							DGLES2_ERROR(GL_OUT_OF_MEMORY);
+						}
+					}
+
+					strncat(source, string[i], len);
+				}
+			}
+		}
+		else
+		{
+			source = (char*)string[0];
+			if(length == NULL || length[0] < 0)
+			{
+				total_len = strlen(source);
+			}
+			else
+			{
+				total_len = length[0];
+			}
+		}
+
+		{
+			// FIXME: This will fail with real constant data!
+			int patched_len;
+			const GLchar* patched = do_eglShaderPatch(source, total_len, &patched_len);
+			if(patched == NULL)
+			{
+				DGLES2_ERROR(GL_OUT_OF_MEMORY);
+			}
+			ctx->hgl.ShaderSource(shader, 1, &patched, &patched_len);
+			free((void*)patched);
+		}
+
+		if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+		{
+			if(!DGLContext_setShaderSource(ctx, shader, source, total_len))
+			{
+				DGLES2_ERROR(GL_OUT_OF_MEMORY);
+			}
+		}
+
+		if(count > 1)
+		{
+			free(source);
+		}
+	}
+	else
+	{
+		ctx->hgl.ShaderSource(shader, count, string, length);
+	}
+
+	DGLES2_LEAVE();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/shader.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,44 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef SHADER_H_
+#define SHADER_H_
+
+typedef struct DGLShader
+{
+	struct DGLObject obj;
+
+	char*	source;
+	GLsizei length;
+} DGLShader;
+
+DGLShader*	DGLShader_create(GLuint name);
+void		DGLShader_destroy(DGLShader* shader);
+
+#endif // SHADER_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/stencil.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,81 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+
+GL_APICALL_BUILD void GL_APIENTRY glStencilFunc(GLenum func, GLint ref, GLuint mask)
+{
+	DGLES2_ENTER();
+	ctx->hgl.StencilFunc(func, ref, mask);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
+{
+	DGLES2_ENTER();
+	ctx->hgl.StencilFuncSeparate(face, func, ref, mask);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glStencilMask(GLuint mask)
+{
+	DGLES2_ENTER();
+	ctx->hgl.StencilMask(mask);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glStencilMaskSeparate(GLenum face, GLuint mask)
+{
+	DGLES2_ENTER();
+	ctx->hgl.StencilMaskSeparate(face, mask);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glStencilOp(GLenum fail, GLenum zfail, GLenum zpass)
+{
+	DGLES2_ENTER();
+	ctx->hgl.StencilOp(fail, zfail, zpass);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glStencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
+{
+	DGLES2_ENTER();
+	ctx->hgl.StencilOpSeparate(face, fail, zfail, zpass);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glClearStencil(GLint s)
+{
+	DGLES2_ENTER();
+	ctx->hgl.ClearStencil(s);
+	DGLES2_LEAVE();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/texture.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1344 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+#include "half.h"
+#include "util.h"
+#include "degl.h"
+
+DGLTexture* DGLTexture_create(GLuint name, DGLTextureType type, GLint num_levels)
+{
+	DGLTexture* texture = malloc(sizeof(DGLTexture));
+	if(texture == NULL)
+	{
+		return NULL;
+	}
+
+	texture->obj.name = name;
+	texture->obj.next = NULL;
+
+	texture->type = type;
+
+	{
+		int face;
+		for(face = 0; face < 6; face++)
+		{
+			texture->num_levels[face] = 0;
+			texture->levels[face] = malloc(num_levels * sizeof(DGLTextureLevel));
+			if(texture->levels[face] == NULL)
+			{
+				while(face--)
+				{
+					free(texture->levels[face]);
+				}
+				free(texture);
+				return NULL;
+			}
+			{
+				int level;
+				for(level = 0; level < num_levels; level++)
+				{
+					texture->levels[face][level].specified = GL_FALSE;
+					texture->levels[face][level].format = 0;
+					texture->levels[face][level].width = 0;
+					texture->levels[face][level].height = 0;
+					texture->levels[face][level].bound_surface = NULL;
+				}
+			}
+			texture->egl_image[face] = NULL;
+		}
+	}
+
+	return texture;
+}
+
+static GLenum dglFaceToTarget(DGLTexture* texture, int face)
+{
+	DGLES2_ASSERT(texture != NULL);
+	{
+		switch(face)
+		{
+			case 0:
+				if(texture->type == DGLES2_TEXTURE_2D)
+				{
+					return GL_TEXTURE_2D;
+				}
+				else
+				{
+					DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+					return GL_TEXTURE_CUBE_MAP_POSITIVE_X;
+				}
+
+			case 1:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
+
+			case 2:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
+
+			case 3:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
+
+			case 4:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
+
+			case 5:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
+
+			default:
+				DGLES2_ASSERT(GL_FALSE);
+				return -1;
+		}
+	}
+}
+
+void DGLTexture_destroy(DGLTexture *texture)
+{
+	DGLES2_ASSERT(texture != NULL);
+	{
+		int face;
+		for(face = 0; face < 6; face++)
+		{
+			DGLES2_ASSERT(texture->levels[face] != NULL);
+			free(texture->levels[face]);
+			texture->levels[face] = NULL;
+
+			if(texture->egl_image[face] != NULL)
+			{
+				deglUnregisterImageTarget(texture->egl_image[face], dglFaceToTarget(texture, face), texture->obj.name);
+				texture->egl_image[face] = NULL;
+			}
+		}
+	}
+	free(texture);
+}
+
+GLboolean DGLTexture_isComplete(const DGLTexture* texture)
+{
+	DGLES2_ASSERT(texture != NULL);
+	{
+		int num_faces = 6 ? texture->type == DGLES2_TEXTURE_CUBE_MAP : 1;
+		int face;
+		for(face = 0; face < num_faces; face++)
+		{
+			if(texture->num_levels[face] < 1)
+			{
+				return GL_FALSE;
+			}
+			else
+			{
+				int i;
+				const DGLTextureLevel* level_zero;
+				int width;
+				int height;
+
+				level_zero = &texture->levels[face][0];
+				width = level_zero->width;
+				height = level_zero->height;
+
+				if(width <= 0 || height <= 0)
+				{
+					return GL_FALSE;
+				}
+
+				for(i = 1; i < texture->num_levels[face]; i++)
+				{
+					const DGLTextureLevel* level = &texture->levels[face][i];
+
+					if(width > 1) width /= 2;
+					if(height > 1) height /= 2;
+
+					if(level->format != level_zero->format ||
+					   level->width != width ||
+					   level->height != height ||
+					   level->width == 0 ||
+					   level->height == 0)
+					{
+						return GL_FALSE;
+					}
+				}
+			}
+		}
+
+		return GL_TRUE;
+	}
+}
+
+GLboolean DGLTexture_hasLevelZero(const DGLTexture* texture)
+{
+	DGLES2_ASSERT(texture != NULL);
+	{
+		int num_faces = 6 ? texture->type == DGLES2_TEXTURE_CUBE_MAP : 1;
+		int face;
+		for(face = 0; face < num_faces; face++)
+		{
+			if(texture->num_levels[face] <= 0 || !texture->levels[face][0].specified)
+			{
+				return GL_FALSE;
+			}
+		}
+
+		return GL_TRUE;
+	}
+}
+
+GLboolean DGLTexture_hasLevelsOtherThanZero(const DGLTexture* texture)
+{
+	DGLES2_ASSERT(texture != NULL);
+	{
+		int num_faces = 6 ? texture->type == DGLES2_TEXTURE_CUBE_MAP : 1;
+		int face;
+		for(face = 0; face < num_faces; face++)
+		{
+			int level;
+			for(level = 1; level < texture->num_levels[face]; level++)
+			{
+				if(texture->levels[face][level].specified)
+				{
+					return GL_TRUE;
+				}
+			}
+		}
+
+		return GL_FALSE;
+	}
+}
+
+static int dglTargetToFace(DGLTexture* texture, GLenum target)
+{
+	DGLES2_ASSERT(texture != NULL);
+	{
+		switch(target)
+		{
+			case GL_TEXTURE_2D:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_2D);
+				return 0;
+
+			case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return 0;
+
+			case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return 1;
+
+			case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return 2;
+
+			case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return 3;
+
+			case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return 4;
+
+			case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
+				DGLES2_ASSERT(texture->type == DGLES2_TEXTURE_CUBE_MAP);
+				return 5;
+
+			default:
+				DGLES2_ASSERT(GL_FALSE);
+				return -1;
+		}
+	}
+}
+
+DGLTextureLevel* DGLTexture_getLevel(DGLTexture* texture, GLenum target, GLint level)
+{	
+	DGLES2_ASSERT(texture != NULL);
+	return &texture->levels[dglTargetToFace(texture, target)][level];
+}
+
+void DGLTexture_setLevel(DGLTexture* texture, GLenum target, GLint level, GLenum format, GLsizei width, GLsizei height)
+{
+	DGLES2_ASSERT(texture != NULL);
+	{
+		DGLTextureLevel* level_obj = DGLTexture_getLevel(texture, target, level);
+		level_obj->format = format;
+		level_obj->width = width;
+		level_obj->height = height;
+		level_obj->specified = GL_TRUE;
+	}
+}
+
+GLeglImageOES DGLTexture_getEGLImage(DGLTexture* texture, GLenum target)
+{
+	return texture->egl_image[dglTargetToFace(texture, target)];
+}
+
+void DGLTexture_setEGLImage(DGLTexture* texture, GLenum target, GLeglImageOES image)
+{
+	texture->egl_image[dglTargetToFace(texture, target)] = image;
+}
+
+void DGLTexture_generateMipmap(DGLTexture* texture)
+{
+	DGLES2_ASSERT(texture != NULL);
+	{
+		int face;
+		int num_faces;
+		const DGLTextureLevel* level_zero;
+		int level;
+		int num_levels;
+		int width, height;
+
+		num_faces = 6 ? texture->type == DGLES2_TEXTURE_CUBE_MAP : 1;
+		for(face = 0; face < num_faces; face++)
+		{
+			level_zero = &texture->levels[face][0];
+
+			num_levels = dglLog2(dglMax(level_zero->width, level_zero->height)) + 1;
+			texture->num_levels[face] = num_levels;
+
+			width = level_zero->width;
+			height = level_zero->height;
+
+			for(level = 0; level < num_levels; level++)
+			{
+				if(width > 1) width /= 2;
+				if(height > 1) height /= 2;
+
+				DGLES2_ASSERT(level < num_levels - 1 || (width > 1 || height > 1));
+
+				if(texture->levels[face][level].bound_surface != NULL)
+				{
+					// Texture image is respecified. Release the bound EGLSurface.
+					deglReleaseTexImage(texture->levels[face][level].bound_surface, texture->obj.name, level);
+				}
+
+				texture->levels[face][level].format = level_zero->format;
+				texture->levels[face][level].width = width;
+				texture->levels[face][level].height = height;
+				texture->levels[face][level].bound_surface = NULL;
+				texture->levels[face][level].specified = GL_TRUE;
+			}
+		}
+	}
+}
+
+// Add a 3-bit two's complement integer to an integer.
+static int dglAddTwosComplement(int a, char b)
+{
+	if(b & 0x4)
+	{
+		// Negative.
+		return a - ((~b + 1) & 0x7);
+	}
+	else
+	{
+		// Positive.
+		return a + b;
+	}
+}
+
+static int dglClamp(int x, int min, int max)
+{
+	if(x < min)
+	{
+		return min;
+	}
+	else if(x > max)
+	{
+		return max;
+	}
+	else
+	{
+		return x;
+	}
+}
+
+static void* dglDecompressETCTexture(int width, int height, const unsigned char* data)
+{
+	int bytes_per_pixel = 3; // RGB888
+
+	unsigned char* decompressed = malloc(width * height * bytes_per_pixel);
+	if(decompressed == NULL)
+	{
+		return NULL;
+	}
+	
+	{
+		int xblock, yblock;
+
+		char dr, dg, db;
+
+		// Number of 4x4 blocks horizontally and vertically.
+		int num_xblocks = (width + 3) / 4;
+		int num_yblocks = (height + 3) / 4;
+
+		for(yblock = 0; yblock < num_yblocks; yblock++)
+		{
+			for(xblock = 0; xblock < num_xblocks; xblock++)
+			{
+				int i;
+				char pixel;
+
+				khronos_int64_t blockbits;
+				int diffbit, flipbit;
+
+				unsigned char r[2], g[2], b[2];
+
+				int table[2];
+
+				// Construct 64 bits from 8 bytes.
+				blockbits = data[0];
+				for(i = 1; i < 8; i++)
+				{
+					blockbits <<= 8;
+					blockbits |= data[i];
+				}
+
+				diffbit = (blockbits >> 33) & 1;
+				flipbit = (blockbits >> 32) & 1;
+
+				// Base color.
+
+				if(!diffbit)
+				{
+					// Individual mode.
+					
+					// Subblock 1.
+					r[0] = (blockbits >> 60) & 0xf;
+					g[0] = (blockbits >> 52) & 0xf;
+					b[0] = (blockbits >> 44) & 0xf;
+
+					r[0] |= r[0] << 4;
+					g[0] |= g[0] << 4;
+					b[0] |= b[0] << 4;
+
+					// Subblock 2.
+					r[1] = (blockbits >> 56) & 0xf;
+					g[1] = (blockbits >> 48) & 0xf;
+					b[1] = (blockbits >> 40) & 0xf;
+
+					r[1] |= r[1] << 4;
+					g[1] |= g[1] << 4;
+					b[1] |= b[1] << 4;
+				}
+				else
+				{
+					// Differential mode.
+
+					r[0] = (blockbits >> 59) & 0x1f;
+					g[0] = (blockbits >> 51) & 0x1f;
+					b[0] = (blockbits >> 43) & 0x1f;
+
+					dr = (blockbits >> 56) & 0x7;
+					dg = (blockbits >> 48) & 0x7;
+					db = (blockbits >> 40) & 0x7;
+
+					// Subblock 2.
+					r[1] = dglAddTwosComplement(r[0], dr);
+					g[1] = dglAddTwosComplement(g[0], dg);
+					b[1] = dglAddTwosComplement(b[0], db);
+
+					r[1] = (r[1] << 3) | ((r[1] >> 2) & 0x7);
+					g[1] = (g[1] << 3) | ((g[1] >> 2) & 0x7);
+					b[1] = (b[1] << 3) | ((b[1] >> 2) & 0x7);
+
+					// Subblock 1.
+					r[0] = (r[0] << 3) | ((r[0] >> 2) & 0x7);
+					g[0] = (g[0] << 3) | ((g[0] >> 2) & 0x7);
+					b[0] = (b[0] << 3) | ((b[0] >> 2) & 0x7);
+				}
+
+				// Modifier tables.
+
+				table[0] = (blockbits >> 37) & 0x7;
+				table[1] = (blockbits >> 34) & 0x7;
+
+				// Write final pixel colors in a top-down left-right order per block.
+				for(pixel = 0; pixel < 4 * 4; pixel++)
+				{
+					static const int tables[][8] = {{2, 8}, {15, 17}, {9, 29}, {13, 42},
+										 	    {18, 60}, {24, 80}, {33, 106}, {47, 183}};
+					
+					int x, y;
+					int loc;
+					int subblock;
+					int modifier;
+
+					x = 4 * xblock + pixel / 4;
+					y = 4 * yblock + pixel % 4;
+
+					if(x >= width || y >= height)
+					{
+						continue;
+					}
+
+					// Memory location of destination pixel.
+					loc = y * width + x;
+					loc *= bytes_per_pixel;
+
+					if(flipbit)
+					{
+						subblock = (pixel / 2) & 1;
+					}
+					else
+					{
+						subblock = pixel / 8;
+					}
+
+					DGLES2_ASSERT(subblock == 0 || subblock == 1);
+
+					modifier = tables[table[subblock]][(blockbits >> pixel) & 1];
+					if((blockbits >> (16 + pixel)) & 1)
+					{
+						modifier *= -1;
+					}
+
+					decompressed[loc + 0] = dglClamp(r[subblock] + modifier, 0, 255);
+					decompressed[loc + 1] = dglClamp(g[subblock] + modifier, 0, 255);
+					decompressed[loc + 2] = dglClamp(b[subblock] + modifier, 0, 255);
+				}
+
+				// Move to next block.
+				data += 8;
+			}
+		}
+	}
+
+	return decompressed;
+}
+
+static GLboolean dglIsPalettedFormat(GLenum format)
+{
+	switch(format)
+	{
+	case GL_PALETTE4_RGB8_OES:
+	case GL_PALETTE4_RGBA8_OES:
+	case GL_PALETTE4_R5_G6_B5_OES:
+	case GL_PALETTE4_RGBA4_OES:
+	case GL_PALETTE4_RGB5_A1_OES:
+	case GL_PALETTE8_RGB8_OES:
+	case GL_PALETTE8_RGBA8_OES:
+	case GL_PALETTE8_R5_G6_B5_OES:
+	case GL_PALETTE8_RGBA4_OES:
+	case GL_PALETTE8_RGB5_A1_OES:
+		return GL_TRUE;
+	default:
+		return GL_FALSE;
+	}
+}
+
+static GLenum dglMapPalettedToBaseFormat(GLenum format)
+{
+	switch(format)
+	{
+	case GL_PALETTE4_RGB8_OES:
+	case GL_PALETTE4_R5_G6_B5_OES:
+	case GL_PALETTE8_RGB8_OES:
+	case GL_PALETTE8_R5_G6_B5_OES:
+		return GL_RGB;
+
+	case GL_PALETTE4_RGBA8_OES:
+	case GL_PALETTE4_RGBA4_OES:
+	case GL_PALETTE4_RGB5_A1_OES:
+	case GL_PALETTE8_RGBA8_OES:
+	case GL_PALETTE8_RGBA4_OES:
+	case GL_PALETTE8_RGB5_A1_OES:
+		return GL_RGBA;
+	
+	default:
+		DGLES2_ASSERT(GL_FALSE);
+	}
+
+	// not reached
+	return 0;
+}
+
+static void* dglDecompressPalettedTexture(int level, GLenum format, int width, int height, int imageSize, const void* data)
+{
+	const unsigned char* palette = data;
+	int bits_per_pixel;
+	int palette_entry_size;
+	int num_palette_entries;
+	const unsigned char* image_data;
+	int i;
+	int bytes_per_pixel;
+	GLenum base_format;
+	char* decompressed_data;
+	int pixels_per_byte;
+	int max_pixels;
+	int end;
+	int r, g, b, a;
+	
+	switch(format)
+	{
+	case GL_PALETTE4_RGB8_OES:
+		bits_per_pixel = 4;
+		palette_entry_size = 3;
+		break;
+
+	case GL_PALETTE4_RGBA8_OES:
+		bits_per_pixel = 4;
+		palette_entry_size = 4;
+		break;
+
+	case GL_PALETTE4_R5_G6_B5_OES:
+	case GL_PALETTE4_RGB5_A1_OES:
+	case GL_PALETTE4_RGBA4_OES:
+		bits_per_pixel = 4;
+		palette_entry_size = 2;
+		break;
+
+	case GL_PALETTE8_RGB8_OES:
+		bits_per_pixel = 8;
+		palette_entry_size = 3;
+		break;
+
+	case GL_PALETTE8_RGBA8_OES:
+		bits_per_pixel = 8;
+		palette_entry_size = 4;
+		break;
+
+	case GL_PALETTE8_R5_G6_B5_OES:
+	case GL_PALETTE8_RGBA4_OES:
+	case GL_PALETTE8_RGB5_A1_OES:
+		bits_per_pixel = 8;
+		palette_entry_size = 2;
+		break;
+
+	default:
+		DGLES2_ASSERT(GL_FALSE);
+	}
+
+	num_palette_entries = 2 << (bits_per_pixel - 1);
+	image_data = palette + num_palette_entries * palette_entry_size;
+
+	// Skip to the correct mip level
+	for(i = 0; i < level; i++)
+	{
+		if(bits_per_pixel == 8)
+		{
+			image_data += width * height * bits_per_pixel / 8;
+		}
+		else
+		{
+			DGLES2_ASSERT(bits_per_pixel == 4);
+			image_data += width * height * bits_per_pixel / 8 / 2;
+		}
+		width /= 2;
+		height /= 2;
+	}
+
+	base_format = dglMapPalettedToBaseFormat(format);
+	if(base_format == GL_RGB)
+	{
+		bytes_per_pixel = 3;
+	}
+	else
+	{
+		DGLES2_ASSERT(base_format == GL_RGBA);
+		bytes_per_pixel = 4;
+	}
+
+	decompressed_data = malloc(width * height * bytes_per_pixel);
+	if(decompressed_data == NULL)
+	{
+		return NULL;
+	}
+	
+	// Don't go past the end of the data
+	pixels_per_byte = 8 / bits_per_pixel;
+	max_pixels = ((const unsigned char*)data + imageSize - image_data) * pixels_per_byte;
+	end = dglMin(width * height, max_pixels);
+
+	for(i = 0; i < end; i++)
+	{
+		int index;
+		if(bits_per_pixel == 4)
+		{
+			if(i & 1)
+			{
+				index = image_data[i / 2] & 15;
+			}
+			else
+			{
+				index = image_data[i / 2] >> 4;
+			}
+		}
+		else
+		{
+			DGLES2_ASSERT(bits_per_pixel == 8);
+			index = image_data[i];
+		}
+
+		switch(format)
+		{
+		case GL_PALETTE4_RGB8_OES:
+		case GL_PALETTE8_RGB8_OES:
+			r = palette[index*3];
+			g = palette[index*3+1];
+			b = palette[index*3+2];
+			break;
+
+		case GL_PALETTE4_RGBA8_OES:
+		case GL_PALETTE8_RGBA8_OES:
+			r = palette[index*4];
+			g = palette[index*4+1];
+			b = palette[index*4+2];
+			a = palette[index*4+3];
+			break;
+
+		case GL_PALETTE4_R5_G6_B5_OES:
+		case GL_PALETTE8_R5_G6_B5_OES:
+			r = palette[index*2+1] >> 3;
+			r = (r << 3) | (r >> 2);
+			g = ((palette[index*2+1] & 7) << 3) | (palette[index*2] >> 5);
+			g = (g << 2) | (g >> 4);
+			b = palette[index*2] & 0x1f;
+			b = (b << 3) | (b >> 2);
+			break;
+
+		case GL_PALETTE4_RGBA4_OES:
+		case GL_PALETTE8_RGBA4_OES:
+			r = palette[index*2+1] >> 4;
+			r |= (r << 4) | r;
+			g = palette[index*2+1] & 0xf;
+			g |= (g << 4) | g;
+			b = palette[index*2] >> 4;
+			b |= (b << 4) | b;
+			a = palette[index*2] & 0xf;
+			a |= (a << 4) | a;
+			break;
+
+		case GL_PALETTE4_RGB5_A1_OES:
+		case GL_PALETTE8_RGB5_A1_OES:
+			r = palette[index*2+1] >> 3;
+			r = (r << 3) | (r >> 2);
+			g = ((palette[index*2+1] & 7) << 2) | (palette[index*2] >> 6);
+			g = (g << 3) | (g >> 2);
+			b = (palette[index*2] >> 1) & 0x1f;
+			b = (b << 3) | (b >> 2);
+			a = (palette[index*2] & 1) ? 255 : 0;
+			break;
+			
+		default:
+			DGLES2_ASSERT(GL_FALSE);
+		}
+
+		if(base_format == GL_RGB)
+		{
+			decompressed_data[i*3+0] = r;
+			decompressed_data[i*3+1] = g;
+			decompressed_data[i*3+2] = b;
+		}
+		else
+		{
+			DGLES2_ASSERT(base_format == GL_RGBA);
+			decompressed_data[i*4+0] = r;
+			decompressed_data[i*4+1] = g;
+			decompressed_data[i*4+2] = b;
+			decompressed_data[i*4+3] = a;
+		}
+	}
+
+	return decompressed_data;
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glActiveTexture(GLenum texture)
+{
+	DGLES2_ENTER();
+	ctx->hgl.ActiveTexture(texture);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glBindTexture (GLenum target, GLuint texture)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP, GL_INVALID_ENUM);
+	DGLContext_getHostError(ctx);
+//	Dprintf("glBindTexture(%x, %d)\n", target, texture);
+	ctx->hgl.BindTexture(target, texture);
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		if(!DGLContext_bindTexture(ctx, target, texture))
+		{
+			DGLES2_ERROR(GL_OUT_OF_MEMORY);
+		}
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+static GLboolean dglIsValid2DTextureTarget(GLenum target)
+{
+	switch(target)
+	{
+		case GL_TEXTURE_2D:
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+		case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+		case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
+			return GL_TRUE;
+
+		default:
+			return GL_FALSE;
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValid2DTextureTarget(target), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsPalettedFormat(internalformat) &&
+					internalformat != GL_ETC1_RGB8_OES,
+					GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(height < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(width < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(border != 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(imageSize < 0, GL_INVALID_VALUE);
+	{
+		if(dglIsPalettedFormat(internalformat))
+		{
+			int num_levels, cur_level;
+			GLenum base_format;
+			DGLTexture* texture;
+
+			base_format = dglMapPalettedToBaseFormat(internalformat);
+			texture = DGLContext_getTexture(ctx, target);
+			DGLES2_ASSERT(texture != NULL);
+
+			DGLES2_ERROR_IF(level > 0, GL_INVALID_VALUE);
+			DGLES2_ERROR_IF(level < -ctx->max_texture_level, GL_INVALID_VALUE);
+
+			num_levels = -level + 1;
+			for(cur_level = 0; cur_level < num_levels; cur_level++)
+			{
+				if(data != NULL)
+				{
+					void* decompressed_data = dglDecompressPalettedTexture(cur_level, internalformat, width, height, imageSize, data);
+					if(decompressed_data == NULL)
+					{
+						DGLES2_ERROR(GL_OUT_OF_MEMORY);
+					}
+					ctx->hgl.TexImage2D(target, cur_level, base_format, width, height, border, base_format, GL_UNSIGNED_BYTE, decompressed_data);
+					free(decompressed_data);
+				}
+				else
+				{
+					ctx->hgl.TexImage2D(target, cur_level, base_format, width, height, border, base_format, GL_UNSIGNED_BYTE, NULL);
+				}
+				if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+				{
+					DGLTexture_setLevel(texture, target, level, internalformat, width, height);
+					DGLTexture_setEGLImage(texture, target, NULL);
+				}
+				width /= 2;
+				height /= 2;
+			}
+		}
+		else
+		{
+			void* decompressed_data;
+			int numblocks;
+
+			DGLES2_ASSERT(internalformat == GL_ETC1_RGB8_OES);
+
+			DGLES2_ERROR_IF(level < 0, GL_INVALID_VALUE);
+			DGLES2_ERROR_IF(level > ctx->max_texture_level, GL_INVALID_VALUE);
+
+			numblocks = ((width + 3) / 4) * ((height + 3) / 4);
+
+			if(imageSize != numblocks * 8)
+			{
+				DGLES2_ERROR(GL_INVALID_VALUE);
+			}
+
+			decompressed_data = dglDecompressETCTexture(width, height, data);
+			ctx->hgl.TexImage2D(target, level, GL_RGB, width, height, border, GL_RGB, GL_UNSIGNED_BYTE, decompressed_data);
+			free(decompressed_data);
+			if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+			{
+				DGLTexture* texture;
+				GLeglImageOES image;
+				
+				texture = DGLContext_getTexture(ctx, target);
+				DGLES2_ASSERT(texture != NULL);
+				DGLTexture_setLevel(texture, target, level, internalformat, width, height);
+				
+				image = DGLTexture_getEGLImage(texture, target);
+				if(image != NULL)
+				{
+					// Texture is respecified. It is no longer an EGLImage sibling.
+					deglUnregisterImageTarget(image, target, texture->obj.name);
+					DGLTexture_setEGLImage(texture, target, NULL);
+				}
+
+				{
+					DGLTextureLevel* level_obj = DGLTexture_getLevel(texture, target, level);
+					if(level_obj->bound_surface != NULL)
+					{
+						// Texture is respecified. Release the bound EGLSurface.
+						deglReleaseTexImage(level_obj->bound_surface, texture->obj.name, level);
+						level_obj->bound_surface = NULL;
+					}
+				}
+			}
+		}
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValid2DTextureTarget(target), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(level < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(level > ctx->max_texture_level, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(!dglIsPalettedFormat(format) && format != GL_ETC1_RGB8_OES, GL_INVALID_ENUM);
+	// No supported formats.
+	DGLES2_ERROR(GL_INVALID_OPERATION);
+	DGLES2_LEAVE();
+}
+
+static GLboolean dglIsValidFormat(GLenum format)
+{
+	switch(format)
+	{
+		case GL_ALPHA:
+		case GL_RGB:
+		case GL_RGBA:
+		case GL_LUMINANCE:
+		case GL_LUMINANCE_ALPHA:
+			return GL_TRUE;
+
+		default:
+			return GL_FALSE;
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glCopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValid2DTextureTarget(target), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(level < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(level > ctx->max_texture_level, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(!dglIsValidFormat(internalformat), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(border != 0, GL_INVALID_VALUE);
+	{
+		DGLContext_getHostError(ctx);
+
+		DGLES2_BEGIN_READING();
+		ctx->hgl.CopyTexImage2D(target, level, internalformat, x, y, width, height, border);	
+		DGLES2_END_READING();
+
+		if(DGLContext_getHostError(ctx) == GL_NO_ERROR) {
+			DGLTexture* texture;
+			GLeglImageOES image;
+			
+			texture = DGLContext_getTexture(ctx, target);
+			DGLES2_ASSERT(texture != NULL);
+			DGLTexture_setLevel(texture, target, level, internalformat, width, height);
+
+			image = DGLTexture_getEGLImage(texture, target);
+			if(image != NULL)
+			{
+				// Texture is respecified. It is no longer an EGLImage sibling.
+				deglUnregisterImageTarget(image, target, texture->obj.name);
+				DGLTexture_setEGLImage(texture, target, NULL);
+			}
+
+			{
+				DGLTextureLevel* level_obj = DGLTexture_getLevel(texture, target, level);
+				if(level_obj->bound_surface != NULL)
+				{
+					// Texture is respecified. Release the bound EGLSurface.
+					deglReleaseTexImage(level_obj->bound_surface, texture->obj.name, level);
+					level_obj->bound_surface = NULL;
+				}
+			}
+		}
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValid2DTextureTarget(target), GL_INVALID_ENUM);
+	{
+		DGLTextureLevel* level_obj = DGLContext_getTextureLevel(ctx, target, level);
+		DGLES2_ASSERT(level_obj != NULL);
+		if(dglIsPalettedFormat(level_obj->format) || level_obj->format == GL_ETC1_RGB8_OES)
+		{
+			DGLES2_ERROR(GL_INVALID_OPERATION);
+		}
+	}
+	DGLContext_getHostError(ctx);
+	DGLES2_BEGIN_READING();
+	ctx->hgl.CopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
+	DGLES2_END_READING();
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		DGLTexture* texture;
+		GLeglImageOES image;
+
+		texture = DGLContext_getTexture(ctx, target);
+		DGLES2_ASSERT(texture != NULL);
+		image = DGLTexture_getEGLImage(texture, target);
+		if(image != NULL)
+		{
+			deglUpdateImageSiblings(image, target, texture->obj.name);
+		}
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDeleteTextures(GLsizei n, const GLuint* textures)
+{
+	DGLES2_ENTER();
+	DGLContext_getHostError(ctx);
+	ctx->hgl.DeleteTextures(n, textures);
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		int i;
+		for(i = 0; i < n; i++)
+		{
+			DGLContext_destroyTexture(ctx, textures[n]);
+		}
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGenerateMipmap (GLenum target)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP, GL_INVALID_ENUM);
+	DGLContext_getHostError(ctx);
+	ctx->hgl.GenerateMipmapEXT(target);
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		DGLTexture* texture;
+		GLeglImageOES image;
+		
+		texture = DGLContext_getTexture(ctx, target);
+		DGLTexture_generateMipmap(texture);
+		image = DGLTexture_getEGLImage(texture, target);
+		if(image != NULL)
+		{
+			// Texture is respecified. It is no longer an EGLImage sibling.
+			deglUnregisterImageTarget(image, target, texture->obj.name);
+			DGLTexture_setEGLImage(texture, target, NULL);
+		}
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGenTextures(GLsizei n, GLuint* textures)
+{
+	DGLES2_ENTER();
+	ctx->hgl.GenTextures(n, textures);
+	DGLES2_LEAVE();
+}
+
+static GLboolean dglIsValidTextureParameter(GLenum pname)
+{
+	switch(pname)
+	{
+		case GL_TEXTURE_WRAP_S:
+		case GL_TEXTURE_WRAP_T:
+		case GL_TEXTURE_MIN_FILTER:
+		case GL_TEXTURE_MAG_FILTER:
+			return GL_TRUE;
+
+		default:
+			return GL_FALSE;
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetTexParameterfv(GLenum target, GLenum pname, GLfloat* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidTextureParameter(pname), GL_INVALID_ENUM);
+	ctx->hgl.GetTexParameterfv(target, pname, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetTexParameteriv(GLenum target, GLenum pname, GLint* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidTextureParameter(pname), GL_INVALID_ENUM);
+	ctx->hgl.GetTexParameteriv(target, pname, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD GLboolean GL_APIENTRY glIsTexture(GLuint texture)
+{
+	DGLES2_ENTER_RET(GL_FALSE);
+	DGLES2_LEAVE_RET(ctx->hgl.IsTexture(texture));
+}
+
+static GLfloat* dglConvertHalfTextureToFloat(GLsizei width, GLsizei height, GLenum format, const void* pixels)
+{
+	int components;
+	GLfloat* conv;
+	int i;
+
+	switch(format)
+	{
+		case GL_ALPHA:
+		case GL_LUMINANCE:
+			components = 1;
+			break;
+
+		case GL_LUMINANCE_ALPHA:
+			components = 2;
+			break;
+
+		case GL_RGB:
+			components = 3;
+			break;
+
+		case GL_RGBA:
+			components = 4;
+			break;
+
+		default:
+			DGLES2_ASSERT(GL_FALSE);
+	}
+
+	conv = malloc(width * height * components * sizeof(GLfloat));
+	if(conv == NULL)
+	{
+		return NULL;
+	}
+
+	for(i = 0; i < width * height * components; i++)
+	{
+		conv[i] = dglConvertHalfToFloat(((GLfixed*)pixels)[i]);
+	}
+
+	return conv;
+}
+
+static GLboolean dglIsValidType(GLenum type)
+{
+	switch(type)
+	{
+		case GL_UNSIGNED_BYTE:
+		case GL_UNSIGNED_SHORT_5_6_5:
+		case GL_UNSIGNED_SHORT_4_4_4_4:
+		case GL_UNSIGNED_SHORT_5_5_5_1:
+			return GL_TRUE;
+
+		default:
+			return GL_FALSE;
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValid2DTextureTarget(target), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(level < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(level > ctx->max_texture_level, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(dglIsPalettedFormat(internalformat), GL_INVALID_OPERATION);
+	DGLES2_ERROR_IF(!dglIsValidFormat(internalformat), GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(!dglIsValidFormat(format), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidType(type), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(border != 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(format != internalformat, GL_INVALID_OPERATION);
+	
+	DGLContext_getHostError(ctx);
+
+	if(pixels != NULL && type == GL_HALF_FLOAT_OES)
+	{
+		GLfloat* conv = dglConvertHalfTextureToFloat(width, height, format, pixels);
+		if(conv == NULL)
+		{
+			DGLES2_ERROR(GL_OUT_OF_MEMORY);
+		}
+		ctx->hgl.TexImage2D(target, level, internalformat, width, height, border, format, GL_FLOAT, conv);
+		free(conv);
+	}
+	else
+	{
+		ctx->hgl.TexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
+	}
+
+	if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+	{
+		DGLTexture* texture;
+		GLeglImageOES image;
+		
+		texture = DGLContext_getTexture(ctx, target);
+		DGLES2_ASSERT(texture != NULL);
+		DGLTexture_setLevel(texture, target, level, internalformat, width, height);
+
+		image = DGLTexture_getEGLImage(texture, target);
+		if(image != NULL)
+		{
+			// Texture is respecified. It is no longer an EGLImage sibling.
+			deglUnregisterImageTarget(image, target, texture->obj.name);
+			DGLTexture_setEGLImage(texture, target, NULL);
+		}
+
+		{
+			DGLTextureLevel* level_obj = DGLTexture_getLevel(texture, target, level);
+			if(level_obj->bound_surface != NULL)
+			{
+				// Texture is respecified. Release the bound EGLSurface.
+				deglReleaseTexImage(level_obj->bound_surface, texture->obj.name, level);
+				level_obj->bound_surface = NULL;
+			}
+		}
+	}
+
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glTexParameterf(GLenum target, GLenum pname, GLfloat param)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidTextureParameter(pname), GL_INVALID_ENUM);
+	ctx->hgl.TexParameterf(target, pname, param);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glTexParameterfv(GLenum target, GLenum pname, const GLfloat* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidTextureParameter(pname), GL_INVALID_ENUM);
+	ctx->hgl.TexParameterfv(target, pname, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glTexParameteri(GLenum target, GLenum pname, GLint param)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidTextureParameter(pname), GL_INVALID_ENUM);
+	ctx->hgl.TexParameteri(target, pname, param);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glTexParameteriv(GLenum target, GLenum pname, const GLint* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D && target != GL_TEXTURE_CUBE_MAP, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidTextureParameter(pname), GL_INVALID_ENUM);
+	ctx->hgl.TexParameteriv(target, pname, params);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(!dglIsValid2DTextureTarget(target), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(level < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(level > ctx->max_texture_level, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(!dglIsValidFormat(format), GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(!dglIsValidType(type), GL_INVALID_ENUM);
+	{
+		DGLTextureLevel* level_obj = DGLContext_getTextureLevel(ctx, target, level);
+		DGLES2_ASSERT(level_obj != NULL);
+		if(format != level_obj->format)
+		{
+			DGLES2_ERROR(GL_INVALID_OPERATION);
+		}
+
+		DGLContext_getHostError(ctx);
+
+		if(pixels != NULL && type == GL_HALF_FLOAT_OES)
+		{
+			GLfloat* conv = dglConvertHalfTextureToFloat(width, height, format, pixels);
+			if(conv == NULL)
+			{
+				DGLES2_ERROR(GL_OUT_OF_MEMORY);
+			}
+			ctx->hgl.TexSubImage2D(target, level, xoffset, yoffset, width, height, format, GL_FLOAT, conv);
+			free(conv);
+		}
+		else
+		{
+			ctx->hgl.TexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
+		}
+
+		if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+		{
+			DGLTexture* texture;
+			GLeglImageOES image;
+			
+			texture = DGLContext_getTexture(ctx, target);
+			DGLES2_ASSERT(texture != NULL);
+			image = DGLTexture_getEGLImage(texture, target);
+			if(image != NULL)
+			{
+				deglUpdateImageSiblings(image, target, texture->obj.name);
+			}
+		}
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glEGLImageTargetTexture2DOES(GLenum target, GLeglImageOES image)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(target != GL_TEXTURE_2D, GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(image == NULL, GL_INVALID_OPERATION);
+	{
+		// Clear all mipmap levels.
+		int level;
+		for(level = 0; level <= ctx->max_texture_level; level++)
+		{
+			ctx->hgl.TexImage2D(target, level, GL_RGBA, 0, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+		}
+
+		if(!DGLContext_specifyTextureFromEGLImage(ctx, image, target))
+		{
+			DGLES2_ERROR(GL_INVALID_OPERATION);
+		}
+
+		{
+			DGLTexture* texture = DGLContext_getTexture(ctx, target);
+			DGLTextureLevel* level_obj = DGLTexture_getLevel(texture, target, 0);
+			if(level_obj->bound_surface != NULL)
+			{
+				// Texture is respecified. Release the bound EGLSurface.
+				deglReleaseTexImage(level_obj->bound_surface, texture->obj.name, 0);
+				level_obj->bound_surface = NULL;
+			}
+		}
+	}
+	DGLES2_LEAVE_NO_ERROR_CHECK();
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/texture.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,70 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef TEXTURE_H_
+#define TEXTURE_H_
+
+typedef enum DGLTextureType
+{
+	DGLES2_TEXTURE_2D,
+	DGLES2_TEXTURE_CUBE_MAP
+} DGLTextureType;
+
+typedef struct DGLTextureLevel
+{
+	GLboolean specified;
+	GLenum format;
+	GLsizei width;
+	GLsizei height;
+	void* bound_surface; // The EGLSurface bound to this image with eglBindTexImage.
+} DGLTextureLevel;
+
+typedef struct DGLTexture
+{
+	struct DGLObject obj;
+
+	DGLTextureType type;
+
+	// One for each face in case of a cube map texture.
+	int num_levels[6];
+	DGLTextureLevel* levels[6];
+	GLeglImageOES egl_image[6]; // EGLimage this texture is a sibling of.
+} DGLTexture;
+
+DGLTexture*			DGLTexture_create(GLuint name, DGLTextureType type, GLint num_levels);
+void				DGLTexture_destroy(DGLTexture* texture);
+GLboolean			DGLTexture_isComplete(const DGLTexture* texture);
+GLboolean			DGLTexture_hasLevelZero(const DGLTexture* texture);
+GLboolean			DGLTexture_hasLevelsOtherThanZero(const DGLTexture* texture);
+DGLTextureLevel*	DGLTexture_getLevel(DGLTexture* texture, GLenum target, GLint level);
+void				DGLTexture_setLevel(DGLTexture* texture, GLenum target, GLint level, GLenum format, GLsizei width, GLsizei height);
+GLeglImageOES		DGLTexture_getEGLImage(DGLTexture* texture, GLenum target);
+void				DGLTexture_setEGLImage(DGLTexture* texture, GLenum target, GLeglImageOES image);
+void				DGLTexture_generateMipmap(DGLTexture* texture);
+
+#endif // TEXTURE_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/util.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,49 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "util.h"
+
+int dglLog2(unsigned int x)
+{
+	int r = 0;
+	while(x >>= 1)
+	{
+		r++;
+	}
+	return r;
+}
+
+int dglMin(int a, int b)
+{
+	return a < b ? a : b;
+}
+
+int dglMax(int a, int b)
+{
+	return a > b ? a : b;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/util.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,36 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef UTIL_H_
+#define UTIL_H_
+
+int dglLog2(unsigned int x);
+int dglMin(int a, int b);
+int dglMax(int a, int b);
+
+#endif  // UTIL_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/vertex.c	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,452 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#include "common.h"
+#include "hgl.h"
+#include "context.h"
+#include "vertex.h"
+#include "get.h"
+#include "half.h"
+
+#define DEBUG_VERTEX 0
+
+GLboolean dglGetVertexAttrib(const DGLContext *ctx, GLuint index, GLenum pname, DGLType type, void* params)
+{
+	GLint i;
+
+	switch(pname)
+	{
+		case GL_VERTEX_ATTRIB_ARRAY_ENABLED:
+			i = ctx->vertex_arrays[index].enabled;
+			break;
+
+		case GL_VERTEX_ATTRIB_ARRAY_SIZE:
+			i = ctx->vertex_arrays[index].size;
+			break;
+
+		case GL_VERTEX_ATTRIB_ARRAY_STRIDE:
+			i = ctx->vertex_arrays[index].stride;
+			break;
+
+		case GL_VERTEX_ATTRIB_ARRAY_TYPE:
+			i = ctx->vertex_arrays[index].type;
+			break;
+
+		case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED:
+			i = ctx->vertex_arrays[index].normalized;
+			break;
+
+		case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
+			i = ctx->vertex_arrays[index].buffer != NULL ? ctx->vertex_arrays[index].buffer->obj.name : 0;
+			break;
+
+		case GL_CURRENT_VERTEX_ATTRIB:
+			if(index == 0)
+			{
+				// Attribute zero can't be set in desktop GL.
+				if(type == DGLES2_TYPE_INT)
+				{
+					((GLint*)params)[0] = (GLint)ctx->attrib_zero[0];
+					((GLint*)params)[1] = (GLint)ctx->attrib_zero[1];
+					((GLint*)params)[2] = (GLint)ctx->attrib_zero[2];
+					((GLint*)params)[3] = (GLint)ctx->attrib_zero[3];
+				}
+				else
+				{
+					DGLES2_ASSERT(type == DGLES2_TYPE_FLOAT);
+					((GLfloat*)params)[0] = ctx->attrib_zero[0];
+					((GLfloat*)params)[1] = ctx->attrib_zero[1];
+					((GLfloat*)params)[2] = ctx->attrib_zero[2];
+					((GLfloat*)params)[3] = ctx->attrib_zero[3];
+				}
+			}
+			else
+			{
+				if(type == DGLES2_TYPE_INT)
+				{
+					ctx->hgl.GetVertexAttribiv(index, GL_CURRENT_VERTEX_ATTRIB, params);
+				}
+				else
+				{
+					DGLES2_ASSERT(type == DGLES2_TYPE_FLOAT);
+					ctx->hgl.GetVertexAttribfv(index, GL_CURRENT_VERTEX_ATTRIB, params);
+				}
+			}
+			return GL_TRUE;
+
+		default:
+			return GL_FALSE;
+	}
+
+	if(type == DGLES2_TYPE_INT)
+	{
+		*(GLint*)params = i;
+	}
+	else
+	{
+		DGLES2_ASSERT(type == DGLES2_TYPE_FLOAT);
+		*(GLfloat*)params = (GLfloat)i;
+	}
+
+	return GL_TRUE;
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDisableVertexAttribArray(GLuint index)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(index >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+#	if(DEBUG_VERTEX == 1)
+	Dprintf("Disabling array %d\n", index);
+#	endif
+	ctx->vertex_arrays[index].enabled = GL_FALSE;
+	ctx->hgl.DisableVertexAttribArray(index);
+	DGLES2_LEAVE();
+}
+
+// Function to convert fixed and half float arrays to float arrays.
+static void dglConvertArrays(DGLContext* ctx, GLint first, GLsizei count)
+{
+	unsigned int i;
+	for(i = 0; i < ctx->max_vertex_attribs; ++i)
+	{
+		DGLVertexArray* va = ctx->vertex_arrays + i;
+		if(!va->enabled)
+		{
+			continue;
+		}
+		{
+			if(va->type == GL_FIXED || va->type == GL_HALF_FLOAT_OES)
+			{
+				const void* ptr = va->buffer != NULL ? va->buffer->data : va->ptr;
+
+				GLsizei stride;
+				if(va->stride)
+				{
+					stride = va->stride;
+				}
+				else if(va->type == GL_FIXED)
+				{
+					stride = va->size * sizeof(GLfixed);
+				}
+				else
+				{
+					DGLES2_ASSERT(va->type == GL_HALF_FLOAT_OES);
+					stride = va->size * sizeof(khronos_int16_t);
+				}
+
+	#			if(DEBUG_VERTEX == 1)
+				Dprintf("Converting %d fixed/half float indices to float.\n", count);
+	#			endif
+
+				if(va->floatptr) free(va->floatptr);
+
+				va->floatptr = malloc(sizeof(GLfloat)*count*va->size);
+				{
+					GLsizei j;
+					for(j = 0; j < count; ++j)
+					{
+						signed k;
+						for(k = 0; k < va->size; ++k)
+						{
+							if(va->type == GL_FIXED)
+							{
+								va->floatptr[j*va->size + k] = ((GLfixed*)(((char*)ptr) + stride*(first + j)))[k] / 65536.0f;
+							}
+							else
+							{
+								khronos_int16_t half;
+								DGLES2_ASSERT(va->type == GL_HALF_FLOAT_OES);
+								half = ((khronos_int16_t*)(((char*)ptr) + stride*(first + j)))[k];
+								va->floatptr[j*va->size + k] = dglConvertHalfToFloat(half);
+							}
+						}
+					}
+				}
+				ctx->hgl.VertexAttribPointer(i, va->size, GL_FLOAT, va->normalized, 0, va->floatptr - first);
+			}
+		}
+	}
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDrawArrays(GLenum mode, GLint first, GLsizei count)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(first < 0, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(count < 0, GL_INVALID_VALUE);
+	dglConvertArrays(ctx, first, count);
+	DGLES2_BEGIN_DRAWING();
+	ctx->hgl.DrawArrays(mode, first, count);
+	DGLES2_END_DRAWING();
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glDrawElements(GLenum mode, GLsizei count, GLenum type, const void* indices)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(count < 0, GL_INVALID_VALUE);
+	{
+		GLsizei indice_size;
+		switch(type)
+		{
+			case GL_UNSIGNED_BYTE: indice_size = sizeof(GLubyte); break;
+			case GL_UNSIGNED_SHORT: indice_size = sizeof(GLushort); break;
+			default:
+			{
+				DGLES2_ERROR(GL_INVALID_ENUM);
+			}
+		}
+		dglConvertArrays(ctx, (GLint)((size_t)indices/indice_size), count);
+		DGLES2_BEGIN_DRAWING();
+		ctx->hgl.DrawElements(mode, count, type, indices);
+		DGLES2_END_DRAWING();
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glEnableVertexAttribArray(GLuint index)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(index >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+#	if(DEBUG_VERTEX == 1)
+	Dprintf("Enabling array %d\n", index);
+#	endif
+	ctx->vertex_arrays[index].enabled = GL_TRUE;
+	ctx->hgl.EnableVertexAttribArray(index);
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(index >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(!dglGetVertexAttrib(ctx, index, pname, DGLES2_TYPE_FLOAT, params))
+	{
+		DGLES2_ERROR(GL_INVALID_ENUM);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetVertexAttribiv(GLuint index, GLenum pname, GLint* params)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(index >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(!dglGetVertexAttrib(ctx, index, pname, DGLES2_TYPE_INT, params))
+	{
+		DGLES2_ERROR(GL_INVALID_ENUM);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glGetVertexAttribPointerv(GLuint index, GLenum pname, void** pointer)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(index >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(pname != GL_VERTEX_ATTRIB_ARRAY_POINTER, GL_INVALID_ENUM);
+	*pointer = (void*)ctx->vertex_arrays[index].ptr;
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttrib1f(GLuint indx, GLfloat x)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(indx == 0)
+	{
+		// Attribute zero can't be set in desktop GL.
+		ctx->attrib_zero[0] = x;
+	}
+	else
+	{
+		ctx->hgl.VertexAttrib1f(indx, x);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttrib1fv(GLuint indx, const GLfloat* values)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(indx == 0)
+	{
+		// Attribute zero can't be set in desktop GL.
+		ctx->attrib_zero[0] = values[0];
+	}
+	else
+	{
+		ctx->hgl.VertexAttrib1fv(indx, values);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttrib2f(GLuint indx, GLfloat x, GLfloat y)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(indx == 0)
+	{
+		// Attribute zero can't be set in desktop GL.
+		ctx->attrib_zero[0] = x;
+		ctx->attrib_zero[1] = y;
+	}
+	else
+	{
+		ctx->hgl.VertexAttrib2f(indx, x, y);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttrib2fv(GLuint indx, const GLfloat* values)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(indx == 0)
+	{
+		// Attribute zero can't be set in desktop GL.
+		ctx->attrib_zero[0] = values[0];
+	}
+	else
+	{
+		ctx->hgl.VertexAttrib2fv(indx, values);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(indx == 0)
+	{
+		// Attribute zero can't be set in desktop GL.
+		ctx->attrib_zero[0] = x;
+		ctx->attrib_zero[1] = y;
+		ctx->attrib_zero[2] = z;
+	}
+	else
+	{
+		ctx->hgl.VertexAttrib3f(indx, x, y, z);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttrib3fv(GLuint indx, const GLfloat* values)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(indx == 0)
+	{
+		// Attribute zero can't be set in desktop GL.
+		ctx->attrib_zero[0] = values[0];
+		ctx->attrib_zero[1] = values[1];
+		ctx->attrib_zero[2] = values[2];
+	}
+	else
+	{
+		ctx->hgl.VertexAttrib3fv(indx, values);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(indx == 0)
+	{
+		// Attribute zero can't be set in desktop GL.
+		ctx->attrib_zero[0] = x;
+		ctx->attrib_zero[1] = y;
+		ctx->attrib_zero[2] = z;
+		ctx->attrib_zero[3] = w;
+	}
+	else
+	{
+		ctx->hgl.VertexAttrib4f(indx, x, y, z, w);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttrib4fv(GLuint indx, const GLfloat* values)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	if(indx == 0)
+	{
+		// Attribute zero can't be set in desktop GL.
+		ctx->attrib_zero[0] = values[0];
+		ctx->attrib_zero[1] = values[1];
+		ctx->attrib_zero[2] = values[2];
+		ctx->attrib_zero[3] = values[3];
+	}
+	else
+	{
+		ctx->hgl.VertexAttrib4fv(indx, values);
+	}
+	DGLES2_LEAVE();
+}
+
+GL_APICALL_BUILD void GL_APIENTRY glVertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr)
+{
+	DGLES2_ENTER();
+	DGLES2_ERROR_IF(indx >= ctx->max_vertex_attribs, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(size < 1 || size > 4, GL_INVALID_VALUE);
+	DGLES2_ERROR_IF(type != GL_BYTE &&
+					type != GL_UNSIGNED_BYTE &&
+					type != GL_SHORT &&
+					type != GL_UNSIGNED_SHORT &&
+					type != GL_FIXED &&
+					type != GL_FLOAT &&
+					type != GL_HALF_FLOAT_OES, 
+					GL_INVALID_ENUM);
+	DGLES2_ERROR_IF(stride < 0, GL_INVALID_VALUE);
+#	if(DEBUG_VERTEX == 1)
+	Dprintf("Array %d at %p (%d elements every %d bytes)\n", indx, ptr, size, stride);
+#	endif
+
+	{
+		DGLVertexArray* va = ctx->vertex_arrays + indx;
+
+		if(type != GL_FIXED && type != GL_HALF_FLOAT_OES)
+		{
+			ctx->hgl.VertexAttribPointer(indx, size, type, normalized, stride, ptr);
+		}
+
+		if(DGLContext_getHostError(ctx) == GL_NO_ERROR)
+		{
+			va->size = size;
+			va->type = type;
+			va->normalized = normalized;
+			va->stride = stride;
+			va->ptr = ptr;
+			
+			va->buffer = DGLContext_findBuffer(ctx, ctx->buffer_binding);
+		}
+	}
+	DGLES2_LEAVE();
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/GLES2/vertex.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,53 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef VERTEX_H_
+#define VERTEX_H_
+
+#include "hgl.h"
+
+struct DGLBuffer;
+
+// GLES Vertex array data holder.
+typedef struct DGLVertexArray
+{
+	GLint size;					// Function call argument.
+	GLenum type;				// --''--
+	GLboolean normalized;		// --''--
+	GLsizei stride;				// --''--
+	const void* ptr;			// --''--
+	
+	GLboolean enabled;			// State.
+	GLfloat* floatptr;			// Buffer for fixed->float conversion.
+	struct DGLBuffer* buffer;	// Buffer binding.
+} DGLVertexArray;
+
+extern void dglVertexFinish();
+
+#endif // VERTEX_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopengles20/src/include/common.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,263 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included
+ * in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+ * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef COMMON_H_
+#define COMMON_H_
+
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+// Correct defines for platform detection.
+#if(CONFIG_X11 == 1)
+#	ifndef __unix__
+#		define __unix__
+#	endif
+#elif(CONFIG_OFFSCREEN == 1)
+#	define __offscreen__
+#elif(CONFIG_WIN32 == 1)
+#	define __win32__
+#else
+#	error "Backend needs to be enabled!"
+#endif // else
+
+// DLL-mangling.
+#ifdef _WIN32
+#	define DGLES2_EXPORT __declspec(dllexport)
+#	define DGLES2_IMPORT __declspec(dllimport)
+#	define DGLES2_CALL	 __stdcall
+#else
+#	define DGLES2_EXPORT
+#	define DGLES2_IMPORT extern
+#	define DGLES2_CALL
+#endif
+
+// For proper imports and exports.
+#if(defined BUILD_EGL)
+#	define EGLAPI       extern
+#	define EGLAPI_BUILD DGLES2_EXPORT
+#elif(defined BUILD_GLES2)
+#	define GL_APICALL       DGLES2_EXPORT
+#	define GL_APICALL_BUILD DGLES2_EXPORT
+#else
+#	error "Only to be used with EGL or GLES!"
+#endif
+
+// The actual standard headers.
+#include "EGL/egl.h"
+#include "GLES2/gl2.h"
+#include "GLES2/gl2ext.h"
+
+// For malloc
+#ifdef __APPLE__
+#	include <stdlib.h>
+#else
+#	include <malloc.h>
+#endif
+
+// Debug location aids.
+#ifdef _MSC_VER
+#	define __PRETTY_FUNCTION__ __FUNCSIG__
+#	ifdef _DEBUG
+#		define CONFIG_DEBUG 1
+#	endif
+#else
+#   if !defined(NDEBUG)
+#       define CONFIG_DEBUG 1
+#   endif
+#endif
+
+#define COMMON_STAMP_FMT "%s:%d(%s)"
+#define COMMON_STAMP_ARGS ,(strchr(__FILE__, '/')?"":__FILE__), __LINE__, __PRETTY_FUNCTION__
+
+#define DUMMY() \
+	fprintf(stderr, "\x1b[41mDUMMY\x1b[0m " COMMON_STAMP_FMT ": Unimplemented!\n" COMMON_STAMP_ARGS)
+#define STUB_ONCE(format, ...) \
+	{ \
+		static int once = 1; \
+		if(once) \
+		{ \
+			fprintf(stderr, "\x1b[43mSTUB ONCE\x1b[0m " COMMON_STAMP_FMT ": " format COMMON_STAMP_ARGS, __VA_ARGS__); \
+			once = 0; \
+		} \
+	} (void) 0
+#define STUB(format, ...) \
+	fprintf(stderr, "STUB " COMMON_STAMP_FMT ": " format COMMON_STAMP_ARGS, __VA_ARGS__)
+
+#if(CONFIG_DEBUG == 1 && !defined NDEBUG)
+#	define Dprintf(format, ...) fprintf(stderr, "DEBUG " COMMON_STAMP_FMT ": " format  COMMON_STAMP_ARGS, __VA_ARGS__)
+#else // NDEBUG
+#	define Dprintf(format, ...) (void)0
+#endif // !NDEBUG
+
+#if(CONFIG_DEBUG == 1 && !defined NDEBUG)
+#	define DGLES2_ASSERT assert
+#else
+#	define DGLES2_ASSERT
+#endif
+
+// Context acquisition
+#define DGLES2_NO_RETVAL ;
+
+#define DGLES2_ENTER_RET(retval) \
+	DGLContext* ctx; \
+	{ \
+		dglGetLock(); \
+		ctx = deglGetCurrentContext(); \
+		if(!ctx) \
+		{ \
+			dglReleaseLock(); \
+			return retval; \
+		} \
+		if(!ctx->initialized) \
+		{ \
+			if(!DGLContext_initialize(ctx)) \
+			{ \
+				dglReleaseLock(); \
+				return retval; \
+			} \
+		} \
+	} (void) 0
+
+// Check the host error API function calls so that the error flag
+// in the wrapper always contains the latest error.
+#define DGLES2_LEAVE_RET(retval) \
+	{ \
+		DGLContext_getHostError(ctx); \
+		dglReleaseLock(); \
+		return retval; \
+	} (void) 0
+
+// Error checking is not necessary when DGLContext_getHostError was already
+// called at the end of the function body. Also, the EGL<->GLES interface
+// functions should preserve the error flag, so this macro should be used there.
+#define DGLES2_LEAVE_NO_ERROR_CHECK_RET(retval) \
+	{ \
+		dglReleaseLock(); \
+		return retval; \
+	} (void) 0
+
+#define DGLES2_ENTER() DGLES2_ENTER_RET(DGLES2_NO_RETVAL)
+#define DGLES2_LEAVE() DGLES2_LEAVE_RET(DGLES2_NO_RETVAL)
+#define DGLES2_LEAVE_NO_ERROR_CHECK() DGLES2_LEAVE_NO_ERROR_CHECK_RET(DGLES2_NO_RETVAL)
+
+// Surface locking
+#define DGLES2_LOCK_SURFACE_RET(read, draw, retval) \
+	do \
+	{ \
+		if(!deglLockSurface(read, draw)) \
+		{ \
+			DGLES2_LEAVE_NO_ERROR_CHECK_RET(retval); \
+		} \
+	} while(0)
+
+#define DGLES2_LOCK_DRAW_SURFACE_RET(retval) DGLES2_LOCK_SURFACE_RET(0, 1, retval)
+#define DGLES2_LOCK_READ_SURFACE_RET(retval) DGLES2_LOCK_SURFACE_RET(1, 0, retval)
+
+#define DGLES2_UNLOCK_SURFACE_RET(retval) \
+	do \
+	{ \
+		if(!deglUnlockSurface()) \
+		{ \
+			DGLES2_LEAVE_RET(retval); \
+		} \
+	} while(0)
+
+#define DGLES2_UNLOCK_SURFACE() DGLES2_UNLOCK_SURFACE_RET(DGLES2_NO_RETVAL)
+
+#define DGLES2_BEGIN_DRAWING_RET(retval) \
+	do \
+	{ \
+		if(ctx->framebuffer_binding == 0) \
+		{ \
+			/* Using default framebuffer. */ \
+			DGLES2_LOCK_DRAW_SURFACE_RET(retval); \
+		} \
+	} while(0)
+
+#define DGLES2_BEGIN_DRAWING() DGLES2_BEGIN_DRAWING_RET(DGLES2_NO_RETVAL)
+
+#define DGLES2_END_DRAWING_RET(retval) \
+	do \
+	{ \
+		if(ctx->framebuffer_binding == 0) \
+		{ \
+			/* Using default framebuffer. */ \
+			DGLES2_UNLOCK_SURFACE_RET(retval); \
+		} \
+		else \
+		{ \
+			/* Using user-created framebuffer. */ \
+			DGLContext_updateFBOAttachmentSiblings(ctx); \
+		} \
+	} while(0)
+
+#define DGLES2_END_DRAWING() DGLES2_END_DRAWING_RET(DGLES2_NO_RETVAL)
+
+#define DGLES2_BEGIN_READING_RET(retval) \
+	do \
+	{ \
+		if(ctx->framebuffer_binding == 0) \
+		{ \
+			/* Using default framebuffer. */ \
+			DGLES2_LOCK_READ_SURFACE_RET(retval); \
+		} \
+	} while(0)
+
+#define DGLES2_BEGIN_READING() DGLES2_BEGIN_READING_RET(DGLES2_NO_RETVAL)
+
+#define DGLES2_END_READING_RET(retval) \
+	do \
+	{ \
+		if(ctx->framebuffer_binding == 0) \
+		{ \
+			/* Using default framebuffer. */ \
+			DGLES2_UNLOCK_SURFACE_RET(retval); \
+		} \
+	} while(0)
+
+#define DGLES2_END_READING() DGLES2_END_READING_RET(DGLES2_NO_RETVAL)
+
+// GL error handling
+#define DGLES2_ERROR_IF_RET(cond, error_, retval) \
+	{ \
+		if(cond) \
+		{ \
+			/* Clear the host GL error flag(s). */ \
+			while(ctx->hgl.GetError() != GL_NO_ERROR); \
+			DGLContext_setError(ctx, error_); \
+			dglReleaseLock(); \
+			return retval; \
+		} \
+	} (void) 0
+
+#define DGLES2_ERROR_IF(cond, error) DGLES2_ERROR_IF_RET(cond, error, DGLES2_NO_RETVAL)
+#define DGLES2_ERROR_RET(error, retval) DGLES2_ERROR_IF_RET(1, error, retval)
+#define DGLES2_ERROR(error) DGLES2_ERROR_IF(1, error)
+
+#endif /* COMMON_H_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/CMakeLists.txt	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,201 @@
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+# CMake meta build file for host libOpenVG
+
+set(SF_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)
+
+# Some of the source files are generated using scripts. Check if the
+# scripts were modified and rebuild if necessary.
+set(ALPHA_RCP_GEN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/genheader/make_alpha_rcp.py)
+set(GAMMA_LUT_GEN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/genheader/make_gamma_lut.py)
+
+set(ALPHA_RCP_FILE ${SF_SRC_DIR}/sfAlphaRcp.h)
+set(GAMMA_LUT_FILE ${SF_SRC_DIR}/sfGammaLUT.h)
+
+add_custom_command(
+    OUTPUT ${ALPHA_RCP_FILE}
+    COMMAND python ${ALPHA_RCP_GEN_FILE} > ${ALPHA_RCP_FILE}
+    DEPENDS ${ALPHA_RCP_GEN_FILE})
+
+add_custom_command(
+    OUTPUT ${GAMMA_LUT_FILE}
+    COMMAND python ${GAMMA_LUT_GEN_FILE} > ${GAMMA_LUT_FILE}
+    DEPENDS ${GAMMA_LUT_GEN_FILE})
+
+# Required in Linux and for LLVM compilation:
+# \todo LLVM script uses the flags differently, so they must be manually changed!
+set(GCC_SSE_FLAGS "-msse2 -mfpmath=sse -march=pentium4")
+
+# Win32 vs. Linux settings
+if(WIN32)
+	message("*** openvg_sg Win32")
+	set(SF_SSE_FLAGS "/arch:SSE2")
+	set(SF_PLATFORM_LINK_LIBRARIES "")
+    set(C_WARNING_FLAGS "")
+	add_definitions(-DOPENVG_DLL_EXPORTS -DNOMINMAX)
+
+	set(GLUT_LIBRARY "")
+	set(GLUT_INCLUDE_DIR "")
+
+    set(LIB_TYPE SHARED)
+    
+else(WIN32)
+	set(SF_SSE_FLAGS ${GCC_SSE_FLAGS})
+	set(SF_PLATFORM_LINK_LIBRARIES m stdc++)
+    set(C_WARNING_FLAGS "-Wall -std=c99 -pedantic-errors -Wno-variadic-macros -Wno-long-long -Wextra")
+    set(CXX_WARNING_FLAGS "-Wall -std=c++98 -pedantic-errors -Wno-variadic-macros -Wno-long-long -Wextra")
+
+    # Easier debugging on linux
+    # \todo Just use BUILD_SHARED_LIBRARIES: This way debug builds can be made with static
+    # and release with dynamic linking.
+    set(LIB_TYPE SHARED)
+
+	find_library(GLUT_LIBRARY glut)
+	find_path(GLUT_INCLUDE_DIR GL/glut.h)
+endif(WIN32)
+
+
+set(VG_SF_SRC_FILES
+  ${SF_SRC_DIR}/sfEGLInterface.h
+  ${SF_SRC_DIR}/sfEGLInterface.cpp
+  ${SF_SRC_DIR}/riApi.cpp
+  ${SF_SRC_DIR}/riArray.h
+  ${SF_SRC_DIR}/riContext.cpp
+  ${SF_SRC_DIR}/riContext.h
+  ${SF_SRC_DIR}/riDefs.h
+  ${SF_SRC_DIR}/riFont.cpp
+  ${SF_SRC_DIR}/riUtils.h
+  ${SF_SRC_DIR}/riUtils.cpp
+  ${SF_SRC_DIR}/riFont.h
+  ${SF_SRC_DIR}/riImage.cpp
+  ${SF_SRC_DIR}/riImage.h
+  ${SF_SRC_DIR}/riMath.cpp
+  ${SF_SRC_DIR}/riMath.h
+  ${SF_SRC_DIR}/riPath.cpp
+  ${SF_SRC_DIR}/riPath.h
+  ${SF_SRC_DIR}/riPixelPipe.cpp
+  ${SF_SRC_DIR}/riPixelPipe.h
+  ${SF_SRC_DIR}/riRasterizer.cpp
+  ${SF_SRC_DIR}/riRasterizer.h
+  ${SF_SRC_DIR}/riVGU.cpp
+  ${SF_SRC_DIR}/sfMask.h
+  ${SF_SRC_DIR}/sfDynamicPixelPipe.h
+  ${SF_SRC_DIR}/sfDynamicPixelPipe.cpp
+  ${SF_SRC_DIR}/sfBlitter.h
+  ${SF_SRC_DIR}/sfBlitter.cpp
+  ${SF_SRC_DIR}/sfDynamicBlitter.h
+  ${SF_SRC_DIR}/sfDynamicBlitter.cpp
+  ${SF_SRC_DIR}/sfFunctionCache.h
+  ${SF_SRC_DIR}/sfCompiler.h
+  ${SF_SRC_DIR}/sfCompiler.cpp
+  ${ALPHA_RCP_FILE}
+  ${GAMMA_LUT_FILE}
+  )
+
+# This VG requires OpenGL to render into window
+find_package(OpenGL)
+
+# pthreads on linux, native threads on win32?
+# \note Porting...
+find_package(Threads)
+
+include_directories(
+    ${SF_SRC_DIR}
+    ${COMMON_INC_DIR}
+    ${COMMON_INC_DIR}/VG
+    ${LLVM_INCLUDE_DIR}
+    ${CMAKE_CURRENT_BINARY_DIR}
+  )
+
+# -fvisibility=hidden?
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SF_SSE_FLAGS} ${C_WARNING_FLAGS}")
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SF_SSE_FLAGS} ${CXX_WARNING_FLAGS}")
+# These preprocessor flags were defined in the visual studio project file:
+# RI_COMPILE_LLVM_BYTECODE;WIN32;NDEBUG;_WINDOWS;_USRDLL;LIBOPENVG_EXPORTS;OPENVG_DLL_EXPORTS;__STDC_LIMIT_MACROS;__STDC_CONSTANT_MACROS;_CRT_SECURE_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;CRT_NONSTDC_NO_WARNINGS;_SCL_SECURE_NO_DEPRECATE
+
+# \note This compiles the full version (nothing is generated)
+add_definitions(-D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS -DRI_COMPILE_LLVM_BYTECODE)
+
+# LLVM bitcode files. \todo Create a macro to add these (LLVMTarget has some
+# code that needs expansion, especially on the dependencies, which aren't
+# handled well enough for our use.
+set(BC_CFLAGS ${BC_CFLAGS} -DNDEBUG -O1 -msse2 -mfpmath=sse -march=pentium4 -c -emit-llvm -I${COMMON_INC_DIR} )
+
+# This macro assumes that a pixelpipe is generated from one source-code file atm.
+macro(make_pixelpipe target_name input_file output_file array_name)
+    set(BINARY_PIXELPIPE_DIR ${CMAKE_CURRENT_BINARY_DIR})
+    set(BINARY_PIXELPIPE_TARGET ${target_name})
+    set(BINARY_PIXELPIPE_FILE ${CMAKE_CURRENT_BINARY_DIR}/${BINARY_PIXELPIPE_TARGET}.bc)
+    set(BINARY_PIXELPIPE_HEADER ${BINARY_PIXELPIPE_DIR}/${output_file})
+
+    set_source_files_properties(${BINARY_PIXELPIPE_HEADER}
+        PROPERTIES GENERATED true)
+
+    set(LLVM_PIXELPIPE_FILES ${SF_SRC_DIR}/${input_file})
+
+    # Note: Adds all project files as dependency to bitcode file.
+    add_custom_command(
+        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${input_file}.bc
+        COMMAND ${LLVM_CC} ARGS ${BC_CFLAGS} -o ${CMAKE_CURRENT_BINARY_DIR}/${input_file}.bc ${LLVM_PIXELPIPE_FILES}
+        DEPENDS ${LLVM_PIXELPIPE_FILES} ${VG_SF_SRC_FILES}
+    )
+
+    add_custom_command(
+        OUTPUT ${BINARY_PIXELPIPE_FILE}
+        COMMAND ${LLVM_LINK} ARGS -f -o ${BINARY_PIXELPIPE_FILE} ${CMAKE_CURRENT_BINARY_DIR}/${input_file}.bc
+        DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${input_file}.bc
+    )
+
+    set(BINARY_PIXELPIPE_HEADER_DEPS ${BINARY_PIXELPIPE_FILE})
+
+    if(CMAKE_BUILD_TYPE STREQUAL Debug)
+        add_custom_command(
+            OUTPUT ${BINARY_PIXELPIPE_FILE}.disasm
+            COMMAND ${LLVM_DIS} ARGS ${BINARY_PIXELPIPE_FILE} -f -o ${BINARY_PIXELPIPE_FILE}.disasm
+            DEPENDS ${BINARY_PIXELPIPE_FILE}
+        )
+        set(BINARY_PIXELPIPE_HEADER_DEPS ${BINARY_PIXELPIPE_DEPS} ${BINARY_PIXELPIPE_FILE}.disasm)
+    endif()
+
+    add_custom_command(
+        OUTPUT ${BINARY_PIXELPIPE_HEADER}
+        COMMAND python ${PROJECT_SOURCE_DIR}/vg/bin/bin2h.py ${BINARY_PIXELPIPE_FILE} ${array_name} > ${BINARY_PIXELPIPE_HEADER}
+        DEPENDS ${BINARY_PIXELPIPE_HEADER_DEPS}
+    )
+
+    set(VG_SF_SRC_FILES ${VG_SF_SRC_FILES} ${BINARY_PIXELPIPE_HEADER})
+endmacro(make_pixelpipe)
+
+make_pixelpipe(llvm_pixelpipe sfDynamicPixelPipe.cpp binaryPixelPipe.h integerPixelPipe_binary)
+make_pixelpipe(llvm_blitter sfDynamicBlitter.cpp binaryBlitter.h integerBlitter_binary)
+
+add_library(${LIBRARY_NAME_PREFIX}OpenVG ${LIB_TYPE} ${VG_SF_SRC_FILES})
+
+set_target_properties(${LIBRARY_NAME_PREFIX}OpenVG PROPERTIES LINK_INTERFACE_LIBRARIES "")
+
+target_link_libraries(${LIBRARY_NAME_PREFIX}OpenVG ${SF_PLATFORM_LINK_LIBRARIES} ${OPENGL_LIBRARIES} ${GLUT_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ${LLVM_JIT_LIBS})
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/genheader/bin2h.py	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,48 @@
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+
+from c_utils import *
+import sys
+import array
+import os.path
+
+def doit():
+    # \todo There's got to be some easier way to do this...
+    inputname = sys.argv[1]
+    arrayname = sys.argv[2]
+    f = file(inputname, 'rb')
+    d = f.read()
+    f.close
+    sz = len(d)
+    i = 0
+    items = []
+    for x in d:
+        items += [str(ord(x))]
+
+    justname = os.path.split(inputname)[1]
+    begin_include_guard(get_include_guard_name(justname + ".h"))
+    make_generation_notice()
+    make_array("static const", "unsigned char", arrayname, items, empty_format, 16)
+    end_include_guard()
+
+if __name__ == '__main__':
+    doit()
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/genheader/c_utils.py	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,72 @@
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+
+def get_include_guard_name(filename):
+    return "__" + filename.upper().replace('.', '_')
+
+def begin_include_guard(defstring):
+    print "#ifndef " + defstring
+    print "#define " + defstring
+
+def end_include_guard():
+    print "#endif\n"
+
+def make_constant(c, v):
+    print "enum { " + str(c) + " = " + str(v) + "};"
+    
+def make_include(fname):
+    print "#include \"" + str(fname) + "\""
+
+def make_generation_notice():
+    print "// This file is automatically generated. Please do not edit."
+
+def begin_namespace(name):
+    print "namespace " + str(name) + " {"
+
+def end_namespace():
+    print "}"
+
+def hex_formatter(i):
+    return hex(i)
+
+def empty_format(i):
+    return str(i)
+
+def make_array(qualifiers, type, name, data, ffn = empty_format, items_per_line = 8):
+    
+    print qualifiers,
+    print type,
+    print name + '[' + str(len(data)) + '] = {'
+    formatted_items = map(ffn, data)
+    s = 0
+    for i in formatted_items:
+        t = ""
+        if s == 0:
+            t = "    "
+        print t + i + ", ",
+        s += 1
+        if s == items_per_line:
+            print ""
+            s = 0
+    print "};"
+    return len(formatted_items)
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/genheader/make_alpha_rcp.py	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,78 @@
+#! /usr/bin/python
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+
+from c_utils import *
+
+# \todo Might require a more accurate table for lookups.
+
+RCP_BITS = 8
+RCP_DATATYPE_BITS = RCP_BITS + 8
+
+def tofx(f):
+    return int(f * (1<<RCP_BITS) + 0.5)
+
+def alpha_to_uintrcp(alpha):
+    if alpha == 0:
+        rf = 255 # Max out
+    else:
+        rf = 255.0/alpha
+    i = tofx(rf)
+    assert(i < (1<<RCP_DATATYPE_BITS))
+    return i
+
+def test_error():
+    max_err = 0
+    for alpha in range(1, 256):
+        for color in range(0, 256):
+            if color > alpha:
+                # Undefined result -> ignore test.
+                continue
+            fa = alpha / 255.0
+            fc = color / 255.0
+            ex = fc / fa
+            exi = int(ex * 255.0 + 0.5)
+            ia = alpha_to_uintrcp(alpha)
+            m = (ia * color) >> RCP_BITS
+            e = abs(exi - m)
+            if e > max_err:
+                print ia * color
+                print alpha, color, exi, m, fa, fc, ex, ia / float(1<<RCP_BITS), ia
+                max_err = e
+    print max_err
+    return max_err
+
+if __name__ == '__main__':
+    vals = []
+    for alpha in range(0, 256):
+       i = alpha_to_uintrcp(alpha)
+       vals += [i]
+    
+    begin_include_guard("_SFALPHARCP_H_") 
+    print ""
+    make_include("riDefs.h")
+    print ""
+    begin_namespace("OpenVGRI")
+    make_constant("ALPHA_RCP_BITS", RCP_BITS)
+    make_array("static const", "RIuint16", "sc_alphaRcp", vals, hex_formatter)
+    end_namespace()
+    end_include_guard()
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/genheader/make_gamma_lut.py	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,81 @@
+#! /usr/bin/python
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+
+# Extremely coarse lrgb<->srgb conversion table generation
+
+from c_utils import *
+
+GAMMA_BITS = 8
+
+def linear_to_gamma(f):
+    if f <= 0.00304:
+        return 12.92 * f
+    return 1.0556*pow(f, 1/2.4) - 0.0556
+
+def gamma_to_linear(f):
+    if f <= 0.03928:
+        return f / 12.92
+    return pow((f+0.0556)/1.0556, 2.4)
+
+def clamp(i, mn, mx):
+    if i < mn:
+        return mn
+    if i > mx:
+        return mx
+    return i
+
+def icolortof(i):
+    return i / 255.0
+
+def fcolortoi(f):
+    return int(f * ((1<<GAMMA_BITS)-1) + 0.5)
+
+all_components = range(0,256)
+all_floats = map(icolortof, all_components)
+
+def make_color_list(conv_func):
+    return map(fcolortoi, map(conv_func, all_floats))
+
+def make_lut_array(name, data):
+    make_array("static const", "RIuint8", name, data, hex_formatter)  
+
+def print_lrgb_to_srgb_table():
+    make_lut_array("sc_lRGB_to_sRGB", make_color_list(linear_to_gamma))
+
+def print_srgb_to_lrgb_table():
+    make_lut_array("sc_sRGB_to_lRGB", make_color_list(gamma_to_linear))
+
+def print_lookups():
+    begin_include_guard("_SFGAMMARCP_H_") 
+    print ""
+    make_include("riDefs.h")
+    print ""
+    begin_namespace("OpenVGRI")
+    print_srgb_to_lrgb_table()
+    print ""
+    print_lrgb_to_srgb_table()
+    end_namespace()
+    end_include_guard()
+
+if __name__ == '__main__':
+    print_lookups()
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/genheader/plot-edges.py	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,91 @@
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+#
+# 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.
+
+import sys
+import matplotlib
+matplotlib.use("wxAgg")
+import matplotlib.pyplot
+import lines
+
+
+if __name__ == '__main__':
+
+    start = 0
+    if len(sys.argv) > 2:
+        start = int(sys.argv[1])
+
+    minx = 65535.
+    miny = 65535.
+    maxx = -65535.
+    maxy = -65535.
+
+    z = zip(lines.lines[::2], lines.lines[1::2]) 
+
+    if len(sys.argv) == 2:
+        end = int(sys.argv[1])
+    elif len(sys.argv) > 2:
+        end = int(sys.argv[2])
+    else:
+        assert(len(sys.argv) == 1)
+        end = len(z)
+
+    print start, end
+
+    legend = False
+    if end - start < 10:
+        legend = True
+
+    for seg in z:
+        px0 = seg[0][0]/128.
+        py0 = seg[0][1]/8.
+        px1 = seg[1][0]/128.
+        py1 = seg[1][1]/8.
+        minx = min(px0, minx)
+        miny = min(py0, miny)
+        maxx = max(px0, maxx)
+        maxy = max(py0, maxy)
+        minx = min(px1, minx)
+        miny = min(py1, miny)
+        maxx = max(px1, maxx)
+        maxy = max(py1, maxy)
+
+    currLegend = 0
+    for seg in z[start:end]:
+        px0 = seg[0][0]/128.
+        py0 = seg[0][1]/8.
+        px1 = seg[1][0]/128.
+        py1 = seg[1][1]/8.
+
+        if not legend:
+            matplotlib.pyplot.plot([px0, px1], [py0, py1])
+        else:
+            matplotlib.pyplot.plot([px0, px1], [py0, py1], label = str(currLegend))
+            currLegend += 1
+
+    minx = min(minx, miny)
+    maxx = max(maxx, maxy)
+    
+    #matplotlib.pyplot.plot(x, y)
+    matplotlib.pyplot.axis([minx,maxx,minx,maxx])
+    if legend:
+        matplotlib.pyplot.legend()
+    matplotlib.pyplot.show()
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riApi.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,3839 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementations of OpenVG API functions.
+ * \note	The actual processing is done in Path, Image, Rasterizer and PixelPipe classes.
+ *//*-------------------------------------------------------------------*/
+
+#include "openvg.h"
+#include "vgext.h"
+#include "riContext.h"
+#include "riRasterizer.h"
+#include "riPixelPipe.h"
+#include "riPath.h"
+#include <stdio.h>
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/* EGL&OS functions for use in an OpenVG implementation */
+// \note To ensure that different EGLs work in parallel, these functions must be implemented.
+// They may be wrappers if the underlying EGL is more complicated that miniEGL.
+void* eglvgGetCurrentVGContext(void);
+bool  eglvgIsInUse(void* image);
+bool  eglvgLockSurface(bool read, bool write);
+bool  eglvgUnlockSurface();
+void  OSAcquireMutex(void);
+void  OSReleaseMutex(void);
+void  eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride );
+void*  eglvgGetImageData( void* image );
+
+#define RI_NO_RETVAL
+
+//this must be the first line in an API function
+#define RI_GET_CONTEXT(RETVAL) \
+    OSAcquireMutex(); \
+    VGContext* context = (VGContext*)eglvgGetCurrentVGContext(); \
+    if(!context) \
+    { \
+        OSReleaseMutex(); \
+        return RETVAL;\
+    }
+
+#define RI_IF_ERROR(COND, ERRORCODE, RETVAL) \
+    if(COND) { context->setError(ERRORCODE); OSReleaseMutex(); return RETVAL; }
+
+//all API functions must call this as their last operation (also functions that don't return values)
+//NOTE: don't evaluate anything or read state in RETVAL (it'll be executed after the mutex has been released)
+#define RI_RETURN(RETVAL) \
+    { OSReleaseMutex(); \
+    return RETVAL; }
+
+static bool isAligned(const void* ptr, int alignment)
+{
+    RI_ASSERT(alignment == 1 || alignment == 2 || alignment == 4);
+    if(((RIuintptr)ptr) & (alignment-1))
+        return false;
+    return true;
+}
+
+static bool isAligned(const void* ptr, VGImageFormat format)
+{
+    RI_ASSERT(isValidImageFormat(format));
+    int alignment = Color::formatToDescriptor(format).bitsPerPixel >> 3;
+    if(alignment <= 1)
+        return true;	//one bit or byte per pixel
+    return isAligned(ptr, alignment);
+}
+
+bool isValidImageFormat(int f)
+{
+    if(f < VG_sRGBX_8888 || f > VG_lABGR_8888_PRE)
+        return false;
+    return true;
+}
+
+}	//namespace OpenVGRI
+
+using namespace OpenVGRI;
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgFlush(void)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    //the RI doesn't cache anything, so this is a no-op
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgFinish(void)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    //the RI doesn't cache anything, so this is a no-op
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGErrorCode RI_APIENTRY vgGetError(void)
+{
+    RI_GET_CONTEXT(VG_NO_CONTEXT_ERROR);
+    VGErrorCode error = context->m_error;
+    context->m_error = VG_NO_ERROR;
+    RI_RETURN(error);
+}
+
+VGErrorCode RI_APIENTRY vgPlatsimGetError(void)
+{
+    RI_GET_CONTEXT(VG_NO_CONTEXT_ERROR);
+    VGErrorCode error = context->m_error;
+    RI_RETURN(error);
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+namespace OpenVGRI
+{
+
+RIfloat inputFloat(VGfloat f)
+{
+    //this function is used for all floating point input values
+    if(RI_ISNAN(f)) return 0.0f;	//convert NaN to zero
+    return RI_CLAMP(f, -RI_FLOAT_MAX, RI_FLOAT_MAX);	//clamp +-inf to +-RIfloat max
+}
+
+Vector2 inputVector2(const Vector2& v)
+{
+    return Vector2(inputFloat(v.x), inputFloat(v.y));
+}
+
+Color inputColor(const Color& c)
+{
+    Color r = c;
+    r.r = inputFloat(r.r);
+    r.g = inputFloat(r.g);
+    r.b = inputFloat(r.b);
+    r.a = inputFloat(r.a);
+    return r;
+}
+
+static int inputFloatToInt(VGfloat value)
+{
+    double v = (double)floor(value);
+    v = v > (double)RI_INT32_MAX ? (double)RI_INT32_MAX : v;
+    v = v < (double)RI_INT32_MIN ? (double)RI_INT32_MIN : v;
+    return (int)v;
+}
+
+static int paramToInt(const void* values, bool floats, int count, int i)
+{
+    RI_ASSERT(i >= 0);
+    if(i >= count || !values)
+        return 0;
+    if(floats)
+        return inputFloatToInt(((const VGfloat*)values)[i]);
+    return (int)((const VGint*)values)[i];
+}
+
+static RIfloat paramToFloat(const void* values, bool floats, int count, int i)
+{
+    RI_ASSERT(i >= 0);
+    if(i >= count || !values)
+        return 0.0f;
+    if(floats)
+        return ((const VGfloat*)values)[i];
+    return (RIfloat)((const VGint*)values)[i];
+}
+
+static void floatToParam(void* output, bool outputFloats, int count, int i, VGfloat value)
+{
+    RI_ASSERT(i >= 0);
+    RI_ASSERT(output);
+    if(i >= count)
+        return;
+    if(outputFloats)
+        ((VGfloat*)output)[i] = value;
+    else
+        ((VGint*)output)[i] = (VGint)inputFloatToInt(value);
+}
+
+static void intToParam(void* output, bool outputFloats, int count, int i, VGint value)
+{
+    RI_ASSERT(i >= 0);
+    RI_ASSERT(output);
+    if(i >= count)
+        return;
+    if(outputFloats)
+        ((VGfloat*)output)[i] = (VGfloat)value;
+    else
+        ((VGint*)output)[i] = value;
+}
+
+}	//namespace OpenVGRI
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void setifv(VGContext* context, VGParamType type, VGint count, const void* values, bool floats)
+{
+    RI_ASSERT(context);
+    RI_ASSERT(!count || (count && values));
+
+    int ivalue = paramToInt(values, floats, count, 0);
+    RIfloat fvalue = paramToFloat(values, floats, count, 0);
+
+    switch(type)
+    {
+    case VG_MATRIX_MODE:
+        if(count != 1 || ivalue < VG_MATRIX_PATH_USER_TO_SURFACE || ivalue > VG_MATRIX_GLYPH_USER_TO_SURFACE)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_matrixMode = (VGMatrixMode)ivalue;
+        break;
+
+    case VG_FILL_RULE:
+        if(count != 1 || ivalue < VG_EVEN_ODD || ivalue > VG_NON_ZERO)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_fillRule = (VGFillRule)ivalue;
+        break;
+
+    case VG_IMAGE_QUALITY:
+        if(count != 1 || !(ivalue == VG_IMAGE_QUALITY_NONANTIALIASED || ivalue == VG_IMAGE_QUALITY_FASTER || ivalue == VG_IMAGE_QUALITY_BETTER))	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_imageQuality = (VGImageQuality)ivalue;
+        break;
+
+    case VG_RENDERING_QUALITY:
+        if(count != 1 || !(ivalue == VG_RENDERING_QUALITY_NONANTIALIASED || ivalue == VG_RENDERING_QUALITY_FASTER || ivalue == VG_RENDERING_QUALITY_BETTER))	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_renderingQuality = (VGRenderingQuality)ivalue;
+        break;
+
+    case VG_BLEND_MODE:
+        if(count != 1 || ivalue < VG_BLEND_SRC || ivalue > VG_BLEND_ADDITIVE)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_blendMode = (VGBlendMode)ivalue;
+        break;
+
+    case VG_IMAGE_MODE:
+        if(count != 1 || ivalue < VG_DRAW_IMAGE_NORMAL || ivalue > VG_DRAW_IMAGE_STENCIL)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_imageMode = (VGImageMode)ivalue;
+        break;
+
+    case VG_SCISSOR_RECTS:
+    {
+        if(count & 3)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }	//count must be a multiple of four
+        try
+        {
+            Array<OpenVGRI::Rectangle> scissor;
+            for(int i=0;i<RI_INT_MIN(count, RI_MAX_SCISSOR_RECTANGLES*4);i+=4)
+            {
+                OpenVGRI::Rectangle s;
+                s.x = paramToInt(values, floats, count, i+0);
+                s.y = paramToInt(values, floats, count, i+1);
+                s.width = paramToInt(values, floats, count, i+2);
+                s.height = paramToInt(values, floats, count, i+3);
+                scissor.push_back(s);	//throws bad_alloc
+            }
+            context->m_scissor.swap(scissor);	//replace context data
+        }
+        catch(std::bad_alloc)
+        {
+            context->setError(VG_OUT_OF_MEMORY_ERROR);
+        }
+        break;
+    }
+
+    case VG_COLOR_TRANSFORM:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_colorTransform = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_COLOR_TRANSFORM_VALUES:
+        if(count != 8 || !values) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        {
+            for(int i=0;i<8;i++)
+            {
+                context->m_inputColorTransformValues[i] = paramToFloat(values, floats, count, i);
+                context->m_colorTransformValues[i] = inputFloat(context->m_inputColorTransformValues[i]);
+            }
+        }
+        break;
+
+    case VG_STROKE_LINE_WIDTH:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputStrokeLineWidth = fvalue;
+        context->m_strokeLineWidth = inputFloat(fvalue);
+        break;
+
+    case VG_STROKE_CAP_STYLE:
+        if(count != 1 || ivalue < VG_CAP_BUTT || ivalue > VG_CAP_SQUARE)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_strokeCapStyle = (VGCapStyle)ivalue;
+        break;
+
+    case VG_STROKE_JOIN_STYLE:
+        if(count != 1 || ivalue < VG_JOIN_MITER || ivalue > VG_JOIN_BEVEL)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_strokeJoinStyle = (VGJoinStyle)ivalue;
+        break;
+
+    case VG_STROKE_MITER_LIMIT:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputStrokeMiterLimit = fvalue;
+        context->m_strokeMiterLimit = inputFloat(fvalue);
+        break;
+
+    case VG_STROKE_DASH_PATTERN:
+    {
+        try
+        {
+            Array<RIfloat> inputStrokeDashPattern;
+            Array<RIfloat> strokeDashPattern;
+            for(int i=0;i<RI_INT_MIN(count, RI_MAX_DASH_COUNT);i++)
+            {
+                RIfloat v = paramToFloat(values, floats, count, i);
+                inputStrokeDashPattern.push_back(v);	//throws bad_alloc
+                strokeDashPattern.push_back(inputFloat(v));	//throws bad_alloc
+            }
+            context->m_inputStrokeDashPattern.swap(inputStrokeDashPattern);	//replace context data
+            context->m_strokeDashPattern.swap(strokeDashPattern);	//replace context data
+        }
+        catch(std::bad_alloc)
+        {
+            context->setError(VG_OUT_OF_MEMORY_ERROR);
+        }
+        break;
+    }
+
+    case VG_STROKE_DASH_PHASE:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputStrokeDashPhase = fvalue;
+        context->m_strokeDashPhase = inputFloat(fvalue);
+        break;
+
+    case VG_STROKE_DASH_PHASE_RESET:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_strokeDashPhaseReset = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_TILE_FILL_COLOR:
+        if(count != 4 || !values) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputTileFillColor.set(paramToFloat(values, floats, count, 0),
+                                     paramToFloat(values, floats, count, 1),
+                                     paramToFloat(values, floats, count, 2),
+                                     paramToFloat(values, floats, count, 3),
+                                     Color::sRGBA);
+        context->m_tileFillColor = inputColor(context->m_inputTileFillColor);
+        break;
+
+    case VG_GLYPH_ORIGIN:
+        if(count != 2 || !values) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputGlyphOrigin.x = paramToFloat(values, floats, count, 0);
+        context->m_inputGlyphOrigin.y = paramToFloat(values, floats, count, 1);
+        context->m_glyphOrigin = inputVector2(context->m_inputGlyphOrigin);
+        break;
+
+    case VG_CLEAR_COLOR:
+        if(count != 4 || !values) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputClearColor.set(paramToFloat(values, floats, count, 0),
+                                  paramToFloat(values, floats, count, 1),
+                                  paramToFloat(values, floats, count, 2),
+                                  paramToFloat(values, floats, count, 3),
+                                  Color::sRGBA);
+        context->m_clearColor = inputColor(context->m_inputClearColor);
+        break;
+
+    case VG_MASKING:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_masking = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_SCISSORING:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_scissoring = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_PIXEL_LAYOUT:
+        if(count != 1 || ivalue < VG_PIXEL_LAYOUT_UNKNOWN || ivalue > VG_PIXEL_LAYOUT_BGR_HORIZONTAL)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_pixelLayout = (VGPixelLayout)ivalue;
+        break;
+
+    case VG_SCREEN_LAYOUT:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        break;	//setting read-only values has no effect
+
+    case VG_FILTER_FORMAT_LINEAR:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_filterFormatLinear = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_FILTER_FORMAT_PREMULTIPLIED:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_filterFormatPremultiplied = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_FILTER_CHANNEL_MASK:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        //undefined bits are ignored
+        context->m_filterChannelMask = (VGbitfield)ivalue;
+        break;
+
+    case VG_MAX_SCISSOR_RECTS:
+    case VG_MAX_DASH_COUNT:
+    case VG_MAX_KERNEL_SIZE:
+    case VG_MAX_SEPARABLE_KERNEL_SIZE:
+    case VG_MAX_COLOR_RAMP_STOPS:
+    case VG_MAX_IMAGE_WIDTH:
+    case VG_MAX_IMAGE_HEIGHT:
+    case VG_MAX_IMAGE_PIXELS:
+    case VG_MAX_IMAGE_BYTES:
+    case VG_MAX_FLOAT:
+    case VG_MAX_GAUSSIAN_STD_DEVIATION:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        break;	//setting read-only values has no effect
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetf(VGParamType type, VGfloat value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR ||
+                type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//vector type value
+    VGfloat values[1] = {value};
+    setifv(context, type, 1, values, true);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSeti(VGParamType type, VGint value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR ||
+                type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//vector type value
+    VGint values[1] = {value};
+    setifv(context, type, 1, values, false);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetiv(VGParamType type, VGint count, const VGint * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count < 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR((!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    setifv(context, type, count, values, false);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetfv(VGParamType type, VGint count, const VGfloat * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count < 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR((!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    setifv(context, type, count, values, true);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getifv(VGContext* context, VGParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_MATRIX_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_matrixMode);
+        break;
+
+    case VG_FILL_RULE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_fillRule);
+        break;
+
+    case VG_IMAGE_QUALITY:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_imageQuality);
+        break;
+
+    case VG_RENDERING_QUALITY:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_renderingQuality);
+        break;
+
+    case VG_BLEND_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_blendMode);
+        break;
+
+    case VG_IMAGE_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_imageMode);
+        break;
+
+    case VG_SCISSOR_RECTS:
+    {
+        if(count > context->m_scissor.size()*4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        for(int i=0;i<context->m_scissor.size();i++)
+        {
+            intToParam(values, floats, count, i*4+0, context->m_scissor[i].x);
+            intToParam(values, floats, count, i*4+1, context->m_scissor[i].y);
+            intToParam(values, floats, count, i*4+2, context->m_scissor[i].width);
+            intToParam(values, floats, count, i*4+3, context->m_scissor[i].height);
+        }
+        break;
+    }
+
+    case VG_COLOR_TRANSFORM:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_colorTransform);
+        break;
+
+    case VG_COLOR_TRANSFORM_VALUES:
+        if(count > 8) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        {
+            for(int i=0;i<count;i++)
+            {
+                floatToParam(values, floats, count, i, context->m_inputColorTransformValues[i]);
+            }
+        }
+        break;
+
+    case VG_STROKE_LINE_WIDTH:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputStrokeLineWidth);
+        break;
+
+    case VG_STROKE_CAP_STYLE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_strokeCapStyle);
+        break;
+
+    case VG_STROKE_JOIN_STYLE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_strokeJoinStyle);
+        break;
+
+    case VG_STROKE_MITER_LIMIT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputStrokeMiterLimit);
+        break;
+
+    case VG_STROKE_DASH_PATTERN:
+    {
+        if(count > context->m_inputStrokeDashPattern.size())	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        for(int i=0;i<context->m_inputStrokeDashPattern.size();i++)
+            floatToParam(values, floats, count, i, context->m_inputStrokeDashPattern[i]);
+        break;
+    }
+
+    case VG_STROKE_DASH_PHASE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputStrokeDashPhase);
+        break;
+
+    case VG_STROKE_DASH_PHASE_RESET:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_strokeDashPhaseReset);
+        break;
+
+    case VG_TILE_FILL_COLOR:
+        if(count > 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputTileFillColor.r);
+        floatToParam(values, floats, count, 1, context->m_inputTileFillColor.g);
+        floatToParam(values, floats, count, 2, context->m_inputTileFillColor.b);
+        floatToParam(values, floats, count, 3, context->m_inputTileFillColor.a);
+        break;
+
+    case VG_CLEAR_COLOR:
+        if(count > 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputClearColor.r);
+        floatToParam(values, floats, count, 1, context->m_inputClearColor.g);
+        floatToParam(values, floats, count, 2, context->m_inputClearColor.b);
+        floatToParam(values, floats, count, 3, context->m_inputClearColor.a);
+        break;
+
+    case VG_GLYPH_ORIGIN:
+        if(count > 2)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputGlyphOrigin.x);
+        floatToParam(values, floats, count, 1, context->m_inputGlyphOrigin.y);
+        break;
+
+    case VG_MASKING:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_masking);
+        break;
+
+    case VG_SCISSORING:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_scissoring);
+        break;
+
+    case VG_PIXEL_LAYOUT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_pixelLayout);
+        break;
+
+    case VG_SCREEN_LAYOUT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, VG_PIXEL_LAYOUT_UNKNOWN);
+        break;
+
+    case VG_FILTER_FORMAT_LINEAR:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_filterFormatLinear);
+        break;
+
+    case VG_FILTER_FORMAT_PREMULTIPLIED:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_filterFormatPremultiplied);
+        break;
+
+    case VG_FILTER_CHANNEL_MASK:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_filterChannelMask);
+        break;
+
+    case VG_MAX_SCISSOR_RECTS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_SCISSOR_RECTANGLES);
+        break;
+
+    case VG_MAX_DASH_COUNT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_DASH_COUNT);
+        break;
+
+    case VG_MAX_KERNEL_SIZE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_KERNEL_SIZE);
+        break;
+
+    case VG_MAX_SEPARABLE_KERNEL_SIZE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_SEPARABLE_KERNEL_SIZE);
+        break;
+
+    case VG_MAX_COLOR_RAMP_STOPS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_COLOR_RAMP_STOPS);
+        break;
+
+    case VG_MAX_IMAGE_WIDTH:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_IMAGE_WIDTH);
+        break;
+
+    case VG_MAX_IMAGE_HEIGHT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_IMAGE_HEIGHT);
+        break;
+
+    case VG_MAX_IMAGE_PIXELS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_IMAGE_PIXELS);
+        break;
+
+    case VG_MAX_IMAGE_BYTES:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_IMAGE_BYTES);
+        break;
+
+    case VG_MAX_FLOAT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, RI_FLOAT_MAX);
+        break;
+
+    case VG_MAX_GAUSSIAN_STD_DEVIATION:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, RI_MAX_GAUSSIAN_STD_DEVIATION);
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGfloat RI_APIENTRY vgGetf(VGParamType type)
+{
+    RI_GET_CONTEXT(0.0f);
+    RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR ||
+                type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, 0.0f);	//vector type value
+    RIfloat ret = 0.0f;
+    getifv(context, type, 1, &ret, true);
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGint RI_APIENTRY vgGeti(VGParamType type)
+{
+    RI_GET_CONTEXT(0);
+    RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR ||
+                type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, 0);	//vector type value
+    VGint ret = 0;
+    getifv(context, type, 1, &ret, false);
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetiv(VGParamType type, VGint count, VGint * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    getifv(context, type, count, values, false);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetfv(VGParamType type, VGint count, VGfloat * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    getifv(context, type, count, values, true);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGint RI_APIENTRY vgGetVectorSize(VGParamType type)
+{
+    RI_GET_CONTEXT(0);
+    VGint ret = 0;
+    switch(type)
+    {
+    case VG_MATRIX_MODE:
+    case VG_FILL_RULE:
+    case VG_IMAGE_QUALITY:
+    case VG_RENDERING_QUALITY:
+    case VG_BLEND_MODE:
+    case VG_IMAGE_MODE:
+        ret = 1;
+        break;
+
+    case VG_SCISSOR_RECTS:
+        ret = 4*context->m_scissor.size();
+        break;
+
+    case VG_COLOR_TRANSFORM:
+        ret = 1;
+        break;
+
+    case VG_COLOR_TRANSFORM_VALUES:
+        ret = 8;
+        break;
+
+    case VG_STROKE_LINE_WIDTH:
+    case VG_STROKE_CAP_STYLE:
+    case VG_STROKE_JOIN_STYLE:
+    case VG_STROKE_MITER_LIMIT:
+        ret = 1;
+        break;
+
+    case VG_STROKE_DASH_PATTERN:
+        ret = context->m_inputStrokeDashPattern.size();
+        break;
+
+    case VG_STROKE_DASH_PHASE:
+    case VG_STROKE_DASH_PHASE_RESET:
+        ret = 1;
+        break;
+
+    case VG_TILE_FILL_COLOR:
+    case VG_CLEAR_COLOR:
+        ret = 4;
+        break;
+
+    case VG_GLYPH_ORIGIN:
+        ret = 2;
+        break;
+
+    case VG_MASKING:
+    case VG_SCISSORING:
+    case VG_PIXEL_LAYOUT:
+    case VG_SCREEN_LAYOUT:
+    case VG_FILTER_FORMAT_LINEAR:
+    case VG_FILTER_FORMAT_PREMULTIPLIED:
+    case VG_FILTER_CHANNEL_MASK:
+    case VG_MAX_SCISSOR_RECTS:
+    case VG_MAX_DASH_COUNT:
+    case VG_MAX_KERNEL_SIZE:
+    case VG_MAX_SEPARABLE_KERNEL_SIZE:
+    case VG_MAX_COLOR_RAMP_STOPS:
+    case VG_MAX_IMAGE_WIDTH:
+    case VG_MAX_IMAGE_HEIGHT:
+    case VG_MAX_IMAGE_PIXELS:
+    case VG_MAX_IMAGE_BYTES:
+    case VG_MAX_FLOAT:
+    case VG_MAX_GAUSSIAN_STD_DEVIATION:
+        ret = 1;
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void setPaintParameterifv(VGContext* context, Paint* paint, VGPaintParamType paramType, VGint count, const void* values, bool floats)
+{
+    RI_ASSERT(context);
+    RI_ASSERT(paint);
+
+    int ivalue = paramToInt(values, floats, count, 0);
+
+    switch(paramType)
+    {
+    case VG_PAINT_TYPE:
+        if(count != 1 || ivalue < VG_PAINT_TYPE_COLOR || ivalue > VG_PAINT_TYPE_PATTERN)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_paintType = (VGPaintType)ivalue;
+        break;
+
+    case VG_PAINT_COLOR:
+        RI_TRACE("\n***** Setting solid color to paint.\n");
+        RI_TRACE("** ptr: %x\n", (int)paint);
+        if(count != 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_inputPaintColor.set(paramToFloat(values, floats, count, 0),
+                                     paramToFloat(values, floats, count, 1),
+                                     paramToFloat(values, floats, count, 2),
+                                     paramToFloat(values, floats, count, 3),
+                                     Color::sRGBA);
+        RI_TRACE("** input solid color: [%.3f %.3f %.3f %.4f]\n", paint->m_inputPaintColor.r, paint->m_inputPaintColor.g, paint->m_inputPaintColor.b, paint->m_inputPaintColor.a);
+        paint->setColor(inputColor(paint->m_inputPaintColor));
+        RI_TRACE("** -> [%.3f %.3f %.3f %.3f]\n", paint->m_paintColor.r, paint->m_paintColor.g, paint->m_paintColor.b, paint->m_paintColor.a);
+        break;
+
+    case VG_PAINT_COLOR_RAMP_SPREAD_MODE:
+        if(count != 1 || ivalue < VG_COLOR_RAMP_SPREAD_PAD || ivalue > VG_COLOR_RAMP_SPREAD_REFLECT)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_colorRampSpreadMode = (VGColorRampSpreadMode)ivalue;
+        break;
+
+    case VG_PAINT_COLOR_RAMP_STOPS:
+    {
+        int numStops = count/5;
+        if(count != numStops*5)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }	//count must be a multiple of five
+        try
+        {
+            Array<Paint::GradientStop> colorRampStops;
+            Array<Paint::GradientStop> inputColorRampStops;
+            RIfloat prevOffset = -RI_FLOAT_MAX;
+            bool valid = true;
+            for(int i=0;i<RI_INT_MIN(numStops, RI_MAX_COLOR_RAMP_STOPS);i++)	//NOTE: ignores the final stop if there is not enough parameters
+            {
+                Paint::GradientStop gs;
+                gs.offset = paramToFloat(values, floats, count, i*5);
+                gs.color.set(paramToFloat(values, floats, count, i*5+1),
+                             paramToFloat(values, floats, count, i*5+2),
+                             paramToFloat(values, floats, count, i*5+3),
+                             paramToFloat(values, floats, count, i*5+4),
+                             Color::sRGBA);
+                inputColorRampStops.push_back(gs);
+
+                if(gs.offset < prevOffset)
+                    valid = false;	//decreasing sequence, ignore it
+
+                if(gs.offset >= 0.0f && gs.offset <= 1.0f)
+                {
+                    gs.color.clamp();
+
+                    if(!colorRampStops.size() && gs.offset > 0.0f)
+                    {	//the first valid stop is not at 0, replicate the first one
+                        RIfloat tmp = gs.offset;
+                        gs.offset = 0.0f;
+                        colorRampStops.push_back(gs);	//throws bad_alloc
+                        gs.offset = tmp;
+                    }
+                    colorRampStops.push_back(gs);	//throws bad_alloc
+                }
+                prevOffset = gs.offset;
+            }
+            if(valid && colorRampStops.size() && colorRampStops[colorRampStops.size()-1].offset < 1.0f)
+            {	//there is at least one stop, but the last one is not at 1, replicate the last one
+                Paint::GradientStop gs = colorRampStops[colorRampStops.size()-1];
+                gs.offset = 1.0f;
+                colorRampStops.push_back(gs);	//throws bad_alloc
+            }
+            if(!valid || !colorRampStops.size())
+            {	//there are no valid stops, add implicit stops
+                colorRampStops.clear();
+                Paint::GradientStop gs;
+                gs.offset = 0.0f;
+                gs.color.set(0,0,0,1,Color::sRGBA);
+                colorRampStops.push_back(gs);	//throws bad_alloc
+                gs.offset = 1.0f;
+                gs.color.set(1,1,1,1,Color::sRGBA);
+                colorRampStops.push_back(gs);	//throws bad_alloc
+            }
+            RI_ASSERT(colorRampStops.size() >= 2 && colorRampStops.size() <= RI_MAX_COLOR_RAMP_STOPS);
+            //paint->m_colorRampStops.swap(colorRampStops);	//set paint array
+            //paint->m_inputColorRampStops.swap(inputColorRampStops);	//set paint array
+            paint->setGradientStops(inputColorRampStops, colorRampStops);
+            //paint->generateLUT();
+        }
+        catch(std::bad_alloc)
+        {
+            context->setError(VG_OUT_OF_MEMORY_ERROR);
+        }
+        break;
+    }
+
+    case VG_PAINT_COLOR_RAMP_PREMULTIPLIED:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_colorRampPremultiplied = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_PAINT_LINEAR_GRADIENT:
+        if(count != 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_inputLinearGradientPoint0.set(paramToFloat(values, floats, count, 0),
+                                          paramToFloat(values, floats, count, 1));
+        paint->m_inputLinearGradientPoint1.set(paramToFloat(values, floats, count, 2),
+                                          paramToFloat(values, floats, count, 3));
+        paint->setLinearGradient(
+            inputVector2(paint->m_inputLinearGradientPoint0),
+            inputVector2(paint->m_inputLinearGradientPoint1));
+
+        break;
+
+    case VG_PAINT_RADIAL_GRADIENT:
+        if(count != 5)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_inputRadialGradientCenter.set(paramToFloat(values, floats, count, 0),
+                                          paramToFloat(values, floats, count, 1));
+        paint->m_inputRadialGradientFocalPoint.set(paramToFloat(values, floats, count, 2),
+                                              paramToFloat(values, floats, count, 3));
+        paint->m_inputRadialGradientRadius = paramToFloat(values, floats, count, 4);
+        paint->setRadialGradient(
+            inputVector2(paint->m_inputRadialGradientCenter),
+            inputVector2(paint->m_inputRadialGradientFocalPoint),
+            inputFloat(paint->m_inputRadialGradientRadius));
+        //paint->m_radialGradientCenter = inputVector2(paint->m_inputRadialGradientCenter);
+        //paint->m_radialGradientFocalPoint = inputVector2(paint->m_inputRadialGradientFocalPoint);
+        //paint->m_radialGradientRadius = inputFloat(paint->m_inputRadialGradientRadius);
+        break;
+
+    case VG_PAINT_PATTERN_TILING_MODE:
+        if(count != 1 || ivalue < VG_TILE_FILL || ivalue > VG_TILE_REFLECT)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_patternTilingMode = (VGTilingMode)ivalue;
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetParameterf(VGHandle object, VGint paramType, VGfloat value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isMaskLayer = context->isValidMaskLayer(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle
+    RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT ||
+                paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //vector valued parameter
+    VGfloat values[1] = {value};
+    if(isImage)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPath)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont);
+        setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, values, true);
+    }
+    else if(isMaskLayer)
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isFont);
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont);
+        if (paramType != VG_FONT_NUM_GLYPHS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetParameteri(VGHandle object, VGint paramType, VGint value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isMaskLayer = context->isValidMaskLayer(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle
+    RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT ||
+                paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//vector valued parameter
+    VGint values[1] = {value};
+    if(isImage)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPath)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont);
+        setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, values, false);
+    }
+    else if(isMaskLayer)
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isFont);
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont);
+        if (paramType != VG_FONT_NUM_GLYPHS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetParameterfv(VGHandle object, VGint paramType, VGint count, const VGfloat * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count < 0 || (!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isMaskLayer = context->isValidMaskLayer(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle
+    if(isImage)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPath)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont);
+        setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, true);
+    }
+    else if(isMaskLayer)
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isFont);
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont);
+        if (paramType != VG_FONT_NUM_GLYPHS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetParameteriv(VGHandle object, VGint paramType, VGint count, const VGint * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count < 0 || (!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isMaskLayer = context->isValidMaskLayer(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle
+    if(isImage)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPath)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont);
+        setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, false);
+    }
+    else if(isMaskLayer)
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isFont);
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont);
+        if (paramType != VG_FONT_NUM_GLYPHS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getPaintParameterifv(VGContext* context, Paint* paint, VGPaintParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_PAINT_TYPE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, paint->m_paintType);
+        break;
+
+    case VG_PAINT_COLOR:
+        if(count > 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, paint->m_inputPaintColor.r);
+        floatToParam(values, floats, count, 1, paint->m_inputPaintColor.g);
+        floatToParam(values, floats, count, 2, paint->m_inputPaintColor.b);
+        floatToParam(values, floats, count, 3, paint->m_inputPaintColor.a);
+        break;
+
+    case VG_PAINT_COLOR_RAMP_SPREAD_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, paint->m_colorRampSpreadMode);
+        break;
+
+    case VG_PAINT_COLOR_RAMP_STOPS:
+        {
+            if(count > paint->m_inputColorRampStops.size()*5)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+            int j = 0;
+            for(int i=0;i<paint->m_inputColorRampStops.size();i++)
+            {
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].offset);
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.r);
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.g);
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.b);
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.a);
+            }
+            break;
+        }
+
+    case VG_PAINT_COLOR_RAMP_PREMULTIPLIED:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, paint->m_colorRampPremultiplied);
+        break;
+
+    case VG_PAINT_LINEAR_GRADIENT:
+        if(count > 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, paint->m_inputLinearGradientPoint0.x);
+        floatToParam(values, floats, count, 1, paint->m_inputLinearGradientPoint0.y);
+        floatToParam(values, floats, count, 2, paint->m_inputLinearGradientPoint1.x);
+        floatToParam(values, floats, count, 3, paint->m_inputLinearGradientPoint1.y);
+        break;
+
+    case VG_PAINT_RADIAL_GRADIENT:
+        if(count > 5)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, paint->m_inputRadialGradientCenter.x);
+        floatToParam(values, floats, count, 1, paint->m_inputRadialGradientCenter.y);
+        floatToParam(values, floats, count, 2, paint->m_inputRadialGradientFocalPoint.x);
+        floatToParam(values, floats, count, 3, paint->m_inputRadialGradientFocalPoint.y);
+        floatToParam(values, floats, count, 4, paint->m_inputRadialGradientRadius);
+        break;
+
+    case VG_PAINT_PATTERN_TILING_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, paint->m_patternTilingMode);
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getPathParameterifv(VGContext* context, Path* path, VGPathParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_PATH_FORMAT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, path->getFormat());
+        break;
+
+    case VG_PATH_DATATYPE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, path->getDatatype());
+        break;
+
+    case VG_PATH_SCALE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, path->getScale());
+        break;
+
+    case VG_PATH_BIAS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, path->getBias());
+        break;
+
+    case VG_PATH_NUM_SEGMENTS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, path->getNumSegments());
+        break;
+
+    case VG_PATH_NUM_COORDS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, path->getNumCoordinates());
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getImageParameterifv(VGContext* context, Image* image, VGImageParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_IMAGE_FORMAT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        RI_ASSERT(isValidImageFormat(image->getDescriptor().vgFormat));
+        intToParam(values, floats, count, 0, image->getDescriptor().vgFormat);
+        break;
+
+    case VG_IMAGE_WIDTH:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, image->getWidth());
+        break;
+
+    case VG_IMAGE_HEIGHT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, image->getHeight());
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getFontParameterifv(VGContext* context, Font* font, VGFontParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_FONT_NUM_GLYPHS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, font->getNumGlyphs());
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGfloat RI_APIENTRY vgGetParameterf(VGHandle object, VGint paramType)
+{
+    RI_GET_CONTEXT(0.0f);
+    RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT ||
+                paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, 0.0f);	//vector valued parameter
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0.0f);	//invalid object handle
+    VGfloat ret = 0.0f;
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, 1, &ret, true);
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, 1, &ret, true);
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, &ret, true);
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, 1, &ret, true);
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGint RI_APIENTRY vgGetParameteri(VGHandle object, VGint paramType)
+{
+    RI_GET_CONTEXT(0);
+    RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT ||
+                paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, 0);	//vector valued parameter
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0);	//invalid object handle
+    VGint ret = 0;
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, 1, &ret, false);
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, 1, &ret, false);
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, &ret, false);
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, 1, &ret, false);
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetParameterfv(VGHandle object, VGint paramType, VGint count, VGfloat * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count <= 0 || !values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid object handle
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, count, values, true);
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, count, values, true);
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, true);
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, count, values, true);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetParameteriv(VGHandle object, VGint paramType, VGint count, VGint * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count <= 0 || !values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid object handle
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, count, values, false);
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, count, values, false);
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, false);
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, count, values, false);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGint RI_APIENTRY vgGetParameterVectorSize(VGHandle object, VGint paramType)
+{
+    RI_GET_CONTEXT(0);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0);	//invalid object handle
+    int ret = 0;
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        switch(paramType)
+        {
+        case VG_IMAGE_FORMAT:
+        case VG_IMAGE_WIDTH:
+        case VG_IMAGE_HEIGHT:
+            ret = 1;
+            break;
+
+        default:
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid paramType
+            break;
+        }
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        switch(paramType)
+        {
+        case VG_PATH_FORMAT:
+        case VG_PATH_DATATYPE:
+        case VG_PATH_SCALE:
+        case VG_PATH_BIAS:
+        case VG_PATH_NUM_SEGMENTS:
+        case VG_PATH_NUM_COORDS:
+            ret = 1;
+            break;
+
+        default:
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid paramType
+            break;
+        }
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        switch(paramType)
+        {
+        case VG_PAINT_TYPE:
+        case VG_PAINT_COLOR_RAMP_SPREAD_MODE:
+        case VG_PAINT_PATTERN_TILING_MODE:
+            ret = 1;
+            break;
+
+        case VG_PAINT_COLOR:
+        case VG_PAINT_LINEAR_GRADIENT:
+            ret = 4;
+            break;
+
+        case VG_PAINT_COLOR_RAMP_STOPS:
+            ret = ((Paint*)object)->m_inputColorRampStops.size() * 5;
+            break;
+
+        case VG_PAINT_COLOR_RAMP_PREMULTIPLIED:
+            ret = 1;
+            break;
+
+        case VG_PAINT_RADIAL_GRADIENT:
+            ret = 5;
+            break;
+
+        default:
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid paramType
+            break;
+        }
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        switch(paramType)
+        {
+        case VG_FONT_NUM_GLYPHS:
+            ret = 1;
+            break;
+
+        default:
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid paramType
+            break;
+        }
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static Matrix3x3* getCurrentMatrix(VGContext* context)
+{
+    RI_ASSERT(context);
+    switch(context->m_matrixMode)
+    {
+    case VG_MATRIX_PATH_USER_TO_SURFACE:
+        return &context->m_pathUserToSurface;
+
+    case VG_MATRIX_IMAGE_USER_TO_SURFACE:
+        return &context->m_imageUserToSurface;
+
+    case VG_MATRIX_FILL_PAINT_TO_USER:
+        return &context->m_fillPaintToUser;
+
+    case VG_MATRIX_STROKE_PAINT_TO_USER:
+        return &context->m_strokePaintToUser;
+
+    default:
+        RI_ASSERT(context->m_matrixMode == VG_MATRIX_GLYPH_USER_TO_SURFACE);
+        return &context->m_glyphUserToSurface;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgLoadIdentity(void)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    Matrix3x3* d = getCurrentMatrix(context);
+    d->identity();
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgLoadMatrix(const VGfloat * m)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Matrix3x3* d = getCurrentMatrix(context);
+    d->set(inputFloat(m[0]), inputFloat(m[3]), inputFloat(m[6]),
+           inputFloat(m[1]), inputFloat(m[4]), inputFloat(m[7]),
+           inputFloat(m[2]), inputFloat(m[5]), inputFloat(m[8]));
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetMatrix(VGfloat * m)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Matrix3x3* d = getCurrentMatrix(context);
+    m[0] = (*d)[0][0];
+    m[1] = (*d)[1][0];
+    m[2] = (*d)[2][0];
+    m[3] = (*d)[0][1];
+    m[4] = (*d)[1][1];
+    m[5] = (*d)[2][1];
+    m[6] = (*d)[0][2];
+    m[7] = (*d)[1][2];
+    m[8] = (*d)[2][2];
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgMultMatrix(const VGfloat * m)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Matrix3x3 n(inputFloat(m[0]), inputFloat(m[3]), inputFloat(m[6]),
+                inputFloat(m[1]), inputFloat(m[4]), inputFloat(m[7]),
+                inputFloat(m[2]), inputFloat(m[5]), inputFloat(m[8]));
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+        n[2].set(0,0,1);
+
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgTranslate(VGfloat tx, VGfloat ty)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    Matrix3x3 n(1, 0, inputFloat(tx),
+                0, 1, inputFloat(ty),
+                0, 0, 1 );
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgScale(VGfloat sx, VGfloat sy)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    Matrix3x3 n(inputFloat(sx), 0,              0,
+                0,              inputFloat(sy), 0,
+                0,              0,              1 );
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgShear(VGfloat shx, VGfloat shy)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    Matrix3x3 n(1,               inputFloat(shx), 0,
+                inputFloat(shy), 1,               0,
+                0,               0,               1);
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgRotate(VGfloat angle)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RIfloat a = RI_DEG_TO_RAD(inputFloat(angle));
+    Matrix3x3 n((RIfloat)cos(a), -(RIfloat)sin(a), 0,
+                (RIfloat)sin(a),  (RIfloat)cos(a), 0,
+                0,              0,             1 );
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgMask(VGHandle mask, VGMaskOperation operation, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    const bool isImage = context->isValidImage(mask);
+    const bool isMaskLayer = context->isValidMaskLayer(mask);
+    const bool needInput = (operation != VG_CLEAR_MASK) && (operation != VG_FILL_MASK);
+    RI_IF_ERROR(operation != VG_CLEAR_MASK && operation != VG_FILL_MASK && !isImage && !isMaskLayer, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(operation != VG_CLEAR_MASK && operation != VG_FILL_MASK && isImage && eglvgIsInUse((Image*)mask), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(operation < VG_CLEAR_MASK || operation > VG_SUBTRACT_MASK, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    RI_IF_ERROR(isMaskLayer && drawable->getNumSamples() != ((Surface*)mask)->getNumSamples(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    if(!drawable || !drawable->getMaskBuffer())
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment or context has no mask buffer
+    }
+
+    if(isImage)
+        drawable->getMaskBuffer()->mask(context->getBlitter(), (Image*)mask, operation, x, y, width, height);
+    else
+    {
+        RI_ASSERT(!isMaskLayer ? !needInput : true);
+        drawable->getMaskBuffer()->mask(context->getBlitter(), (!mask || !needInput) ? NULL : ((Surface*)mask)->getImage(), operation, x, y, width, height);
+    }
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+void RI_APIENTRY vgRenderToMask(VGPath path, VGbitfield paintModes, VGMaskOperation operation)
+{
+    Path* iPath = (Path*)path;
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!paintModes || (paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+    RI_IF_ERROR(operation < VG_CLEAR_MASK || operation > VG_SUBTRACT_MASK, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* curr = context->getCurrentDrawable();
+    const Surface* mask = curr->getMaskBuffer();
+    if(!curr || !curr->getMaskBuffer())
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment or context has no mask buffer
+    }
+
+    if(operation == VG_CLEAR_MASK || operation == VG_FILL_MASK)
+    {
+        //RI_ASSERT(false); // should call fill!
+        Image* dummy = NULL;
+        curr->getMaskBuffer()->mask(context->getBlitter(), dummy, operation, 0, 0, curr->getWidth(), curr->getHeight());
+        RI_RETURN(RI_NO_RETVAL);
+    }
+
+    try
+    {
+        // Create a temporary image to render the path on for some mask operations.
+        // \todo tero: There are optimizations that can do all the mask operations in one pass, but it
+        // takes too much time to implement them now.
+        Drawable *tmpDrawable = NULL;
+        
+        try 
+        {
+            if (operation == VG_INTERSECT_MASK)
+            {
+                tmpDrawable = RI_NEW(Drawable, (Color::formatToDescriptor(VG_A_8), curr->getWidth(), curr->getHeight(), 1, 0));
+            }
+        } catch (std::bad_alloc e)
+        {
+            throw e;
+        }
+         
+        //Drawable drawable(Color::formatToDescriptor(VG_A_8), curr->getWidth(), curr->getHeight(), curr->getNumSamples(), 1);    //TODO 0 mask bits (mask buffer is not used)
+
+        Rasterizer& rasterizer = context->m_rasterizer;
+        rasterizer.clear();
+
+        rasterizer.setScissoring(context->m_scissoring ? true : false);
+        if(context->m_scissoring)
+            rasterizer.setScissor(context->m_scissor);	//throws bad_alloc
+
+        PixelPipe& pixelPipe = context->m_pixelPipe;
+
+        // \hack If the mask operation is intersect, we render normally to tempbuffer!
+        if (!tmpDrawable)
+            pixelPipe.setRenderToMask(true);
+        else
+            pixelPipe.setRenderToMask(false);
+
+        bool skipFill = false;
+
+        if (operation == VG_SET_MASK)
+        {
+            Surface *maskSurface = curr->getMaskBuffer();
+            maskSurface->clear(Color(), 0, 0, maskSurface->getWidth(), maskSurface->getHeight());
+            skipFill = true;
+        }
+
+        skipFill = skipFill && (paintModes & VG_STROKE_PATH);
+
+        pixelPipe.setMaskOperation(operation);
+        pixelPipe.setDrawable(tmpDrawable ? tmpDrawable : curr);
+        pixelPipe.setImage(NULL, VG_DRAW_IMAGE_NORMAL);
+        pixelPipe.setMask(false);
+        pixelPipe.setPaint(NULL);   //use default paint (solid color alpha = 1)
+        pixelPipe.setBlendMode(VG_BLEND_SRC_OVER);   //write solid color * coverage to dest
+        bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true;
+        rasterizer.setAntiAliasing(aa);
+
+        Matrix3x3 userToSurface = context->m_pathUserToSurface;
+        userToSurface[2].set(0,0,1);	//force affinity
+
+        if((paintModes & VG_FILL_PATH) && (!skipFill))
+        {
+            rasterizer.clear();
+            rasterizer.setup(0, 0, mask->getWidth(), mask->getHeight(), context->m_fillRule, &pixelPipe);
+            pixelPipe.prepareSpanUniforms(aa);
+            iPath->fill(userToSurface, rasterizer);	//throws bad_alloc
+            rasterizer.fill();	//throws bad_alloc
+            //curr->getMaskBuffer()->mask(drawable.getColorBuffer(), operation, 0, 0, drawable.getWidth(), drawable.getHeight());
+            if (tmpDrawable)
+            {
+                RI_ASSERT(operation == VG_INTERSECT_MASK);
+                curr->getMaskBuffer()->mask(context->getBlitter(), tmpDrawable->getColorBuffer()->getImage(), operation, 0, 0, tmpDrawable->getWidth(), tmpDrawable->getHeight());
+
+                if (paintModes & VG_STROKE_PATH)
+                {
+                    Surface* tmpSurf = tmpDrawable->getColorBuffer();
+                    tmpSurf->clear(Color(), 0, 0, 
+                        tmpSurf->getWidth(), tmpSurf->getHeight());
+                }
+                else
+                {
+                    RI_DELETE(tmpDrawable);
+                    tmpDrawable = NULL;
+                }
+            }
+
+        }
+
+        if((paintModes & VG_STROKE_PATH) && context->m_strokeLineWidth > 0.0f)
+        {
+            pixelPipe.prepareSpanUniforms(aa);
+            rasterizer.clear();
+            rasterizer.setup(0, 0, mask->getWidth(), mask->getHeight(), VG_NON_ZERO, &pixelPipe);
+
+            iPath->stroke(userToSurface, rasterizer, context->m_strokeDashPattern, context->m_strokeDashPhase, context->m_strokeDashPhaseReset ? true : false,
+                 context->m_strokeLineWidth, context->m_strokeCapStyle, context->m_strokeJoinStyle, RI_MAX(context->m_strokeMiterLimit, 1.0f));	//throws bad_alloc
+            rasterizer.fill();	//throws bad_alloc
+            //curr->getMaskBuffer()->mask(drawable.getColorBuffer(), operation, 0, 0, drawable.getWidth(), drawable.getHeight());
+
+            if (tmpDrawable)
+            {
+                RI_ASSERT(operation == VG_INTERSECT_MASK);
+                curr->getMaskBuffer()->mask(context->getBlitter(), tmpDrawable->getColorBuffer()->getImage(), operation, 0, 0, tmpDrawable->getWidth(), tmpDrawable->getHeight());
+                RI_DELETE(tmpDrawable);
+                tmpDrawable = NULL;
+            }
+        }
+        RI_ASSERT(!tmpDrawable);
+
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGMaskLayer RI_APIENTRY vgCreateMaskLayer(VGint width, VGint height)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(width > RI_MAX_IMAGE_WIDTH || height > RI_MAX_IMAGE_HEIGHT || width*height > RI_MAX_IMAGE_PIXELS ||
+                width*height > RI_MAX_IMAGE_BYTES, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    Drawable* curr = context->getCurrentDrawable();
+    if(!curr || !curr->getMaskBuffer())
+        RI_RETURN(VG_INVALID_HANDLE);   //no current drawing surface
+
+    Surface* layer = NULL;
+    try
+    {
+        layer = RI_NEW(Surface, (Color::formatToDescriptor(VG_A_8), width, height, curr->getNumSamples()));	//throws bad_alloc
+        RI_ASSERT(layer);
+        context->m_maskLayerManager->addResource(layer, context);	//throws bad_alloc
+        layer->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height);
+        RI_RETURN((VGMaskLayer)layer);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(layer);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyMaskLayer(VGMaskLayer maskLayer)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid handle
+
+    context->m_maskLayerManager->removeResource((Surface*)maskLayer);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgFillMaskLayer(VGMaskLayer maskLayer, VGint x, VGint y, VGint width, VGint height, VGfloat value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid handle
+    RI_IF_ERROR(value < 0.0f || value > 1.0f, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Surface* layer = (Surface*)maskLayer;
+    RI_IF_ERROR(width <= 0 || height <= 0 || x < 0 || y < 0 || x > layer->getWidth()-width || y > layer->getHeight()-height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    layer->clear(Color(1,1,1,value,Color::sRGBA), x, y, width, height);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgCopyMask(VGMaskLayer maskLayer, VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid handle
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable || !drawable->getMaskBuffer())
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment or context has no mask buffer
+    }
+    Surface* layer = (Surface*)maskLayer;
+    RI_IF_ERROR(width <= 0 || height <= 0 || drawable->getNumSamples() != layer->getNumSamples(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {   //copy drawing surface mask to mask layer
+        // \note Removed support for msaa
+        layer->m_image->blit(context, drawable->getMaskBuffer()->getImage(), sx, sy, dx, dy, width, height);
+        //layer->blit(drawable->getMaskBuffer(), sx, sy, dx, dy, width, height);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgClear(VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+
+    try
+    {
+        if(context->m_scissoring)
+            drawable->getColorBuffer()->clear(context->m_clearColor, x, y, width, height, &context->m_scissor);	//throws bad_alloc
+        else
+            drawable->getColorBuffer()->clear(context->m_clearColor, x, y, width, height);
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGPath RI_APIENTRY vgCreatePath(VGint pathFormat, VGPathDatatype datatype, VGfloat scale, VGfloat bias, VGint segmentCapacityHint, VGint coordCapacityHint, VGbitfield capabilities)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(pathFormat != VG_PATH_FORMAT_STANDARD, VG_UNSUPPORTED_PATH_FORMAT_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(datatype < VG_PATH_DATATYPE_S_8 || datatype > VG_PATH_DATATYPE_F, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    RIfloat s = inputFloat(scale);
+    RIfloat b = inputFloat(bias);
+    RI_IF_ERROR(s == 0.0f, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    capabilities &= VG_PATH_CAPABILITY_ALL;	//undefined bits are ignored
+
+    Path* path = NULL;
+    try
+    {
+        path = RI_NEW(Path, (pathFormat, datatype, s, b, segmentCapacityHint, coordCapacityHint, capabilities));	//throws bad_alloc
+        RI_ASSERT(path);
+        context->m_pathManager->addResource(path, context);	//throws bad_alloc
+        RI_RETURN((VGPath)path);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(path);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgClearPath(VGPath path, VGbitfield capabilities)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    capabilities &= VG_PATH_CAPABILITY_ALL;	//undefined bits are ignored
+    ((Path*)path)->clear(capabilities);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyPath(VGPath path)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+
+    context->m_pathManager->removeResource((Path*)path);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgRemovePathCapabilities(VGPath path, VGbitfield capabilities)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    capabilities &= VG_PATH_CAPABILITY_ALL;	//undefined bits are ignored
+
+    VGbitfield caps = ((Path*)path)->getCapabilities();
+    caps &= ~capabilities;
+    ((Path*)path)->setCapabilities(caps);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGbitfield RI_APIENTRY vgGetPathCapabilities(VGPath path)
+{
+    RI_GET_CONTEXT(0);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, 0);	//invalid path handle
+    VGbitfield ret = ((Path*)path)->getCapabilities();
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgAppendPathData(VGPath dstPath, VGint numSegments, const VGubyte * pathSegments, const void * pathData)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(dstPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    Path* p = (Path*)dstPath;
+    RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_APPEND_TO), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//no append cap
+    RI_IF_ERROR(numSegments <= 0 || !pathSegments || !pathData, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//no segments or data
+    RI_IF_ERROR((p->getDatatype() == VG_PATH_DATATYPE_S_16 && !isAligned(pathData,2)) ||
+                ((p->getDatatype() == VG_PATH_DATATYPE_S_32 || p->getDatatype() == VG_PATH_DATATYPE_F) && !isAligned(pathData,4)),
+                VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid alignment
+    for(int i=0;i<numSegments;i++)
+    {
+        VGPathSegment c = (VGPathSegment)(pathSegments[i] & 0x1e);
+        RI_IF_ERROR(c < VG_CLOSE_PATH || c > VG_LCWARC_TO, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid segment
+        RI_IF_ERROR(c & ~0x1f, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//reserved bits are nonzero
+    }
+
+    try
+    {
+        p->appendData((const RIuint8*)pathSegments, numSegments, (const RIuint8*)pathData);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgModifyPathCoords(VGPath dstPath, VGint startIndex, VGint numSegments, const void * pathData)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(dstPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    Path* p = (Path*)dstPath;
+    RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_MODIFY), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//no modify cap
+    RI_IF_ERROR(!pathData || startIndex < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startIndex, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//no segments
+    RI_IF_ERROR((p->getDatatype() == VG_PATH_DATATYPE_S_16 && !isAligned(pathData,2)) ||
+                ((p->getDatatype() == VG_PATH_DATATYPE_S_32 || p->getDatatype() == VG_PATH_DATATYPE_F) && !isAligned(pathData,4)),
+                VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid alignment
+    p->modifyCoords(startIndex, numSegments, (const RIuint8*)pathData);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgAppendPath(VGPath dstPath, VGPath srcPath)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(srcPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_APPEND_TO) ||
+                !(((Path*)srcPath)->getCapabilities() & VG_PATH_CAPABILITY_APPEND_FROM), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+
+    try
+    {
+        ((Path*)dstPath)->append((Path*)srcPath);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgTransformPath(VGPath dstPath, VGPath srcPath)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(srcPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_TRANSFORM_TO) ||
+                !(((Path*)srcPath)->getCapabilities() & VG_PATH_CAPABILITY_TRANSFORM_FROM), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+    try
+    {
+        ((Path*)dstPath)->transform((Path*)srcPath, context->m_pathUserToSurface);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static bool drawPath(VGContext* context, VGPath path, const Matrix3x3& userToSurfaceMatrix, VGbitfield paintModes)
+{
+    Path* iPath = (Path*)path;
+    //set up rendering surface and mask buffer
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+        return false;   //no EGL surface is current at the moment
+
+    Rasterizer& rasterizer = context->m_rasterizer;
+    rasterizer.clear();
+
+    if(context->m_scissoring)
+    {
+        rasterizer.setScissor(context->m_scissor);	//throws bad_alloc
+    }
+    rasterizer.setScissoring(context->m_scissoring ? true : false);
+
+    PixelPipe& pixelPipe = context->m_pixelPipe;
+    pixelPipe.setRenderToMask(false);
+    pixelPipe.setDrawable(drawable);
+    pixelPipe.setImage(NULL, VG_DRAW_IMAGE_NORMAL);
+    pixelPipe.setMask(context->m_masking ? true : false);
+    pixelPipe.setBlendMode(context->m_blendMode);
+    pixelPipe.setTileFillColor(context->m_tileFillColor);
+    pixelPipe.setImageQuality(context->m_imageQuality);
+    pixelPipe.setColorTransform(context->m_colorTransform ? true : false, context->m_colorTransformValues);
+    bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true;
+    rasterizer.setAntiAliasing(aa);
+
+    Matrix3x3 userToSurface = userToSurfaceMatrix;
+    userToSurface[2].set(0,0,1);	//force affinity
+
+    if(paintModes & VG_FILL_PATH)
+    {
+        // \todo Reorganize so that pipe.setpaint handles/requires the matrix setup?
+        pixelPipe.setPaint((Paint*)context->m_fillPaint);
+
+        Matrix3x3 paintToSurfaceMatrix = userToSurface * context->m_fillPaintToUser;
+        Matrix3x3 surfaceToPaintMatrix = paintToSurfaceMatrix; 
+        if(surfaceToPaintMatrix.invert())
+        {
+            surfaceToPaintMatrix[2].set(0,0,1);		//force affinity
+            pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+            pixelPipe.prepareSpanUniforms(aa);
+
+            rasterizer.clear();
+            rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), context->m_fillRule, &pixelPipe);
+            iPath->fill(userToSurface, rasterizer);	//throws bad_alloc
+            rasterizer.fill();	//throws bad_alloc
+        }
+    }
+
+    if(paintModes & VG_STROKE_PATH && context->m_strokeLineWidth > 0.0f)
+    {
+        pixelPipe.setPaint((Paint*)context->m_strokePaint);
+
+        Matrix3x3 paintToSurfaceMatrix = userToSurface * context->m_strokePaintToUser;
+        Matrix3x3 surfaceToPaintMatrix = paintToSurfaceMatrix; 
+        if(surfaceToPaintMatrix.invert())
+        {
+            surfaceToPaintMatrix[2].set(0,0,1);		//force affinity
+            pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+            pixelPipe.prepareSpanUniforms(aa);
+
+            rasterizer.clear();
+            rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_NON_ZERO, &pixelPipe);
+            iPath->stroke(userToSurface, rasterizer, context->m_strokeDashPattern, context->m_strokeDashPhase, context->m_strokeDashPhaseReset ? true : false,
+                 context->m_strokeLineWidth, context->m_strokeCapStyle, context->m_strokeJoinStyle, RI_MAX(context->m_strokeMiterLimit, 1.0f));	//throws bad_alloc
+            rasterizer.fill();	//throws bad_alloc
+
+        }
+    }
+    return true;
+}
+
+void RI_APIENTRY vgDrawPath(VGPath path, VGbitfield paintModes)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!paintModes || (paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+
+    try
+    {
+		eglvgLockSurface(0, 1);
+        if(!drawPath(context, path, context->m_pathUserToSurface, paintModes))
+        {
+			eglvgUnlockSurface();
+            RI_RETURN(RI_NO_RETVAL);
+        }
+		eglvgUnlockSurface();
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGfloat RI_APIENTRY vgPathLength(VGPath path, VGint startSegment, VGint numSegments)
+{
+    RI_GET_CONTEXT(-1.0f);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, -1.0f);	//invalid path handle
+    Path* p = (Path*)path;
+    RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_PATH_LENGTH), VG_PATH_CAPABILITY_ERROR, -1.0f);	//invalid caps
+    RI_IF_ERROR(startSegment < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startSegment, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, -1.0f);
+    RIfloat pathLength = -1.0f;
+    try
+    {
+        pathLength = p->getPathLength(startSegment, numSegments);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(pathLength);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgPointAlongPath(VGPath path, VGint startSegment, VGint numSegments, VGfloat distance, VGfloat * x, VGfloat * y, VGfloat * tangentX, VGfloat * tangentY)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    Path* p = (Path*)path;
+    RI_IF_ERROR((x && y && !(p->getCapabilities() & VG_PATH_CAPABILITY_POINT_ALONG_PATH)) ||
+                (tangentX && tangentY && !(p->getCapabilities() & VG_PATH_CAPABILITY_TANGENT_ALONG_PATH)), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+    RI_IF_ERROR(startSegment < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startSegment, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isAligned(x,4) || !isAligned(y,4) || !isAligned(tangentX,4) || !isAligned(tangentY,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {
+        Vector2 point, tangent;
+        p->getPointAlong(startSegment, numSegments, distance, point, tangent);	//throws bad_alloc
+        if(x && y)
+        {
+            *x = point.x;
+            *y = point.y;
+        }
+        if(tangentX && tangentY)
+        {
+            tangent.normalize();
+            *tangentX = tangent.x;
+            *tangentY = tangent.y;
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgPathBounds(VGPath path, VGfloat * minx, VGfloat * miny, VGfloat * width, VGfloat * height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)path)->getCapabilities() & VG_PATH_CAPABILITY_PATH_BOUNDS), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+    RI_IF_ERROR(!minx || !miny || !width || !height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isAligned(minx,4) || !isAligned(miny,4) || !isAligned(width,4) || !isAligned(height,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {
+        RIfloat pminx,pminy,pmaxx,pmaxy;
+        ((Path*)path)->getPathBounds(pminx, pminy, pmaxx, pmaxy);	//throws bad_alloc
+        *minx = pminx;
+        *miny = pminy;
+        *width = pmaxx - pminx;
+        *height = pmaxy - pminy;
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgPathTransformedBounds(VGPath path, VGfloat * minx, VGfloat * miny, VGfloat * width, VGfloat * height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)path)->getCapabilities() & VG_PATH_CAPABILITY_PATH_TRANSFORMED_BOUNDS), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+    RI_IF_ERROR(!minx || !miny || !width || !height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isAligned(minx,4) || !isAligned(miny,4) || !isAligned(width,4) || !isAligned(height,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {
+        RIfloat pminx, pminy, pmaxx, pmaxy;
+        ((Path*)path)->getPathTransformedBounds(context->m_pathUserToSurface, pminx, pminy, pmaxx, pmaxy);	//throws bad_alloc
+        *minx = pminx;
+        *miny = pminy;
+        *width = pmaxx - pminx;
+        *height = pmaxy - pminy;
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGboolean RI_APIENTRY vgInterpolatePath(VGPath dstPath, VGPath startPath, VGPath endPath, VGfloat amount)
+{
+    RI_GET_CONTEXT(VG_FALSE);
+    RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(startPath) || !context->isValidPath(endPath), VG_BAD_HANDLE_ERROR, VG_FALSE);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_TO) ||
+                !(((Path*)startPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_FROM) ||
+                !(((Path*)endPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_FROM), VG_PATH_CAPABILITY_ERROR, VG_FALSE);	//invalid caps
+    VGboolean ret = VG_FALSE;
+    try
+    {
+        if(((Path*)dstPath)->interpolate((const Path*)startPath, (const Path*)endPath, inputFloat(amount)))	//throws bad_alloc
+            ret = VG_TRUE;
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGPaint RI_APIENTRY vgCreatePaint(void)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    Paint* paint = NULL;
+    RI_TRACE("\n***** vgCreatePaint\n");
+    try
+    {
+        paint = RI_NEW(Paint, ());	//throws bad_alloc
+        RI_ASSERT(paint);
+        context->m_paintManager->addResource(paint, context);	//throws bad_alloc
+        RI_TRACE("===== vgCreatePaint: Created paint obj: %x\n", (int)paint);
+        RI_RETURN((VGPaint)paint);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(paint);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyPaint(VGPaint paint)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid paint handle
+
+    context->m_paintManager->removeResource((Paint*)paint);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetPaint(VGPaint paint, VGbitfield paintModes)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_TRACE("\n***** vgSetPaint: %x mode: %d\n", (int)paint, (int)paintModes);
+    RI_IF_ERROR(paint && !context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid paint handle
+    RI_IF_ERROR(!paintModes || paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+
+    context->releasePaint(paintModes);
+
+    if(paintModes & VG_FILL_PATH)
+    {
+        if(paint)
+            ((Paint*)paint)->addReference();
+        context->m_fillPaint = paint;
+    }
+    if(paintModes & VG_STROKE_PATH)
+    {
+        if(paint)
+            ((Paint*)paint)->addReference();
+        context->m_strokePaint = paint;
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetColor(VGPaint paint, VGuint rgba)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_TRACE("\n***** vgSetColor: %x, rgba: %x\n", paint, rgba);
+    RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid paint handle
+    Paint* p = (Paint*)paint;
+    p->m_inputPaintColor.unpack(rgba, Color::formatToDescriptor(VG_sRGBA_8888));
+    p->setColor(inputColor(p->m_inputPaintColor));
+    RI_TRACE("** -> [%.3f %.3f %.3f %.3f]\n", p->m_paintColor.r, p->m_paintColor.g, p->m_paintColor.b, p->m_paintColor.a);
+//    p->m_paintColor = inputColor(p->m_inputPaintColor);
+//    p->m_paintColor.clamp();
+//    p->m_paintColor.premultiply();
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGuint RI_APIENTRY vgGetColor(VGPaint paint)
+{
+    RI_GET_CONTEXT(0);
+    RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, 0);	//invalid paint handle
+    Color tempColor = ((Paint*)paint)->m_inputPaintColor;
+    tempColor.clamp();
+    unsigned int ret = tempColor.pack(Color::formatToDescriptor(VG_sRGBA_8888));
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGPaint RI_APIENTRY vgGetPaint(VGPaintMode paintMode)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(paintMode != VG_FILL_PATH && paintMode != VG_STROKE_PATH, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);	//invalid paint mode
+
+    if(paintMode == VG_FILL_PATH)
+    {
+        RI_RETURN(context->m_fillPaint);
+    }
+    RI_RETURN(context->m_strokePaint);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgPaintPattern(VGPaint paint, VGImage image)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPaint(paint) || (image != VG_INVALID_HANDLE && !context->isValidImage(image)), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid handle
+    Image* img = (Image*)image;
+    Paint* pnt = (Paint*)paint;
+    RI_IF_ERROR(image != VG_INVALID_HANDLE && eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    Image* pattern = pnt->m_pattern;
+    if(pattern)
+    {
+        pattern->removeInUse();
+        if(!pattern->removeReference())
+            RI_DELETE(pattern);
+    }
+    pnt->m_pattern = img;
+
+    if(img)
+    {
+        img->addReference();
+        img->addInUse();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGImage RI_APIENTRY vgCreateImage(VGImageFormat format, VGint width, VGint height, VGbitfield allowedQuality)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(!isValidImageFormat(format), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(width <= 0 || height <= 0 || !allowedQuality ||
+                (allowedQuality & ~(VG_IMAGE_QUALITY_NONANTIALIASED | VG_IMAGE_QUALITY_FASTER | VG_IMAGE_QUALITY_BETTER)), VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(width > RI_MAX_IMAGE_WIDTH || height > RI_MAX_IMAGE_HEIGHT || width*height > RI_MAX_IMAGE_PIXELS ||
+                ((width*Color::formatToDescriptor(format).bitsPerPixel+7)/8)*height > RI_MAX_IMAGE_BYTES, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+
+    Image* image = NULL;
+    try
+    {
+        image = RI_NEW(Image, (Color::formatToDescriptor(format), width, height, allowedQuality));	//throws bad_alloc
+        RI_ASSERT(image);
+        context->m_imageManager->addResource(image, context);	//throws bad_alloc
+        RI_RETURN((VGImage)image);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(image);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyImage(VGImage image)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid image handle
+
+    context->m_imageManager->removeResource((Image*)image);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgClearImage(VGImage image, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* img = (Image*)image;
+    RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+	eglvgLockSurface(0, 1);
+    img->clear(context->m_clearColor, x, y, width, height);
+	eglvgUnlockSurface();
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgImageSubData(VGImage image, const void * data, VGint dataStride, VGImageFormat dataFormat, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* img = (Image*)image;
+    RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    {
+        Image input(Color::formatToDescriptor(dataFormat), width, height, dataStride, const_cast<RIuint8*>((const RIuint8*)data));
+        input.addReference();
+        try
+        {
+            img->blit(context, &input, 0, 0, x, y, width, height);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+        }
+        input.removeReference();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetImageSubData(VGImage image, void * data, VGint dataStride, VGImageFormat dataFormat, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* img = (Image*)image;
+    RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    {
+        Image output(Color::formatToDescriptor(dataFormat), width, height, dataStride, (RIuint8*)data);
+        output.addReference();
+        try
+        {
+            output.blit(context, img, x, y, 0, 0, width, height);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+        }
+        output.removeReference();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGImage RI_APIENTRY vgChildImage(VGImage parent, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(!context->isValidImage(parent), VG_BAD_HANDLE_ERROR, VG_INVALID_HANDLE);
+    Image* p = (Image*)parent;
+    RI_IF_ERROR(eglvgIsInUse((Image*)parent), VG_IMAGE_IN_USE_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(x < 0 || x >= p->getWidth() || y < 0 || y >= p->getHeight() ||
+                width <= 0 || height <= 0 || RI_INT_ADDSATURATE(x, width) > p->getWidth() || RI_INT_ADDSATURATE(y, height) > p->getHeight(), VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+
+    Image* child = NULL;
+    try
+    {
+        child = RI_NEW(Image, (p, x, y, width, height));	//throws bad_alloc
+        RI_ASSERT(child);
+        context->m_imageManager->addResource(child, context);	//throws bad_alloc
+        RI_RETURN((VGImage)child);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(child);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGImage RI_APIENTRY vgGetParent(VGImage image)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, VG_INVALID_HANDLE);
+    VGImage ret = image;	//if image has no ancestors, image is returned.
+
+    //The vgGetParent function returns the closest valid ancestor (i.e., one that has not been the target of a vgDestroyImage call)
+    // of the given image.
+    Image* im = ((Image*)image)->getParent();
+    for(;im;im = im->getParent())
+    {
+        if(context->isValidImage((VGImage)im))
+        {	//the parent is valid and alive
+            ret = (VGImage)im;
+            break;
+        }
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgCopyImage(VGImage dst, VGint dx, VGint dy, VGImage src, VGint sx, VGint sy, VGint width, VGint height, VGboolean dither)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(eglvgIsInUse((Image*)dst) || eglvgIsInUse((Image*)src), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {
+        ((Image*)dst)->blit(context, (Image*)src, sx, sy, dx, dy, width, height, NULL, dither ? true : false);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+ 
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static bool drawImage(VGContext* context, VGImage image, const Matrix3x3& userToSurfaceMatrix)
+{
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+        return false;   //no EGL surface is current at the moment
+
+    Image* img = (Image*)image;
+    //transform image corners into the surface space
+    Vector3 p0(0, 0, 1);
+    Vector3 p1(0, (RIfloat)img->getHeight(), 1);
+    Vector3 p2((RIfloat)img->getWidth(), (RIfloat)img->getHeight(), 1);
+    Vector3 p3((RIfloat)img->getWidth(), 0, 1);
+    p0 = userToSurfaceMatrix * p0;
+    p1 = userToSurfaceMatrix * p1;
+    p2 = userToSurfaceMatrix * p2;
+    p3 = userToSurfaceMatrix * p3;
+    if(p0.z <= 0.0f || p1.z <= 0.0f || p2.z <= 0.0f || p3.z <= 0.0f)
+        return false;
+
+    //projection
+    p0 *= 1.0f/p0.z;
+    p1 *= 1.0f/p1.z;
+    p2 *= 1.0f/p2.z;
+    p3 *= 1.0f/p3.z;
+
+    Rasterizer& rasterizer = context->m_rasterizer;
+    rasterizer.clear();
+
+    rasterizer.setScissoring(context->m_scissoring ? true : false);
+    if(context->m_scissoring)
+        rasterizer.setScissor(context->m_scissor);	//throws bad_alloc
+
+    PixelPipe& pixelPipe = context->m_pixelPipe;
+    pixelPipe.setTileFillColor(context->m_tileFillColor);
+    pixelPipe.setPaint((Paint*)context->m_fillPaint);
+    pixelPipe.setImageQuality(context->m_imageQuality);
+    pixelPipe.setBlendMode(context->m_blendMode);
+    pixelPipe.setRenderToMask(false);
+    pixelPipe.setDrawable(drawable);
+    pixelPipe.setMask(context->m_masking ? true : false);
+    pixelPipe.setColorTransform(context->m_colorTransform ? true : false, context->m_colorTransformValues);
+    const bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true;
+    rasterizer.setAntiAliasing(aa);
+
+    Matrix3x3 surfaceToImageMatrix = userToSurfaceMatrix;
+    Matrix3x3 surfaceToPaintMatrix = userToSurfaceMatrix * context->m_fillPaintToUser;
+    if(surfaceToImageMatrix.invert() && surfaceToPaintMatrix.invert())
+    {
+        VGImageMode imode = context->m_imageMode;
+        if(!surfaceToPaintMatrix.isAffine())
+            imode = VG_DRAW_IMAGE_NORMAL;	//if paint matrix is not affine, always use normal image mode
+        surfaceToPaintMatrix[2].set(0,0,1);	//force affine
+
+        pixelPipe.setImage(img, imode);
+        pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+        pixelPipe.setSurfaceToImageMatrix(surfaceToImageMatrix);
+        pixelPipe.prepareSpanUniforms(aa);
+        rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_EVEN_ODD, &pixelPipe);
+
+        rasterizer.addEdge(Vector2(p0.x,p0.y), Vector2(p1.x,p1.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p1.x,p1.y), Vector2(p2.x,p2.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p2.x,p2.y), Vector2(p3.x,p3.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p3.x,p3.y), Vector2(p0.x,p0.y));	//throws bad_alloc
+
+        rasterizer.fill();	//throws bad_alloc
+    }
+    return true;
+}
+
+void RI_APIENTRY vgDrawImage(VGImage image)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* img = (Image*)image;
+    RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+
+    try
+    {
+        if(!drawImage(context, image, context->m_imageUserToSurface))
+        {
+            RI_RETURN(RI_NO_RETVAL);
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetPixels(VGint dx, VGint dy, VGImage src, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(eglvgIsInUse((Image*)src), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+
+    Drawable* drawable = context->getCurrentDrawable();
+    Array<OpenVGRI::Rectangle>* scissors = !context->m_scissoring ? NULL : &context->m_scissor;
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    try
+    {
+        drawable->getColorBuffer()->m_image->blit(context, (Image*)src, sx, sy, dx, dy, width, height, scissors, false);	//throws bad_alloc
+        //drawable->getColorBuffer()->blit(*(Image*)src, sx, sy, dx, dy, width, height);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgWritePixels(const void * data, VGint dataStride, VGImageFormat dataFormat, VGint dx, VGint dy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    {
+        Array<OpenVGRI::Rectangle>* scissors = !context->m_scissoring ? NULL : &context->m_scissor;
+        Image input(Color::formatToDescriptor(dataFormat), width, height, dataStride, const_cast<RIuint8*>((const RIuint8*)data));
+        input.addReference();
+        try
+        {
+            drawable->getColorBuffer()->m_image->blit(context, &input, 0, 0, dx, dy, width, height, scissors, false);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+            // TEROP: out-of-mem?
+        }
+        input.removeReference();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetPixels(VGImage dst, VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(eglvgIsInUse((Image*)dst), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    try
+    {
+        ((Image*)dst)->blit(context, drawable->getColorBuffer()->m_image, sx, sy, dx, dy, width, height);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgReadPixels(void* data, VGint dataStride, VGImageFormat dataFormat, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    {
+        Image output(Color::formatToDescriptor(dataFormat), width, height, dataStride, (RIuint8*)data);
+        output.addReference();
+        try
+        {
+            output.blit(context, drawable->getColorBuffer()->m_image, sx, sy, 0, 0, width, height);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+        }
+        output.removeReference();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgCopyPixels(VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    Array<OpenVGRI::Rectangle>* scissors = !context->m_scissoring ? NULL : &context->m_scissor;
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    try
+    {
+        drawable->getColorBuffer()->m_image->blit(context, drawable->getColorBuffer()->m_image, sx, sy, dx, dy, width, height, scissors, false);	//throws bad_alloc
+        //drawable->getColorBuffer()->blit(drawable->getColorBuffer(), sx, sy, dx, dy, width, height);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgColorMatrix(VGImage dst, VGImage src, const VGfloat * matrix)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!matrix || !isAligned(matrix,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+
+    RIfloat m[20];
+    for(int i=0;i<20;i++)
+    {
+        m[i] = inputFloat(matrix[i]);
+    }
+    try
+    {
+        d->colorMatrix(*s, m, context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgConvolve(VGImage dst, VGImage src, VGint kernelWidth, VGint kernelHeight, VGint shiftX, VGint shiftY, const VGshort * kernel, VGfloat scale, VGfloat bias, VGTilingMode tilingMode)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!kernel || !isAligned(kernel,2) || kernelWidth <= 0 || kernelHeight <= 0 || kernelWidth > RI_MAX_KERNEL_SIZE || kernelHeight > RI_MAX_KERNEL_SIZE, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->convolve(*s, kernelWidth, kernelHeight, shiftX, shiftY, (const RIint16*)kernel, inputFloat(scale), inputFloat(bias), tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSeparableConvolve(VGImage dst, VGImage src, VGint kernelWidth, VGint kernelHeight, VGint shiftX, VGint shiftY, const VGshort * kernelX, const VGshort * kernelY, VGfloat scale, VGfloat bias, VGTilingMode tilingMode)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!kernelX || !kernelY || !isAligned(kernelX,2) || !isAligned(kernelY,2) || kernelWidth <= 0 || kernelHeight <= 0 || kernelWidth > RI_MAX_SEPARABLE_KERNEL_SIZE || kernelHeight > RI_MAX_SEPARABLE_KERNEL_SIZE, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->separableConvolve(*s, kernelWidth, kernelHeight, shiftX, shiftY, (const RIint16*)kernelX, (const RIint16*)kernelY,
+                                         inputFloat(scale), inputFloat(bias), tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false,
+                                         context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGaussianBlur(VGImage dst, VGImage src, VGfloat stdDeviationX, VGfloat stdDeviationY, VGTilingMode tilingMode)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RIfloat sx = inputFloat(stdDeviationX);
+    RIfloat sy = inputFloat(stdDeviationY);
+    RI_IF_ERROR(sx <= 0.0f || sy <= 0.0f || sx > (RIfloat)RI_MAX_GAUSSIAN_STD_DEVIATION || sy > (RIfloat)RI_MAX_GAUSSIAN_STD_DEVIATION, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->gaussianBlur(*s, sx, sy, tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false,
+                        context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgLookup(VGImage dst, VGImage src, const VGubyte * redLUT, const VGubyte * greenLUT, const VGubyte * blueLUT, const VGubyte * alphaLUT, VGboolean outputLinear, VGboolean outputPremultiplied)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!redLUT || !greenLUT || !blueLUT || !alphaLUT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->lookup(*s, (const RIuint8*)redLUT, (const RIuint8*)greenLUT, (const RIuint8*)blueLUT, (const RIuint8*)alphaLUT,
+                  outputLinear ? true : false, outputPremultiplied ? true : false, context->m_filterFormatLinear ? true : false,
+                  context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgLookupSingle(VGImage dst, VGImage src, const VGuint * lookupTable, VGImageChannel sourceChannel, VGboolean outputLinear, VGboolean outputPremultiplied)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!lookupTable || !isAligned(lookupTable,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    const Color::Descriptor& desc = s->getDescriptor();
+    RI_ASSERT(Color::isValidDescriptor(desc));
+    //give an error if src is in rgb format and the source channel is not valid
+    RI_IF_ERROR((!desc.isLuminance() && !desc.isAlphaOnly()) && (sourceChannel != VG_RED && sourceChannel != VG_GREEN && sourceChannel != VG_BLUE && sourceChannel != VG_ALPHA), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->lookupSingle(*s, (const RIuint32*)lookupTable, sourceChannel, outputLinear ? true : false, outputPremultiplied ? true : false,
+                        context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGHardwareQueryResult RI_APIENTRY vgHardwareQuery(VGHardwareQueryType key, VGint setting)
+{
+    RI_GET_CONTEXT(VG_HARDWARE_UNACCELERATED);
+    RI_IF_ERROR(key != VG_IMAGE_FORMAT_QUERY && key != VG_PATH_DATATYPE_QUERY, VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED);
+    RI_IF_ERROR(key == VG_IMAGE_FORMAT_QUERY && !isValidImageFormat(setting), VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED);
+    RI_IF_ERROR(key == VG_PATH_DATATYPE_QUERY && (setting < VG_PATH_DATATYPE_S_8 || setting > VG_PATH_DATATYPE_F), VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED);
+    RI_RETURN(VG_HARDWARE_UNACCELERATED);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+     
+const VGubyte * RI_APIENTRY vgGetString(VGStringID name)
+{
+    static const VGubyte vendor[] = "Nokia";
+    static const VGubyte renderer[] = {"OpenVG 1.1 Faster Reference Implementation May 13 2008"};
+    static const VGubyte version[] = "1.1";
+    static const VGubyte extensions[] = "";
+    const VGubyte* r = NULL;
+    RI_GET_CONTEXT(NULL);
+    switch(name)
+    {
+    case VG_VENDOR:
+        r = vendor;
+        break;
+    case VG_RENDERER:
+        r = renderer;
+        break;
+    case VG_VERSION:
+        r = version;
+        break;
+    case VG_EXTENSIONS:
+        r = extensions;
+        break;
+    default:
+        break;
+    }
+    RI_RETURN(r);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGFont RI_APIENTRY vgCreateFont(VGint glyphCapacityHint)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(glyphCapacityHint < 0, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+
+    Font* font = NULL;
+    try
+    {
+        font = RI_NEW(Font, (glyphCapacityHint));	//throws bad_alloc
+        RI_ASSERT(font);
+        context->m_fontManager->addResource(font, context);	//throws bad_alloc
+        RI_RETURN((VGFont)font);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(font);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyFont(VGFont font)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+
+    context->m_fontManager->removeResource((Font*)font);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetGlyphToPath(VGFont font, VGuint glyphIndex, VGPath path, VGboolean isHinted, const VGfloat glyphOrigin[2], const VGfloat escapement[2])
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    RI_IF_ERROR(path != VG_INVALID_HANDLE && !context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!glyphOrigin || !escapement || !isAligned(glyphOrigin,sizeof(VGfloat)) || !isAligned(escapement,sizeof(VGfloat)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Font* f = (Font*)font;
+
+    try
+    {
+        f->setGlyphToPath(glyphIndex, path, isHinted ? true : false, Vector2(inputFloat(glyphOrigin[0]), inputFloat(glyphOrigin[1])), Vector2(inputFloat(escapement[0]), inputFloat(escapement[1])));
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetGlyphToImage(VGFont font, VGuint glyphIndex, VGImage image, const VGfloat glyphOrigin[2], const VGfloat escapement[2])
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    if(image != VG_INVALID_HANDLE)
+    {
+        RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid image handle
+        RI_IF_ERROR(eglvgIsInUse((Image*)image), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); //image in use
+    }
+    RI_IF_ERROR(!glyphOrigin || !escapement || !isAligned(glyphOrigin,sizeof(VGfloat)) || !isAligned(escapement,sizeof(VGfloat)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Font* f = (Font*)font;
+
+    try
+    {
+        f->setGlyphToImage(glyphIndex, image, Vector2(inputFloat(glyphOrigin[0]), inputFloat(glyphOrigin[1])), Vector2(inputFloat(escapement[0]), inputFloat(escapement[1])));
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgClearGlyph(VGFont font, VGuint glyphIndex)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    Font* f = (Font*)font;
+    Font::Glyph* g = f->findGlyph(glyphIndex);
+    RI_IF_ERROR(!g, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);   //glyphIndex not defined
+
+    f->clearGlyph(g);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDrawGlyph(VGFont font, VGuint glyphIndex, VGbitfield paintModes, VGboolean allowAutoHinting)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    RI_IF_ERROR(paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+    Font* f = (Font*)font;
+    Font::Glyph* g = f->findGlyph(glyphIndex);
+    RI_IF_ERROR(!g, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);   //glyphIndex not defined
+    RI_UNREF(allowAutoHinting); //RI doesn't implement autohinting
+
+    try
+    {
+        if(paintModes)
+        {
+            Matrix3x3 userToSurfaceMatrix = context->m_glyphUserToSurface;
+            Vector2 t = context->m_glyphOrigin - g->m_origin;
+            Matrix3x3 n(1, 0, t.x,
+                        0, 1, t.y,
+                        0, 0, 1 );
+            userToSurfaceMatrix *= n;
+            userToSurfaceMatrix[2].set(0,0,1);		//force affinity
+
+            bool ret = true;
+			eglvgLockSurface(0, 1);
+            if(g->m_image != VG_INVALID_HANDLE)
+                ret = drawImage(context, g->m_image, userToSurfaceMatrix);
+            else if(g->m_path != VG_INVALID_HANDLE)
+                ret = drawPath(context, g->m_path, userToSurfaceMatrix, paintModes);
+			eglvgUnlockSurface();
+            if(!ret)
+            {
+                RI_RETURN(RI_NO_RETVAL);
+            }
+        }
+
+        context->m_glyphOrigin += g->m_escapement;
+        context->m_inputGlyphOrigin = context->m_glyphOrigin;
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDrawGlyphs(VGFont font, VGint glyphCount, const VGuint *glyphIndices, const VGfloat *adjustments_x, const VGfloat *adjustments_y, VGbitfield paintModes, VGboolean allowAutoHinting)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    RI_IF_ERROR(!glyphIndices || !isAligned(glyphIndices, sizeof(VGuint)) || glyphCount <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR((adjustments_x && !isAligned(adjustments_x, sizeof(VGfloat))) || (adjustments_y && !isAligned(adjustments_y, sizeof(VGfloat))), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+    Font* f = (Font*)font;
+    for(int i=0;i<glyphCount;i++)
+    {
+        Font::Glyph* g = f->findGlyph(glyphIndices[i]);
+        RI_IF_ERROR(!g, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);   //glyphIndex not defined
+    }
+    RI_UNREF(allowAutoHinting); //RI doesn't implement autohinting
+
+    try
+    {
+        for(int i=0;i<glyphCount;i++)
+        {
+            Font::Glyph* g = f->findGlyph(glyphIndices[i]);
+
+            if(paintModes)
+            {
+                Matrix3x3 userToSurfaceMatrix = context->m_glyphUserToSurface;
+                Vector2 t = context->m_glyphOrigin - g->m_origin;
+                Matrix3x3 n(1, 0, t.x,
+                            0, 1, t.y,
+                            0, 0, 1 );
+                userToSurfaceMatrix *= n;
+                userToSurfaceMatrix[2].set(0,0,1);		//force affinity
+
+                bool ret = true;
+                if(g->m_image != VG_INVALID_HANDLE)
+                    ret = drawImage(context, g->m_image, userToSurfaceMatrix);
+                else if(g->m_path != VG_INVALID_HANDLE)
+                    ret = drawPath(context, g->m_path, userToSurfaceMatrix, paintModes);
+                if(!ret)
+                {
+                    RI_RETURN(RI_NO_RETVAL);
+                }
+            }
+
+            context->m_glyphOrigin += g->m_escapement;
+            if(adjustments_x)
+                context->m_glyphOrigin.x += inputFloat(adjustments_x[i]);
+            if(adjustments_y)
+                context->m_glyphOrigin.y += inputFloat(adjustments_y[i]);
+            context->m_inputGlyphOrigin = context->m_glyphOrigin;
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+	RI_RETURN(RI_NO_RETVAL);
+}
+
+VGint vgePathCoordsSizeInBytes(VGPath path, VGint startIndex, VGint numSegments)
+{
+    RI_GET_CONTEXT( 0 );
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, 0);
+    VGint ret = ((OpenVGRI::Path*)path)->coordsSizeInBytes( startIndex, numSegments );
+    RI_RETURN(ret);
+}
+
+
+VGImage vgCreateEGLImageTargetKHR(VGeglImageKHR image)
+{
+#if defined(USE_FULL_EGL)
+    RI_GET_CONTEXT( 0 );
+    VGImage ret;
+    OpenVGRI::Color::Descriptor desc;
+    OpenVGRI::RIuint8* data;
+    // Get data for VGImage
+    int width;
+    int height;
+    int stride;
+
+    eglvgGetImageDescriptor( image, desc, width, height, stride );
+    // There is some error.
+    // EGLImage is null or EGLImage target is EGL_VG_PARENT_IMAGE_KHR.
+    RI_IF_ERROR(!width || !height || !stride, VG_ILLEGAL_ARGUMENT_ERROR, NULL);
+    // Data is created in EGLImage class.
+    data = (OpenVGRI::RIuint8*)eglvgGetImageData( image );    
+    // Create VGImage
+    // allowedQuality = VG_IMAGE_QUALITY_NONANTIALIASED | VG_IMAGE_QUALITY_FASTER | VG_IMAGE_QUALITY_BETTER
+    ret = vgCreateImage( desc.vgFormat, width, height, VG_IMAGE_QUALITY_NONANTIALIASED );
+    // If VGImage is not created raise error and return null
+    RI_IF_ERROR(!ret, VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, NULL);
+    // Set data for VGImage.
+    // This will copy that data-object.
+    vgImageSubData( ret, 
+                    data, 
+                    stride, 
+                    desc.vgFormat, 
+                    0, 
+                    0,
+                    width, 
+                    height);
+    // Return VGImage
+    RI_RETURN(ret);
+#else
+    (void)image;
+    return VG_INVALID_HANDLE;
+#endif //USE_FULL_EGL
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riArray.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,242 @@
+#ifndef __RIARRAY_H
+#define __RIARRAY_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Array class.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIDEFS_H
+#include "riDefs.h"
+#endif
+
+#include <string.h>	//for memcpy
+
+namespace OpenVGRI
+{
+
+//=======================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \brief	An array class similar to std::vector.
+* \param
+* \return
+* \note		Follows std::vector's naming convention (except resizeAndReallocate).
+*//*-------------------------------------------------------------------*/
+
+template <class Item> class Array
+{
+public:
+    friend class Rasterizer;
+
+    Array() : m_array(NULL), m_size(0), m_allocated(0) {}	//throws bad_alloc
+    ~Array()
+    {
+        RI_DELETE_ARRAY(m_array);
+    }
+
+    void		swap(Array& s)
+    {
+        Item* tarray = m_array;
+        m_array = s.m_array;
+        s.m_array = tarray;
+
+        int tsize = m_size;
+        m_size = s.m_size;
+        s.m_size = tsize;
+
+        int tallocated = m_allocated;
+        m_allocated = s.m_allocated;
+        s.m_allocated = tallocated;
+    }
+
+    //if more room is needed, reallocate, otherwise return
+    void		reserve( int items )	//throws bad_alloc
+    {
+        RI_ASSERT( items >= 0 );
+        if( items <= m_allocated )
+            return;	//if there is room already, return
+
+        RI_ASSERT( items > m_allocated );
+
+        Item* newa = RI_NEW_ARRAY(Item, items);	//throws bad_alloc if runs out of memory
+        for(int i=0;i<m_size;i++)
+            newa[i] = m_array[i];
+        RI_DELETE_ARRAY(m_array);
+        m_array = newa;
+        m_allocated = items;
+        //doesn't change size
+    }
+
+    //reserve and change size
+    void		resize( int items )	//throws bad_alloc
+    {
+        reserve( items );	//throws bad_alloc if runs out of memory
+        m_size = items;
+    }
+
+    //resize and allocate exactly the correct amount of memory
+    void		resizeAndReallocate( int items )	//throws bad_alloc
+    {
+        RI_ASSERT( items >= 0 );
+        if( items == m_allocated )
+        {
+            m_size = items;
+            return;
+        }
+
+        if( items == 0 )
+        {
+            RI_DELETE_ARRAY(m_array);
+            m_size = 0;
+            m_allocated = 0;
+            return;
+        }
+
+        Item* newa = RI_NEW_ARRAY(Item, items);	//throws bad_alloc if runs out of memory
+        int copySize = (m_size < items) ? m_size : items;	//min(m_size,items)
+        for(int i=0;i<copySize;i++)
+            newa[i] = m_array[i];
+        RI_DELETE_ARRAY(m_array);
+        m_array = newa;
+        m_allocated = items;
+        m_size = items;		//changes also size
+    }
+    void		clear()
+    {
+        m_size = 0;
+    }
+
+    //sort array (needs operator< defined for Item. Define it with < for increasing order and > for decreasing.)
+    void		sort()
+    {
+        if(m_size <= 1)
+            return;
+        quicksort(0, m_size - 1);
+    }
+
+    void sort(int first, int last)
+    {
+        RI_ASSERT(first <= last);
+        RI_ASSERT((first >= 0) && (last < m_size));
+
+        if (m_size <= 1)
+            return;
+
+        if ((last - first) < 1)
+            return;
+
+        quicksort(first, last);
+#if defined(RI_DEBUG)
+        for (int i = first+1; i <= last; i++)
+        {
+            RI_ASSERT(m_array[i-1] <= m_array[i]);
+        }
+#endif
+    }
+
+    int     findIndex(const Item& item)
+    {
+        for(int i = 0; i < m_size; i++)
+            if (m_array[i] == item)
+                return i;
+        return -1;
+    }
+
+    //remove the first occurrence of an item from the array
+    bool        remove(const Item& item)
+    {
+        int i=0;
+        for(;i<m_size;i++)
+        {
+            if(m_array[i] == item)
+                break;
+        }
+        if(i >= m_size)
+            return false;   //not found
+        for(;i<m_size-1;i++)
+        {
+            m_array[i] = m_array[i+1];
+        }
+        m_size--;
+        return true;
+    }
+
+    RI_INLINE void			push_back( const Item& item )	//throws bad_alloc
+    {
+        if( m_size >= m_allocated )
+            reserve( (!m_allocated) ? 8 : m_allocated * 2 );	//by default, reserve 8. throws bad_alloc if runs out of memory
+        m_array[m_size++] = item;
+    }
+    RI_INLINE int			size() const				{ return m_size; }
+    RI_INLINE Item&			operator[](int i)			{ RI_ASSERT(i >= 0 && i < m_size); return m_array[i]; }
+    RI_INLINE const Item&	operator[](int i) const		{ RI_ASSERT(i >= 0 && i < m_size); return m_array[i]; }
+
+private:
+    Array(const Array& s);				//!< Not allowed.
+    void operator=(const Array& s);		//!< Not allowed.
+
+    void quicksort(int left, int right)
+    {
+        int i = left, j = right;
+        Item x = m_array[(left+right)>>1];
+
+        do
+        {
+            while (m_array[i] < x)
+                i++;
+            while (x < m_array[j])
+                j--;
+            if (i<=j)
+            {
+                Item tmp = m_array[i];
+                m_array[i] = m_array[j];
+                m_array[j] = tmp;
+                i++;
+                j--;
+            }
+        } while (i<=j);
+
+        if(left < j) quicksort(left, j);
+        if(i < right) quicksort(i, right);
+    }
+
+
+    Item*		m_array;
+    int			m_size;
+    int			m_allocated;
+};
+
+//=======================================================================
+
+}	//namespace OpenVGRI
+
+#endif /* __RIARRAY_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riContext.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,332 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of VGContext functions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "riContext.h"
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	VGContext constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGContext::VGContext(VGContext* shareContext) :
+    // Mode settings
+    m_matrixMode(VG_MATRIX_PATH_USER_TO_SURFACE),
+    m_fillRule(VG_EVEN_ODD),
+    m_imageQuality(VG_IMAGE_QUALITY_FASTER),
+    m_renderingQuality(VG_RENDERING_QUALITY_BETTER),
+    m_blendMode(VG_BLEND_SRC_OVER),
+    m_imageMode(VG_DRAW_IMAGE_NORMAL),
+
+    // Scissor rectangles
+    m_scissor(),
+
+    // Stroke parameters
+    m_strokeLineWidth(1.0f),
+    m_inputStrokeLineWidth(1.0f),
+    m_strokeCapStyle(VG_CAP_BUTT),
+    m_strokeJoinStyle(VG_JOIN_MITER),
+    m_strokeMiterLimit(4.0f),
+    m_inputStrokeMiterLimit(4.0f),
+    m_strokeDashPattern(),
+    m_inputStrokeDashPattern(),
+    m_strokeDashPhase(0.0f),
+    m_inputStrokeDashPhase(0.0f),
+    m_strokeDashPhaseReset(VG_FALSE),
+
+    // Edge fill color for vgConvolve and pattern paint
+    m_tileFillColor(0,0,0,0, Color::sRGBA),
+    m_inputTileFillColor(0,0,0,0, Color::sRGBA),
+
+    // Color for vgClear
+    m_clearColor(0,0,0,0, Color::sRGBA),
+    m_inputClearColor(0,0,0,0, Color::sRGBA),
+
+    m_glyphOrigin(0.0f, 0.0f),
+    m_inputGlyphOrigin(0.0f, 0.0f),
+
+    m_masking(VG_FALSE),
+    m_scissoring(VG_FALSE),
+
+    m_pixelLayout(VG_PIXEL_LAYOUT_UNKNOWN),
+
+    m_filterFormatLinear(VG_FALSE),
+    m_filterFormatPremultiplied(VG_FALSE),
+    m_filterChannelMask(VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA),
+
+    // Matrices
+    m_pathUserToSurface(),
+    m_imageUserToSurface(),
+    m_glyphUserToSurface(),
+    m_fillPaintToUser(),
+    m_strokePaintToUser(),
+
+    m_fillPaint(VG_INVALID_HANDLE),
+    m_strokePaint(VG_INVALID_HANDLE),
+
+    m_colorTransform(VG_FALSE),
+    m_colorTransformValues(),
+    m_inputColorTransformValues(),
+
+    m_error(VG_NO_ERROR),
+
+    m_imageManager(NULL),
+    m_pathManager(NULL),
+    m_paintManager(NULL),
+    m_fontManager(NULL),
+    m_maskLayerManager(NULL),
+
+    m_eglDrawable(NULL)
+{
+    if(shareContext)
+    {
+        m_imageManager = shareContext->m_imageManager;
+        m_pathManager = shareContext->m_pathManager;
+        m_paintManager = shareContext->m_paintManager;
+        m_fontManager = shareContext->m_fontManager;
+        m_maskLayerManager = shareContext->m_maskLayerManager;
+    }
+    else
+    {
+        try
+        {
+            m_imageManager = RI_NEW(OpenVGRI::ResourceManager<Image>, ());	//throws bad_alloc
+            m_pathManager = RI_NEW(OpenVGRI::ResourceManager<Path>, ());	//throws bad_alloc
+            m_paintManager = RI_NEW(OpenVGRI::ResourceManager<Paint>, ());	//throws bad_alloc
+            m_fontManager = RI_NEW(OpenVGRI::ResourceManager<Font>, ());	//throws bad_alloc
+            m_maskLayerManager = RI_NEW(OpenVGRI::ResourceManager<Surface>, ());	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+            RI_DELETE(m_imageManager);
+            RI_DELETE(m_pathManager);
+            RI_DELETE(m_paintManager);
+            RI_DELETE(m_fontManager);
+            RI_DELETE(m_maskLayerManager);
+
+            throw;
+        }
+    }
+    RI_ASSERT(m_imageManager);
+    RI_ASSERT(m_pathManager);
+    RI_ASSERT(m_paintManager);
+    RI_ASSERT(m_fontManager);
+    RI_ASSERT(m_maskLayerManager);
+
+    m_imageManager->addReference();
+    m_pathManager->addReference();
+    m_paintManager->addReference();
+    m_fontManager->addReference();
+    m_maskLayerManager->addReference();
+
+    m_inputColorTransformValues[0] = 1.0f;
+    m_inputColorTransformValues[1] = 1.0f;
+    m_inputColorTransformValues[2] = 1.0f;
+    m_inputColorTransformValues[3] = 1.0f;
+    m_inputColorTransformValues[4] = 0.0f;
+    m_inputColorTransformValues[5] = 0.0f;
+    m_inputColorTransformValues[6] = 0.0f;
+    m_inputColorTransformValues[7] = 0.0f;
+    m_colorTransformValues[0] = 1.0f;
+    m_colorTransformValues[1] = 1.0f;
+    m_colorTransformValues[2] = 1.0f;
+    m_colorTransformValues[3] = 1.0f;
+    m_colorTransformValues[4] = 0.0f;
+    m_colorTransformValues[5] = 0.0f;
+    m_colorTransformValues[6] = 0.0f;
+    m_colorTransformValues[7] = 0.0f;
+
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	VGContext destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGContext::~VGContext()
+{
+    releasePaint(VG_FILL_PATH | VG_STROKE_PATH);
+    setDefaultDrawable(NULL);
+
+    //destroy own images, paths and paints
+    while(Image* i = m_imageManager->getFirstResource(this))
+        m_imageManager->removeResource(i);
+    while(Path* p = m_pathManager->getFirstResource(this))
+        m_pathManager->removeResource(p);
+    while(Paint* t = m_paintManager->getFirstResource(this))
+        m_paintManager->removeResource(t);
+    while(Font* t = m_fontManager->getFirstResource(this))
+        m_fontManager->removeResource(t);
+    while(Surface* t = m_maskLayerManager->getFirstResource(this))
+        m_maskLayerManager->removeResource(t);
+
+    //decrease the reference count of resource managers
+    if(!m_imageManager->removeReference())
+        RI_DELETE(m_imageManager);
+    if(!m_pathManager->removeReference())
+        RI_DELETE(m_pathManager);
+    if(!m_paintManager->removeReference())
+        RI_DELETE(m_paintManager);
+    if(!m_fontManager->removeReference())
+        RI_DELETE(m_fontManager);
+    if(!m_maskLayerManager->removeReference())
+        RI_DELETE(m_maskLayerManager);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Sets new default drawable.
+* \param	drawable New drawable or NULL when context is unbound
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void VGContext::setDefaultDrawable(Drawable* drawable)
+{
+    if(m_eglDrawable)
+    {
+        if(!m_eglDrawable->removeReference())
+            RI_DELETE(m_eglDrawable);
+    }
+    m_eglDrawable = drawable;
+    if(m_eglDrawable)
+    {
+        m_eglDrawable->addReference();
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given image is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidImage(VGImage image)
+{
+    return m_imageManager->isValid((Image*)image);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given path is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidPath(VGPath path)
+{
+    return m_pathManager->isValid((Path*)path);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given paint is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidPaint(VGPaint paint)
+{
+    return m_paintManager->isValid((Paint*)paint);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given font is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidFont(VGFont font)
+{
+    return m_fontManager->isValid((Font*)font);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given mask layer is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidMaskLayer(VGMaskLayer layer)
+{
+    return m_maskLayerManager->isValid((Surface*)layer);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Releases the given paint objects of the context.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void VGContext::releasePaint(VGbitfield paintModes)
+{
+    if(paintModes & VG_FILL_PATH)
+    {
+        //release previous paint
+        Paint* prev = (Paint*)m_fillPaint;
+        if(prev)
+        {
+            if(!prev->removeReference())
+                RI_DELETE(prev);
+        }
+        m_fillPaint = VG_INVALID_HANDLE;
+    }
+    if(paintModes & VG_STROKE_PATH)
+    {
+        //release previous paint
+        Paint* prev = (Paint*)m_strokePaint;
+        if(prev)
+        {
+            if(!prev->removeReference())
+                RI_DELETE(prev);
+        }
+        m_strokePaint = VG_INVALID_HANDLE;
+    }
+}
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riContext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,290 @@
+#ifndef __RICONTEXT_H
+#define __RICONTEXT_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	VGContext class. Used for storing OpenVG state.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef OPENVG_H
+#include "openvg.h"
+#endif
+
+#ifndef __RIDEFS_H
+#include "riDefs.h"
+#endif
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#include "riImage.h"
+#endif
+
+#ifndef __RIPATH_H
+#include "riPath.h"
+#endif
+
+#ifndef __RIFONT_H
+#include "riFont.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#ifndef __SFDYNAMICBLITTER_H
+#   include "sfDynamicBlitter.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+class VGContext;
+
+/*-------------------------------------------------------------------*//*!
+* \brief	A list of resources (Images, Paths, or Paints) shared by a
+*			set of contexts.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+template <class Resource> class ResourceManager
+{
+public:
+    ResourceManager() :
+        m_referenceCount(0),
+        m_resources()
+    {
+    }
+
+    ~ResourceManager()
+    {
+        RI_ASSERT(m_referenceCount == 0);
+        RI_ASSERT(m_resources.size() == 0);
+    }
+
+    void			addReference()
+    {
+        m_referenceCount++;
+    }
+
+    int				removeReference()
+    {
+        m_referenceCount--;
+        RI_ASSERT(m_referenceCount >= 0);
+        return m_referenceCount;
+    }
+
+    void			addResource(Resource* resource, VGContext* context)
+    {
+        Entry r;
+        r.resource = resource;
+        r.context = context;
+        m_resources.push_back(r);	//throws bad_alloc
+        resource->addReference();
+    }
+
+    void			removeResource(Resource* resource)
+    {
+        if(!resource->removeReference())
+            RI_DELETE(resource);
+
+        int i=0;
+        bool found = false;
+        for(;i<m_resources.size();i++)
+        {
+            if(m_resources[i].resource == resource)
+            {
+                found = true;
+                break;
+            }
+        }
+        RI_ASSERT(found);
+
+        for(;i<m_resources.size()-1;i++)
+        {
+            m_resources[i] = m_resources[i+1];
+        }
+        m_resources.resize(m_resources.size()-1);
+    }
+
+    bool			isValid(Resource* resource)
+    {
+        for(int i=0;i<m_resources.size();i++)
+        {
+            if(m_resources[i].resource == resource)
+                return true;
+        }
+        return false;
+    }
+
+    Resource*		getFirstResource(VGContext* context)
+    {
+        for(int i=0;i<m_resources.size();i++)
+        {
+            if(m_resources[i].context == context)
+                return m_resources[i].resource;
+        }
+        return NULL;
+    }
+
+private:
+    ResourceManager(const ResourceManager&);
+    ResourceManager operator=(const ResourceManager&);
+
+    struct Entry
+    {
+        Resource*	resource;
+        VGContext*	context;
+    };
+
+    int				m_referenceCount;
+    Array<Entry>	m_resources;
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class VGContext
+{
+public:
+    VGContext(VGContext* shareContext);	//throws bad_alloc
+    ~VGContext();
+
+    void            setDefaultDrawable(Drawable* drawable); //called from EGL
+    Drawable*       getCurrentDrawable()        { return m_eglDrawable; }
+    DynamicBlitter& getBlitter() { return m_blitter; }
+
+    bool			isValidImage(VGImage image);
+    bool			isValidPath(VGPath path);
+    bool			isValidPaint(VGPaint paint);
+    bool			isValidFont(VGFont font);
+    bool			isValidMaskLayer(VGMaskLayer layer);
+
+    void			releasePaint(VGbitfield paintModes);
+
+    void			setError(VGErrorCode error)		{ if(m_error == VG_NO_ERROR) m_error = error; }
+
+    // Mode settings
+    VGMatrixMode					m_matrixMode;
+    VGFillRule						m_fillRule;
+    VGImageQuality					m_imageQuality;
+    VGRenderingQuality				m_renderingQuality;
+    VGBlendMode						m_blendMode;
+    VGImageMode						m_imageMode;
+
+    // Scissor rectangles
+    Array<Rectangle>				m_scissor;
+
+    // Stroke parameters
+    RIfloat							m_strokeLineWidth;
+    RIfloat							m_inputStrokeLineWidth;
+    VGCapStyle						m_strokeCapStyle;
+    VGJoinStyle						m_strokeJoinStyle;
+    RIfloat							m_strokeMiterLimit;
+    RIfloat							m_inputStrokeMiterLimit;
+    Array<RIfloat>					m_strokeDashPattern;
+    Array<RIfloat>					m_inputStrokeDashPattern;
+    RIfloat							m_strokeDashPhase;
+    RIfloat							m_inputStrokeDashPhase;
+    VGboolean						m_strokeDashPhaseReset;
+
+    // Edge fill color for vgConvolve and pattern paint
+    Color							m_tileFillColor;
+    Color							m_inputTileFillColor;
+
+    // Color for vgClear
+    Color							m_clearColor;
+    Color							m_inputClearColor;
+
+    Vector2                         m_glyphOrigin;
+    Vector2                         m_inputGlyphOrigin;
+
+    VGboolean						m_masking;
+    VGboolean						m_scissoring;
+
+    VGPixelLayout					m_pixelLayout;
+
+    VGboolean						m_filterFormatLinear;
+    VGboolean						m_filterFormatPremultiplied;
+    VGbitfield						m_filterChannelMask;
+
+    // Matrices
+    Matrix3x3						m_pathUserToSurface;
+    Matrix3x3						m_imageUserToSurface;
+    Matrix3x3						m_glyphUserToSurface;
+    Matrix3x3						m_fillPaintToUser;
+    Matrix3x3						m_strokePaintToUser;
+
+    VGPaint							m_fillPaint;
+    VGPaint							m_strokePaint;
+
+    VGboolean                       m_colorTransform;
+    RIfloat                         m_colorTransformValues[8];
+    RIuint32                        m_iColorTransformValues[8];
+    RIfloat                         m_inputColorTransformValues[8];
+
+    VGErrorCode						m_error;
+
+    ResourceManager<Image>*			m_imageManager;
+    ResourceManager<Path>*			m_pathManager;
+    ResourceManager<Paint>*			m_paintManager;
+    ResourceManager<Font>*			m_fontManager;
+    ResourceManager<Surface>*		m_maskLayerManager;
+
+    Rasterizer                      m_rasterizer;
+
+    PixelPipe                       m_pixelPipe;
+    DynamicBlitter                  m_blitter;
+
+private:
+    Drawable*                       m_eglDrawable;
+
+    VGContext(const VGContext&);			//!< Not allowed.
+    void operator=(const VGContext&);		//!< Not allowed.
+};
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+//==============================================================================================
+
+#endif /* __RICONTEXT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riDefs.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,206 @@
+#ifndef __RIDEFS_H
+#define __RIDEFS_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Platform- and compiler-dependent type and macro definitions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include <float.h>
+#include <math.h>
+#include <assert.h>
+#include <new>	//for bad_alloc
+
+#if defined(_WIN32) && defined(_DEBUG)
+#   define WIN32_LEAN_AND_MEAN
+#   include <windows.h>
+#endif
+
+//make for-clause scope c++ standard compliant on msvc
+#if defined (_MSC_VER)
+#	if !defined (for)
+        __forceinline bool getFalse (void) { return false; }
+#		define for if(getFalse()); else for
+#	endif // for
+
+#pragma warning(disable:4710)	//disable function not inlined warning
+#pragma warning(disable:4714)	//disable function not __forceinlined warning
+#endif  // _MSC_VER
+
+namespace OpenVGRI
+{
+
+//=======================================================================
+
+typedef long long       RIint64;
+typedef unsigned long long RIuint64;
+typedef int				RIint32;
+typedef unsigned int	RIuint32;
+typedef short			RIint16;
+typedef unsigned short	RIuint16;
+typedef signed char		RIint8;
+typedef unsigned char	RIuint8;
+typedef float			RIfloat32;
+//TODO add compile-time assertions to guarantee the sizes
+
+#if defined (_MSC_VER) // MSVC WIN32
+#	define RI_INLINE __forceinline
+#elif defined __APPLE__ || defined (__GNUC__) || defined (__GCC32__)
+#	define RI_INLINE inline
+#endif
+
+/*!< Unsigned int that can hold a pointer to any type */
+/*!< Signed int that can hold a pointer to any type */
+#if defined (_MSC_VER) && (_MSC_VER >= 1300)
+typedef uintptr_t		RIuintptr;
+typedef intptr_t		RIintptr;
+#else
+typedef unsigned long   RIuintptr;
+typedef signed long     RIintptr;
+#endif
+
+#define RI_UINT32_MAX (0xffffffffu)
+#define RI_INT32_MAX  (0x7fffffff)
+#define RI_INT32_MIN  (-0x7fffffff-1)
+
+/* maximum mantissa is 23 */
+#define RI_MANTISSA_BITS 23
+
+/* maximum exponent is 8 */
+#define RI_EXPONENT_BITS 8
+
+typedef union
+{
+    RIfloat32	f;
+    RIuint32	i;
+} RIfloatInt;
+
+RI_INLINE float	getFloatMax()
+{
+    RIfloatInt v;
+    v.i = (((1<<(RI_EXPONENT_BITS-1))-1+127) << 23) | (((1<<RI_MANTISSA_BITS)-1) << (23-RI_MANTISSA_BITS));
+    return v.f;
+}
+#define RI_FLOAT_MAX  getFloatMax()
+
+#define RI_MAX_IMAGE_WIDTH					16384
+#define RI_MAX_IMAGE_HEIGHT					16384
+#define RI_MAX_IMAGE_PIXELS					(RI_MAX_IMAGE_WIDTH*RI_MAX_IMAGE_HEIGHT)
+#define RI_MAX_IMAGE_BYTES					(4*RI_MAX_IMAGE_WIDTH*RI_MAX_IMAGE_HEIGHT)
+#define RI_MAX_DASH_COUNT					256
+#define RI_MAX_COLOR_RAMP_STOPS				256
+#define RI_MAX_KERNEL_SIZE					256
+#define RI_MAX_SEPARABLE_KERNEL_SIZE		256
+#define RI_MAX_GAUSSIAN_STD_DEVIATION		16.0f
+#define RI_MAX_SCISSOR_RECTANGLES			256
+#define RI_MAX_EDGES						262144
+#define RI_MAX_SAMPLES						1
+//#define RI_NUM_TESSELLATED_SEGMENTS_QUAD	256
+//#define RI_NUM_TESSELLATED_SEGMENTS_CUBIC	256
+//#define RI_NUM_TESSELLATED_SEGMENTS_ARC		256
+#define RI_NUM_TESSELLATED_SEGMENTS_QUAD	8
+#define RI_NUM_TESSELLATED_SEGMENTS_CUBIC	8
+#define RI_NUM_TESSELLATED_SEGMENTS_ARC		8
+
+#if !defined(_WIN32) && !defined(SF_PROFILE)
+#	ifndef NDEBUG
+#	define _DEBUG 1
+#	endif
+#endif
+
+#if _DEBUG
+    #define RI_DEBUG
+#endif
+
+#ifdef RI_DEBUG
+#	define RI_ASSERT(X) assert(X)
+#else
+#	define RI_ASSERT(X) (void(0))
+#endif
+
+#if defined(RI_DEBUG)
+#   define RI_PRINTF(...) printf(__VA_ARGS__)
+#else
+#   define RI_PRINTF(...)
+#endif
+
+#if defined(RI_DEBUG)
+#   if defined(_WIN32)
+#       define RI_TRACE(...) do { \
+        char buf[512]; \
+        snprintf(buf, sizeof(buf), __VA_ARGS__); \
+        OutputDebugString(buf); \
+    } while(false)
+#   else
+#       define RI_TRACE(...) printf(__VA_ARGS__)
+#   endif
+#else
+#   define RI_TRACE(...)
+#endif
+
+#define RI_UNREF(X) ((void)(X))
+#if defined(_WIN32)
+#   define RI_APIENTRY VG_API_ENTRY
+#else
+#	define RI_APIENTRY
+#endif
+
+#if defined(_WIN32)
+#   define snprintf sprintf_s 
+#endif 
+
+#define RI_API_CALL VG_API_CALL
+
+#define RI_NEW(TYPE, PARAMS)           (new TYPE PARAMS)
+#define RI_NEW_ARRAY(TYPE, ITEMS)      (new TYPE[ITEMS])
+#define RI_DELETE(PARAMS)              (delete (PARAMS))
+#define RI_DELETE_ARRAY(PARAMS)        (delete[] (PARAMS))
+
+bool			isValidImageFormat(int format);
+
+// \todo Move these to utility functions, etc.
+RI_INLINE void RI_MEM_ZERO(void *dst, size_t n)
+{
+    RI_ASSERT(n > 0);
+    RI_ASSERT((n & 0x3) == 0);
+
+    RIuint32 *ptr = (RIuint32*)dst;
+    for(size_t i = 0; i < (n>>2); i++)
+    {
+        *ptr++ = 0;
+    }
+}
+
+//=======================================================================
+
+}	//namespace OpenVGRI
+
+#endif /* __RIDEFS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riEGLOS.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,58 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef _RIEGLOS_H
+#define _RIEGLOS_H
+
+#include "EGL/egl.h"
+#include "riImage.h"
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+    struct OSWindowContext
+    {
+        int                 window;
+        unsigned int*       tmp;
+        int                 tmpWidth;
+        int                 tmpHeight;
+    };
+
+    void* OSGetCurrentThreadID(void);
+    void OSDeinitMutex(void);
+    void OSAcquireMutex(void);
+    void OSReleaseMutex(void);
+    OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window);
+    void OSDestroyWindowContext(OSWindowContext* ctx);
+    bool OSIsWindow(const OSWindowContext* context);
+    void OSGetWindowSize(const OSWindowContext* ctx, int& width, int& height);
+    void OSBlitToWindow(OSWindowContext* ctx, const Drawable* drawable);
+    EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id);
+}   //namespace OpenVGRI
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riFont.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,203 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of Font class.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "riFont.h"
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Font constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Font::Font(int capacityHint) :
+    m_referenceCount(0),
+    m_glyphs()
+{
+    RI_ASSERT(capacityHint >= 0);
+    m_glyphs.reserve(capacityHint);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Font destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Font::~Font()
+{
+    //remove references to paths and images
+    for(int i=0;i<m_glyphs.size();i++)
+        clearGlyph(&m_glyphs[i]);
+    RI_ASSERT(m_referenceCount == 0);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Find a glyph based on glyphIndex.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Font::Glyph* Font::findGlyph(unsigned int index)
+{
+    for(int i=0;i<m_glyphs.size();i++)
+    {
+        if(m_glyphs[i].m_state != Glyph::GLYPH_UNINITIALIZED && m_glyphs[i].m_index == index)
+            return &m_glyphs[i];
+    }
+    return NULL;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Find a free glyph or allocate a new one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Font::Glyph* Font::newGlyph()
+{
+    for(int i=0;i<m_glyphs.size();i++)
+    {
+        if(m_glyphs[i].m_state == Glyph::GLYPH_UNINITIALIZED)
+            return &m_glyphs[i];
+    }
+    m_glyphs.resize(m_glyphs.size()+1);
+    return &m_glyphs[m_glyphs.size()-1];
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Free glyph and its data.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Font::clearGlyph(Glyph* g)
+{
+    RI_ASSERT(g);
+    if(g->m_path != VG_INVALID_HANDLE)
+    {
+        Path* p = (Path*)g->m_path;
+        if(!p->removeReference())
+            RI_DELETE(p);
+    }
+    if(g->m_image != VG_INVALID_HANDLE)
+    {
+        Image* p = (Image*)g->m_image;
+        p->removeInUse();
+        if(!p->removeReference())
+            RI_DELETE(p);
+    }
+    Glyph a;
+    *g = a;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Font::setGlyphToPath(unsigned int index, VGPath path, bool isHinted, const Vector2& origin, const Vector2& escapement)
+{
+    Glyph* g = findGlyph(index);
+    if(g)
+    {   //glyph exists, replace
+        clearGlyph(g);
+    }
+    else
+    {   //glyph doesn't exist, allocate a new one
+        g = newGlyph();
+    }
+
+    g->m_index = index;
+    g->m_state = Glyph::GLYPH_PATH;
+    g->m_path = path;
+    g->m_image = VG_INVALID_HANDLE;
+    g->m_isHinted = isHinted;
+    g->m_origin = origin;
+    g->m_escapement = escapement;
+
+    if(path != VG_INVALID_HANDLE)
+    {
+        Path* p = (Path*)path;
+        p->addReference();
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Font::setGlyphToImage(unsigned int index, VGImage image, const Vector2& origin, const Vector2& escapement)
+{
+    Glyph* g = findGlyph(index);
+    if(g)
+    {   //glyph exists, replace
+        clearGlyph(g);
+    }
+    else
+    {   //glyph doesn't exist, allocate a new one
+        g = newGlyph();
+    }
+
+    g->m_index = index;
+    g->m_state = Glyph::GLYPH_IMAGE;
+    g->m_path = VG_INVALID_HANDLE;
+    g->m_image = image;
+    g->m_isHinted = false;
+    g->m_origin = origin;
+    g->m_escapement = escapement;
+
+    if(image != VG_INVALID_HANDLE)
+    {
+        Image* p = (Image*)image;
+        p->addReference();
+        p->addInUse();
+    }
+}
+
+//=======================================================================
+
+}	//namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riFont.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,116 @@
+#ifndef __RIFONT_H
+#define __RIFONT_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 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.
+ *
+ *//**
+ * \file
+ * \brief	VGContext class. Used for storing OpenVG state.
+ * \note	
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _OPENVG_H
+#include "openvg.h"
+#endif
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#ifndef __RIPATH_H
+#include "riPath.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#include "riImage.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Storage and operations for VGFont.
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+class Font
+{
+public:
+	struct Glyph
+	{
+        enum State
+        {
+            GLYPH_UNINITIALIZED     = 0,
+            GLYPH_PATH              = 1,
+            GLYPH_IMAGE             = 2
+        };
+		Glyph()				{ m_state = GLYPH_UNINITIALIZED; m_path = m_image = VG_INVALID_HANDLE; m_isHinted = false; m_origin.set(0.0f, 0.0f); m_escapement.set(0.0f, 0.0f); }
+        unsigned int m_index;
+        State        m_state;
+		VGPath		 m_path;
+		VGImage		 m_image;
+		bool		 m_isHinted;
+		Vector2		 m_origin;
+		Vector2		 m_escapement;
+	};
+
+	Font(int capacityHint);	//throws bad_alloc
+	~Font();
+
+	int				getNumGlyphs() const					{ int n=0; for(int i=0;i<m_glyphs.size();i++) { if(m_glyphs[i].m_state != Glyph::GLYPH_UNINITIALIZED) n++; } return n; }
+	void			addReference()							{ m_referenceCount++; }
+	int				removeReference()						{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+	void			setGlyphToPath(unsigned int index, VGPath path, bool isHinted, const Vector2& origin, const Vector2& escapement);    //throws bad_alloc
+	void			setGlyphToImage(unsigned int index, VGImage image, const Vector2& origin, const Vector2& escapement);    //throws bad_alloc
+    Glyph*          findGlyph(unsigned int index);
+    void            clearGlyph(Glyph* g);
+private:
+	Font(const Font&);						//!< Not allowed.
+	void operator=(const Font&);			//!< Not allowed.
+
+    Glyph*          newGlyph();    //throws bad_alloc
+
+	int				m_referenceCount;
+	Array<Glyph>	m_glyphs;
+};
+
+//=======================================================================
+
+}	//namespace OpenVGRI
+
+//=======================================================================
+
+#endif /* __RIFONT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riImage.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2835 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of Color and Image functions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "riImage.h"
+#include "riRasterizer.h"
+#include "riContext.h"
+
+#ifndef __SFDYNAMICBLITTER_H
+#   include "sfDynamicBlitter.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from numBits into a shifted mask
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static RI_INLINE unsigned int bitsToMask(unsigned int bits, unsigned int shift)
+{
+    return ((1<<bits)-1) << shift;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from color (RIfloat) to an int with 1.0f mapped to the
+*			given maximum with round-to-nearest semantics.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RI_INLINE int ffloor(RIfloat x)
+{
+    return (x >= 0) ? (int)x : (int)(x-1);
+}
+
+//static const float FLOAT_0	 = 0.0f;
+static const float FLOAT_0_5 = 0.5f;
+
+/* \note Rewrite this if time. */
+static unsigned int colorToInt(RIfloat c, int maxc)
+{
+#if defined RI_USE_SSE
+    /*
+        Registers mapping:
+        c		<->	xmm0,
+        maxc	<-> xmm1
+        0		<-> xmm2
+    */
+    _asm
+    {
+        xorps		xmm2, xmm2					; xmm2 = 0
+
+        ;---------------------------------------------
+        ; Computing: xmm0 = (c * (RIfloat)maxc + 0.5f)
+        ;---------------------------------------------
+        movss		xmm0, dword ptr [c]			; xmm0 = c
+        cvtsi2ss	xmm1, dword ptr [maxc]		; xmm1 = (float)maxc
+        mulss		xmm0, xmm1					; xmm0 = xmm0 * xmm1 = c * (float)maxc
+        addss		xmm0, FLOAT_0_5				; xmm0 = xmm0 + 0.5f = c * (float)maxc + 0.5f
+
+        ;---------------------------------------------
+        ; Computing: xmm0 = floor(xmm0) = floor(c * (RIfloat)maxc + 0.5f)
+        ;---------------------------------------------
+        cvttss2si   ebx, xmm0					; ebx = (int)xmm0
+        mov         eax, ebx					; eax = ebx = (int)xmm0
+        shr         eax, 31						; eax = sign(eax) = sign((int)xmm0)
+        sub         ebx, eax					; ebx = ebx - sign((int)xmm0) = (int)xmm0 - sign((int)xmm0) = (int)floor((int)xmm0)
+        cvtsi2ss    xmm0, ebx					; xmm0 = floor(xmm0)
+
+        pmaxsw		xmm0, xmm2;					; xmm0 = MAX(xmm0, 0)
+        pminsw		xmm0, xmm1					; xmm0 = MIN(xmm0, maxc)
+        cvttss2si   eax, xmm0					; return value = eax = (int)xmm0
+    }
+#else
+    return RI_INT_MIN(RI_INT_MAX((int)ffloor(c * (RIfloat)maxc + 0.5f), 0), maxc);
+#endif
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from int to color (RIfloat) with the given maximum
+*			mapped to 1.0f.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static RI_INLINE RIfloat intToColor(unsigned int i, unsigned int maxi)
+{
+    return (RIfloat)(i & maxi) / (RIfloat)maxi;
+}
+
+void Color::Descriptor::toSmallDescriptor(Color::SmallDescriptor& smallDesc) const
+{
+    switch (bitsPerPixel)
+    {
+    case 32:
+        smallDesc.size = SIZE_32;
+        break;
+    case 24:
+        smallDesc.size = SIZE_24;
+        break;
+    case 16:
+        smallDesc.size = SIZE_16;
+        break;
+    case 8:
+        smallDesc.size = SIZE_8;
+        break;
+    case 4:
+        smallDesc.size = SIZE_4;
+        break;
+    default:
+        RI_ASSERT(bitsPerPixel == 1);
+        smallDesc.size = SIZE_1;
+        break;
+    }
+    smallDesc.shape = shape;
+    smallDesc.internalFormat = internalFormat;
+}
+
+Color::Descriptor Color::Descriptor::getDummyDescriptor()
+{
+    static const Descriptor dummy = Color::Descriptor(8,0,8,8,8,16,8,24,0,0,sRGBA,32,SHAPE_ABGR);
+    return dummy;
+}
+
+/**
+ * \brief   Determine the shape of the color format from other data.
+ * \todo    The naming is poor because it may be interpreted as returning the member
+ *          "shape".
+ */
+Color::Shape Color::Descriptor::getShape() const
+{
+    // \todo There should be some easier way to define the shape so that it does
+    // not need to be determined with so many conditions.
+
+    if (isAlphaOnly())
+    {
+        return SHAPE_A;
+    }
+    else if (isLuminance())
+    {
+        if (alphaBits)
+        {
+            if (alphaShift == 0)
+                return SHAPE_LA;
+            return SHAPE_AL;
+        }
+        return SHAPE_L;
+    } 
+    else if (!alphaBits)
+    {
+        if (bitsPerPixel == 32)
+        {
+            switch(redShift)
+            {
+            case 0:
+                return SHAPE_XBGR;
+            case 8:
+                return SHAPE_BGRX;
+            case 16:
+                return SHAPE_XRGB;
+            default:
+                RI_ASSERT(redShift == 24);
+                return SHAPE_RGBX;
+            }
+        } else if (bitsPerPixel == 24)
+        {
+            if (!redShift)
+                return SHAPE_BGR;
+            else
+            {
+                RI_ASSERT(redShift == 16);
+                return SHAPE_RGB;
+            }
+        } else
+        {
+            RI_ASSERT(redBits == 5 && greenBits == 6 && blueBits == 5);
+            if(redShift)
+                return SHAPE_RGB;
+            else
+                return SHAPE_BGR;
+        }
+    }
+    else
+    {
+        if (bitsPerPixel == 32)
+        {
+            switch(redShift)
+            {
+            case 0:
+                return SHAPE_ABGR;
+            case 8:
+                return SHAPE_BGRA;
+            case 16:
+                return SHAPE_ARGB;
+            default:
+                RI_ASSERT(redShift == 24);
+                return SHAPE_RGBA;
+            }
+        } else
+        {
+            RI_ASSERT(bitsPerPixel == 16);
+            if (redBits == 5)
+            {
+                RI_ASSERT(greenBits == 5 && blueBits == 5 && alphaBits == 1);
+                switch(redShift)
+                {
+                case 0:
+                    return SHAPE_ABGR;
+                case 1:
+                    return SHAPE_BGRA;
+                case 10:
+                    return SHAPE_ARGB;
+                default:
+                    RI_ASSERT(redShift == 11);
+                    return SHAPE_RGBA;
+                }
+            } else
+            {
+                RI_ASSERT(redBits == 4 && greenBits == 4 && alphaBits == 4);
+                switch(redShift)
+                {
+                case 0:
+                    return SHAPE_ABGR;
+                case 4:
+                    return SHAPE_BGRA;
+                case 8:
+                    return SHAPE_ARGB;
+                default:
+                    RI_ASSERT(redShift == 12);
+                    return SHAPE_RGBA;
+                }
+            }
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from packed integer in a given format to a Color.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Color::unpack(unsigned int inputData, const Color::Descriptor& inputDesc)
+{
+    int rb = inputDesc.redBits;
+    int gb = inputDesc.greenBits;
+    int bb = inputDesc.blueBits;
+    int ab = inputDesc.alphaBits;
+    int lb = inputDesc.luminanceBits;
+    int rs = inputDesc.redShift;
+    int gs = inputDesc.greenShift;
+    int bs = inputDesc.blueShift;
+    int as = inputDesc.alphaShift;
+    int ls = inputDesc.luminanceShift;
+
+    m_format = inputDesc.internalFormat;
+    if(lb)
+    {	//luminance
+        r = g = b = intToColor(inputData >> ls, (1<<lb)-1);
+        a = 1.0f;
+    }
+    else
+    {	//rgba
+        r = rb ? intToColor(inputData >> rs, (1<<rb)-1) : (RIfloat)1.0f;
+        g = gb ? intToColor(inputData >> gs, (1<<gb)-1) : (RIfloat)1.0f;
+        b = bb ? intToColor(inputData >> bs, (1<<bb)-1) : (RIfloat)1.0f;
+        a = ab ? intToColor(inputData >> as, (1<<ab)-1) : (RIfloat)1.0f;
+
+        if(isPremultiplied())
+        {	//clamp premultiplied color to alpha to enforce consistency
+            r = RI_MIN(r, a);
+            g = RI_MIN(g, a);
+            b = RI_MIN(b, a);
+        }
+    }
+
+    assertConsistency();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from Color to a packed integer in a given format.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+unsigned int Color::pack(const Color::Descriptor& outputDesc) const
+{
+    assertConsistency();
+
+    int rb = outputDesc.redBits;
+    int gb = outputDesc.greenBits;
+    int bb = outputDesc.blueBits;
+    int ab = outputDesc.alphaBits;
+    int lb = outputDesc.luminanceBits;
+    int rs = outputDesc.redShift;
+    int gs = outputDesc.greenShift;
+    int bs = outputDesc.blueShift;
+    int as = outputDesc.alphaShift;
+    int ls = outputDesc.luminanceShift;
+
+    if(lb)
+    {	//luminance
+        RI_ASSERT(isLuminance());
+        return colorToInt(r, (1<<lb)-1) << ls;
+    }
+    else
+    {	//rgb
+        RI_ASSERT(!isLuminance());
+        unsigned int cr = rb ? colorToInt(r, (1<<rb)-1) : 0;
+        unsigned int cg = gb ? colorToInt(g, (1<<gb)-1) : 0;
+        unsigned int cb = bb ? colorToInt(b, (1<<bb)-1) : 0;
+        unsigned int ca = ab ? colorToInt(a, (1<<ab)-1) : 0;
+        return packRGBAInteger(cr, rs, cg, gs, cb, bs, ca, as);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from the current internal format to another.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+/* \todo Integer & lookup versions */
+
+static RIfloat gamma(RIfloat c)
+{
+    if( c <= 0.00304f )
+        c *= 12.92f;
+    else
+        c = 1.0556f * (RIfloat)pow(c, 1.0f/2.4f) - 0.0556f;
+    return c;
+}
+
+static RIfloat invgamma(RIfloat c)
+{
+    if( c <= 0.03928f )
+        c /= 12.92f;
+    else
+        c = (RIfloat)pow((c + 0.0556f)/1.0556f, 2.4f);
+    return c;
+}
+
+static RIfloat lRGBtoL(RIfloat r, RIfloat g, RIfloat b)
+{
+    return 0.2126f*r + 0.7152f*g + 0.0722f*b;
+}
+
+void Color::convert(InternalFormat outputFormat)
+{
+    /* \todo This should probably be converted to integer code. */
+
+    assertConsistency();
+
+    if( m_format == outputFormat )
+        return;
+
+    if(isPremultiplied())
+    {	//unpremultiply
+        RIfloat ooa = (a != 0.0f) ? 1.0f / a : (RIfloat)0.0f;
+        r *= ooa;
+        g *= ooa;
+        b *= ooa;
+    }
+
+    //From Section 3.4.2 of OpenVG spec
+    //1: sRGB = gamma(lRGB)
+    //2: lRGB = invgamma(sRGB)
+    //3: lL = 0.2126 lR + 0.7152 lG + 0.0722 lB
+    //4: lRGB = lL
+    //5: sL = gamma(lL)
+    //6: lL = invgamma(sL)
+    //7: sRGB = sL
+
+    //Source/Dest lRGB sRGB   lL   sL
+    //lRGB          -    1    3    3,5
+    //sRGB          2    -    2,3  2,3,5
+    //lL            4    4,1  -    5
+    //sL            7,2  7    6    -
+
+    const unsigned int shift = 3;
+    unsigned int conversion = (m_format & (NONLINEAR | LUMINANCE)) | ((outputFormat & (NONLINEAR | LUMINANCE)) << shift);
+
+    switch(conversion)
+    {
+    case lRGBA | (sRGBA << shift): r = gamma(r); g = gamma(g); b = gamma(b); break;							//1
+    case lRGBA | (lLA << shift)  : r = g = b = lRGBtoL(r, g, b); break;										//3
+    case lRGBA | (sLA << shift)  : r = g = b = gamma(lRGBtoL(r, g, b)); break;								//3,5
+    case sRGBA | (lRGBA << shift): r = invgamma(r); g = invgamma(g); b = invgamma(b); break;				//2
+    case sRGBA | (lLA << shift)  : r = g = b = lRGBtoL(invgamma(r), invgamma(g), invgamma(b)); break;		//2,3
+    case sRGBA | (sLA << shift)  : r = g = b = gamma(lRGBtoL(invgamma(r), invgamma(g), invgamma(b))); break;//2,3,5
+    case lLA   | (lRGBA << shift): break;																	//4
+    case lLA   | (sRGBA << shift): r = g = b = gamma(r); break;												//4,1
+    case lLA   | (sLA << shift)  : r = g = b = gamma(r); break;												//5
+    case sLA   | (lRGBA << shift): r = g = b = invgamma(r); break;											//7,2
+    case sLA   | (sRGBA << shift): break;																	//7
+    case sLA   | (lLA << shift)  : r = g = b = invgamma(r); break;											//6
+    default: RI_ASSERT((m_format & (LUMINANCE | NONLINEAR)) == (outputFormat & (LUMINANCE | NONLINEAR))); break;	//nop
+    }
+
+    if(outputFormat & PREMULTIPLIED)
+    {	//premultiply
+        r *= a;
+        g *= a;
+        b *= a;
+    }
+    m_format = outputFormat;
+
+    assertConsistency();
+}
+
+/*------------------------------------------------------------------------*//*!
+* \brief	Creates a pixel format descriptor out of VGImageFormat
+* \param
+* \return
+* \note     Remove this function and use the "const" version for consistency.
+*//*------------------------------------------------------------------------*/
+Color::Descriptor Color::formatToDescriptor(VGImageFormat format)
+{
+    Descriptor desc;
+    memset(&desc, 0, sizeof(Descriptor));
+    RI_ASSERT(isValidImageFormat(format));
+
+    int baseFormat = (int)format & 15;
+    const int numBaseFormats = 15;
+    RI_ASSERT(baseFormat >= 0 && baseFormat < numBaseFormats);
+    int swizzleBits = ((int)format >> 6) & 3;
+
+    /* base formats
+    VG_sRGBX_8888                               =  0,
+    VG_sRGBA_8888                               =  1,
+    VG_sRGBA_8888_PRE                           =  2,
+    VG_sRGB_565                                 =  3,
+    VG_sRGBA_5551                               =  4,
+    VG_sRGBA_4444                               =  5,
+    VG_sL_8                                     =  6,
+    VG_lRGBX_8888                               =  7,
+    VG_lRGBA_8888                               =  8,
+    VG_lRGBA_8888_PRE                           =  9,
+    VG_lL_8                                     = 10,
+    VG_A_8                                      = 11,
+    VG_BW_1                                     = 12,
+    VG_A_1                                      = 13,
+    VG_A_4                                      = 14,
+    */
+
+    static const int redBits[numBaseFormats] =       {8, 8, 8, 5, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0};
+    static const int greenBits[numBaseFormats] =     {8, 8, 8, 6, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0};
+    static const int blueBits[numBaseFormats] =      {8, 8, 8, 5, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0};
+    static const int alphaBits[numBaseFormats] =     {0, 8, 8, 0, 1, 4, 0, 0, 8, 8, 0, 8, 0, 1, 4};
+    static const int luminanceBits[numBaseFormats] = {0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 1, 0, 0};
+
+    static const int redShifts[4*numBaseFormats] = {24, 24, 24, 11, 11, 12, 0, 24, 24, 24, 0, 0, 0, 0, 0,	//RGBA
+                                                    16, 16, 16, 11, 10, 8,  0, 16, 16, 16, 0, 0, 0, 0, 0,	//ARGB
+                                                    8,  8,  8,  0,  1,  4,  0, 8,  8,  8,  0, 0, 0, 0, 0,	//BGRA
+                                                    0,  0,  0,  0,  0,  0,  0, 0,  0,  0,  0, 0, 0, 0, 0};	//ABGR
+
+    static const int greenShifts[4*numBaseFormats] = {16, 16, 16, 5,  6,  8,  0, 16, 16, 16, 0, 0, 0, 0, 0,	//RGBA
+                                                      8,  8,  8,  5,  5,  4,  0, 8,  8,  8,  0, 0, 0, 0, 0,	//ARGB
+                                                      16, 16, 16, 5,  6,  8,  0, 16, 16, 16, 0, 0, 0, 0, 0,	//BGRA
+                                                      8,  8,  8,  5,  5,  4,  0, 8,  8,  8,  0, 0, 0, 0, 0};//ABGR
+
+    static const int blueShifts[4*numBaseFormats] =  {8,  8,  8,  0,  1,  4,  0, 8,  8,  8,  0, 0, 0, 0, 0,	//RGBA
+                                                      0,  0,  0,  0,  0,  0,  0, 0,  0,  0,  0, 0, 0, 0, 0,	//ARGB
+                                                      24, 24, 24, 11, 11, 12, 0, 24, 24, 24, 0, 0, 0, 0, 0,	//BGRA
+                                                      16, 16, 16, 11, 10, 8,  0, 16, 16, 16, 0, 0, 0, 0, 0};//ABGR
+
+    static const int alphaShifts[4*numBaseFormats] = {0,  0,  0,  0,  0,  0,  0, 0,  0,  0,  0, 0, 0, 0, 0,	//RGBA
+                                                      0,  24, 24, 0,  15, 12, 0, 0,  24, 24, 0, 0, 0, 0, 0,	//ARGB
+                                                      0,  0,  0,  0,  0,  0,  0, 0,  0,  0,  0, 0, 0, 0, 0,	//BGRA
+                                                      0,  24, 24, 0,  15, 12, 0, 0,  24, 24, 0, 0, 0, 0, 0};//ABGR
+
+    static const int bpps[numBaseFormats] = {32, 32, 32, 16, 16, 16, 8, 32, 32, 32, 8, 8, 1, 1, 4};
+
+    static const InternalFormat internalFormats[numBaseFormats] = {sRGBA, sRGBA, sRGBA_PRE, sRGBA, sRGBA, sRGBA, sLA, lRGBA, lRGBA, lRGBA_PRE, lLA, lRGBA, lLA, lRGBA, lRGBA};
+
+    desc.redBits = redBits[baseFormat];
+    desc.greenBits = greenBits[baseFormat];
+    desc.blueBits = blueBits[baseFormat];
+    desc.alphaBits = alphaBits[baseFormat];
+    desc.luminanceBits = luminanceBits[baseFormat];
+
+    desc.redShift = redShifts[swizzleBits * numBaseFormats + baseFormat];
+    desc.greenShift = greenShifts[swizzleBits * numBaseFormats + baseFormat];
+    desc.blueShift = blueShifts[swizzleBits * numBaseFormats + baseFormat];
+    desc.alphaShift = alphaShifts[swizzleBits * numBaseFormats + baseFormat];
+    desc.luminanceShift = 0;	//always zero
+
+    desc.vgFormat = format;
+    desc.bitsPerPixel = bpps[baseFormat];
+    desc.bytesPerPixel = desc.bitsPerPixel / 8;
+    desc.internalFormat = internalFormats[baseFormat];
+    desc.shape = desc.getShape();
+
+    if (desc.alphaBits)
+    {
+        desc.maskBits = desc.alphaBits;
+        desc.maskShift = desc.alphaShift;
+    } 
+    else if (!desc.isLuminance())
+    {
+        desc.maskBits = desc.redBits;
+        desc.maskShift = desc.redShift;
+    } 
+    else
+    {
+        desc.maskBits = desc.luminanceBits;
+        desc.maskShift = desc.luminanceShift;
+    }
+
+    return desc;
+}
+
+
+struct DescToFormatMapping
+{
+    Color::Descriptor desc;
+    VGImageFormat format;
+};
+
+RI_INLINE static bool isDescEqualToMapping(const Color::Descriptor& desc, const DescToFormatMapping &mapping)
+{
+    if ((desc.redBits == mapping.desc.redBits) &&
+        (desc.redShift == mapping.desc.redShift) &&
+        (desc.greenBits == mapping.desc.greenBits) &&
+        (desc.greenShift == mapping.desc.greenShift) &&
+        (desc.blueBits == mapping.desc.blueBits) &&
+        (desc.blueShift == mapping.desc.blueShift) &&
+        (desc.alphaBits == mapping.desc.alphaBits) &&
+        (desc.alphaShift == mapping.desc.alphaShift) &&
+        (desc.luminanceBits == mapping.desc.luminanceBits) &&
+        (desc.luminanceShift == mapping.desc.luminanceShift) &&
+        (desc.internalFormat == mapping.desc.internalFormat) &&
+        (desc.bitsPerPixel == mapping.desc.bitsPerPixel))
+        return true;
+
+    return false;
+}
+
+VGImageFormat Color::descriptorToVGImageFormat(const Descriptor& desc)
+{
+//Color::Descriptor::Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp) :
+    // \todo These are hardcoded here only to allow constant initialization, they should be generated
+    // using formatToDescriptor!
+    static const DescToFormatMapping map[] = {
+    /* RGB{A,X} channel ordering */
+        { formatToDescriptorConst(VG_sRGBX_8888), VG_sRGBX_8888 },
+        { formatToDescriptorConst(VG_sRGBA_8888), VG_sRGBA_8888 },
+        { formatToDescriptorConst(VG_sRGBA_8888_PRE), VG_sRGBA_8888_PRE },
+        { formatToDescriptorConst(VG_sRGB_565), VG_sRGB_565 },
+        { formatToDescriptorConst(VG_sRGBA_5551), VG_sRGBA_5551 },
+        { formatToDescriptorConst(VG_sRGBA_4444), VG_sRGBA_4444 },
+        { formatToDescriptorConst(VG_sL_8), VG_sL_8 },
+        { formatToDescriptorConst(VG_lRGBX_8888), VG_lRGBX_8888 },
+        { formatToDescriptorConst(VG_lRGBA_8888), VG_lRGBA_8888 },
+        { formatToDescriptorConst(VG_lRGBA_8888_PRE), VG_lRGBA_8888_PRE },
+        { formatToDescriptorConst(VG_lL_8), VG_lL_8 },
+        { formatToDescriptorConst(VG_A_8), VG_A_8 },
+        { formatToDescriptorConst(VG_BW_1), VG_BW_1 },
+        { formatToDescriptorConst(VG_A_1), VG_A_1 },
+        { formatToDescriptorConst(VG_A_4), VG_A_4 },
+
+  /* {A,X}RGB channel ordering */
+        { formatToDescriptorConst(VG_sXRGB_8888), VG_sXRGB_8888 },
+        { formatToDescriptorConst(VG_sARGB_8888), VG_sARGB_8888 },
+        { formatToDescriptorConst(VG_sARGB_8888_PRE), VG_sARGB_8888_PRE },
+        { formatToDescriptorConst(VG_sARGB_1555), VG_sARGB_1555 },
+        { formatToDescriptorConst(VG_sARGB_4444), VG_sARGB_4444 },
+        { formatToDescriptorConst(VG_lXRGB_8888), VG_lXRGB_8888 },
+        { formatToDescriptorConst(VG_lARGB_8888), VG_lARGB_8888 },
+        { formatToDescriptorConst(VG_lARGB_8888_PRE), VG_lARGB_8888_PRE },
+
+  /* BGR{A,X} channel ordering */
+        { formatToDescriptorConst(VG_sBGRX_8888), VG_sBGRX_8888 },
+        { formatToDescriptorConst(VG_sBGRA_8888), VG_sBGRA_8888 },
+        { formatToDescriptorConst(VG_sBGRA_8888_PRE), VG_sBGRA_8888_PRE },
+        { formatToDescriptorConst(VG_sBGR_565), VG_sBGR_565 },
+        { formatToDescriptorConst(VG_sBGRA_5551), VG_sBGRA_5551 },
+        { formatToDescriptorConst(VG_sBGRA_4444), VG_sBGRA_4444 },
+        { formatToDescriptorConst(VG_lBGRX_8888), VG_lBGRX_8888 },
+        { formatToDescriptorConst(VG_lBGRA_8888), VG_lBGRA_8888 },
+        { formatToDescriptorConst(VG_lBGRA_8888_PRE), VG_lBGRA_8888_PRE },
+
+  /* {A,X}BGR channel ordering */
+        { formatToDescriptorConst(VG_sXBGR_8888), VG_sXBGR_8888 },
+        { formatToDescriptorConst(VG_sABGR_8888), VG_sABGR_8888 },
+        { formatToDescriptorConst(VG_sABGR_8888_PRE), VG_sABGR_8888_PRE },
+        { formatToDescriptorConst(VG_sABGR_1555), VG_sABGR_1555 },
+        { formatToDescriptorConst(VG_sABGR_4444), VG_sABGR_4444 },
+        { formatToDescriptorConst(VG_lXBGR_8888), VG_lXBGR_8888 },
+        { formatToDescriptorConst(VG_lABGR_8888), VG_lABGR_8888 },
+        { formatToDescriptorConst(VG_lABGR_8888_PRE), VG_lABGR_8888_PRE },
+    };
+
+    for (size_t i = 0; i < sizeof(map)/sizeof(map[0]); i++)
+    {
+        if (isDescEqualToMapping(desc, map[i]))
+            return map[i].format;
+    }
+    RI_ASSERT(false);
+    return (VGImageFormat)-1;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Checks if the pixel format descriptor is valid (i.e. all the
+*           values are supported by the RI)
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool Color::isValidDescriptor(const Color::Descriptor& desc)
+{
+    //A valid descriptor has 1, 2, 4, 8, 16, or 32 bits per pixel, and either luminance or rgba channels, but not both.
+    //Any of the rgba channels can be missing, and not all bits need to be used. Maximum channel bit depth is 8.
+    int rb = desc.redBits;
+    int gb = desc.greenBits;
+    int bb = desc.blueBits;
+    int ab = desc.alphaBits;
+    int lb = desc.luminanceBits;
+    int rs = desc.redShift;
+    int gs = desc.greenShift;
+    int bs = desc.blueShift;
+    int as = desc.alphaShift;
+    int ls = desc.luminanceShift;
+    int bpp = desc.bitsPerPixel;
+
+    int rgbaBits = rb + gb + bb + ab;
+    if(rb < 0 || rb > 8 || rs < 0 || rs + rb > bpp || !(rb || !rs))
+        return false;	//invalid channel description
+    if(gb < 0 || gb > 8 || gs < 0 || gs + gb > bpp || !(gb || !gs))
+        return false;	//invalid channel description
+    if(bb < 0 || bb > 8 || bs < 0 || bs + bb > bpp || !(bb || !bs))
+        return false;	//invalid channel description
+    if(ab < 0 || ab > 8 || as < 0 || as + ab > bpp || !(ab || !as))
+        return false;	//invalid channel description
+    if(lb < 0 || lb > 8 || ls < 0 || ls + lb > bpp || !(lb || !ls))
+        return false;	//invalid channel description
+
+#if 0
+    if(rgbaBits && lb)
+        return false;	//can't have both rgba and luminance
+#endif
+    if(!rgbaBits && !lb)
+        return false;	//must have either rgba or luminance
+    if(rgbaBits)
+    {	//rgba
+        if(rb+gb+bb == 0)
+        {	//alpha only
+            if(rs || gs || bs || as || ls)
+                return false;	//wrong shifts (even alpha shift must be zero)
+            if((ab != 1 && ab != 2  && ab != 4 && ab != 8) || bpp != ab)
+                return false;	//alpha size must be 1, 2, 4, or, 8, bpp must match
+        }
+        else
+        {	//rgba
+            if(rgbaBits > bpp)
+                return false;	//bpp must be greater than or equal to the sum of rgba bits
+            if(!(bpp == 32 || bpp == 16 || bpp == 8))
+                return false;	//only 1, 2, and 4 byte formats are supported for rgba
+
+            unsigned int rm = bitsToMask((unsigned int)rb, (unsigned int)rs);
+            unsigned int gm = bitsToMask((unsigned int)gb, (unsigned int)gs);
+            unsigned int bm = bitsToMask((unsigned int)bb, (unsigned int)bs);
+            unsigned int am = bitsToMask((unsigned int)ab, (unsigned int)as);
+            if((rm & gm) || (rm & bm) || (rm & am) || (gm & bm) || (gm & am) || (bm & am))
+                return false;	//channels overlap
+        }
+    }
+    else
+    {	//luminance
+        if(rs || gs || bs || as || ls)
+            return false;	//wrong shifts (even luminance shift must be zero)
+        if(!(lb == 1 || lb == 8) || bpp != lb)
+            return false;	//luminance size must be either 1 or 8, bpp must match
+    }
+
+    if(desc.vgFormat != -1)
+    {
+        if(!isValidImageFormat(desc.vgFormat))
+            return false;	//invalid image format
+
+        Descriptor d = formatToDescriptor(desc.vgFormat);
+        if(d.redBits != rb || d.greenBits != gb || d.blueBits != bb || d.alphaBits != ab || d.luminanceBits != lb ||
+           d.redShift != rs || d.greenShift != gs || d.blueShift != bs || d.alphaShift != as || d.luminanceShift != ls ||
+           d.bitsPerPixel != bpp)
+           return false;	//if the descriptor has a VGImageFormat, it must match the bits, shifts, and bpp
+    } 
+
+    if((unsigned int)desc.internalFormat & ~(Color::PREMULTIPLIED | Color::NONLINEAR | Color::LUMINANCE))
+        return false;	//invalid internal format
+
+    return true;
+}
+
+//==============================================================================================
+
+//==============================================================================================
+
+IntegerColor::IntegerColor(const Color& color)
+{
+    r = (RIuint32)(color.r * 255.0f + 0.5f);
+    g = (RIuint32)(color.g * 255.0f + 0.5f);
+    b = (RIuint32)(color.b * 255.0f + 0.5f);
+    a = (RIuint32)(color.a * 255.0f + 0.5f);
+}
+
+//==============================================================================================
+
+//==============================================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Constructs a blank image.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Image::Image(const Color::Descriptor& desc, int width, int height, VGbitfield allowedQuality) :
+    m_desc(desc),
+    m_width(width),
+    m_height(height),
+    m_allowedQuality(allowedQuality),
+    m_inUse(0),
+    m_stride(0),
+    m_data(NULL),
+    m_referenceCount(0),
+    m_ownsData(true),
+    m_parent(NULL),
+    m_storageOffsetX(0),
+    m_storageOffsetY(0),
+    m_unsafeData(false)
+{
+    RI_ASSERT(Color::isValidDescriptor(m_desc));
+    RI_ASSERT(width > 0 && height > 0);
+
+    m_stride = (m_width*m_desc.bitsPerPixel+7)/8;
+
+    m_data = RI_NEW_ARRAY(RIuint8, m_stride*m_height);	//throws bad_alloc
+    memset(m_data, 0, m_stride*m_height);	//clear image
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Constructs an image that uses an external array for its data
+*			storage.
+* \param
+* \return
+* \note		This is meant for internal use to make blitting easier
+* \note     Now this is "tagged" into m_unsafeData if necessary.
+*           Using this constructor may then affect performance.
+*//*-------------------------------------------------------------------*/
+
+Image::Image(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data) :
+    m_desc(desc),
+    m_width(width),
+    m_height(height),
+    m_allowedQuality(0),
+    m_inUse(0),
+    m_stride(stride),
+    m_data(data),
+    m_referenceCount(0),
+    m_ownsData(false),
+    m_parent(NULL),
+    m_storageOffsetX(0),
+    m_storageOffsetY(0),
+    m_unsafeData(false)
+{
+    RI_ASSERT(Color::isValidDescriptor(m_desc));
+    RI_ASSERT(width > 0 && height > 0);
+    RI_ASSERT(data);
+    setUnsafe(true); // External data always potentially unsafe, see note above.
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Construcs a child image.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Image::Image(Image* parent, int x, int y, int width, int height) :
+    m_desc(Color::formatToDescriptor(VG_sRGBA_8888)),	//dummy initialization, will be overwritten below (can't read from parent->m_desc before knowing the pointer is valid)
+    m_width(width),
+    m_height(height),
+    m_allowedQuality(0),
+    m_inUse(0),
+    m_stride(0),
+    m_data(NULL),
+    m_referenceCount(0),
+    m_ownsData(false),
+    m_parent(parent),
+    m_storageOffsetX(0),
+    m_storageOffsetY(0),
+    m_unsafeData(false)
+{
+    RI_ASSERT(parent);
+    RI_ASSERT(x >= 0 && y >= 0 && width > 0 && height > 0);
+    RI_ASSERT(RI_INT_ADDSATURATE(x,width) <= parent->m_width && RI_INT_ADDSATURATE(y,height) <= parent->m_height);	//child image must be contained in parent
+
+    m_desc = parent->m_desc;
+    RI_ASSERT(Color::isValidDescriptor(m_desc));
+    m_allowedQuality = parent->m_allowedQuality;
+    m_stride = parent->m_stride;
+    m_data = parent->m_data;
+    m_storageOffsetX = parent->m_storageOffsetX + x;
+    m_storageOffsetY = parent->m_storageOffsetY + y;
+
+    //increase the reference and use count of the parent
+    addInUse();
+    parent->addInUse();
+    parent->addReference();
+    m_unsafeData = parent->m_unsafeData;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Image destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Image::~Image()
+{
+    RI_ASSERT(m_referenceCount == 0);
+
+    if(m_parent)
+    {
+        //decrease the reference and use count of the parent
+        removeInUse();
+        m_parent->removeInUse();
+        if(!m_parent->removeReference())
+            RI_DELETE(m_parent);
+    }
+    RI_ASSERT(m_inUse == 0);
+
+
+    if(m_ownsData)
+    {
+        RI_ASSERT(!m_parent);		//can't have parent if owns the data
+        RI_DELETE_ARRAY(m_data);	//delete image data if we own it
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the two images share pixels.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool Image::overlaps(const Image* src) const
+{
+    RI_ASSERT(src);
+
+    if(m_data != src->m_data)
+        return false;	//images don't share data
+
+    //check if the image storage regions overlap
+    Rectangle r(m_storageOffsetX, m_storageOffsetY, m_width, m_height);
+    r.intersect(Rectangle(src->m_storageOffsetX, src->m_storageOffsetY, src->m_width, src->m_height));
+    if(!r.width || !r.height)
+        return false;	//intersection is empty, images don't overlap
+
+    return true;
+}
+
+/**
+ * \brief   Expand log2 bpp packed pixel (single value) to 8 bits. This will
+ *          Result in 8, 4, or 2 same pixel values to be packed into the return value.
+ */
+RI_INLINE static RIuint32 logExpand8(RIuint32 packedColor, int srcBits)
+{
+    RI_ASSERT(srcBits == 4 || srcBits == 2 || srcBits == 1);
+    RIuint32 ret = packedColor;
+    int n = srcBits;
+    while (n < 8)
+    {
+        ret |= ret << n;
+        n += n;
+    }
+    return ret;
+}
+
+RI_INLINE void Image::fillPacked(RIuint32 packedColor)
+{
+    RIuint32 pc = packedColor;
+    int Bpp = m_desc.bitsPerPixel / 8;
+    int nSetsPerScanline = m_width;
+
+    RI_ASSERT(nSetsPerScanline);
+    // \todo 1bpp and 4bpp mask formats must be supported. fillPackedPixels should
+    // automatically work, but riMemSet32 path needs a bit more logic.
+    // \note < 8bpp formats are always rounded to 8-bit boundaries at scanline end.
+    // It is assumed that the "padding bits" may be filled.
+        
+    if (m_desc.bitsPerPixel < 8)
+    {
+        pc = logExpand8(packedColor, m_desc.bitsPerPixel);
+        Bpp = 1;
+        nSetsPerScanline = (m_width * m_desc.bitsPerPixel + 7) / 8;
+        //nSetsPerScanline /= (8/m_desc.bitsPerPixel);
+    }
+
+    RI_ASSERT(Bpp <= 4 && Bpp >= 1);
+
+    if (m_stride == ((m_desc.bitsPerPixel*m_width+7)/8))
+    {
+        const int nPixels = nSetsPerScanline * m_height;
+        riMemSet32(m_data, pc, nPixels, Bpp);
+    } else
+    {
+        RIuint8 *ptr = (RIuint8*)m_data;
+        // set per-scanline
+        for (int y = 0; y < m_height; y++)
+        {
+            riMemSet32(ptr, pc, nSetsPerScanline, Bpp); 
+            ptr += m_stride;
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Clears a rectangular portion of an image with the given clear color.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::clear(const Color& clearColor, int x, int y, int w, int h)
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(m_referenceCount > 0);
+
+
+    //intersect clear region with image bounds
+    Rectangle r(0,0,m_width,m_height);
+    r.intersect(Rectangle(x,y,w,h));
+    if(!r.width || !r.height)
+        return;		//intersection is empty or one of the rectangles is invalid
+
+    Color col = clearColor;
+    col.clamp();
+    col.convert(getDescriptor().internalFormat);
+
+    IntegerColor ic = IntegerColor(col);
+    ic.truncateColor(getDescriptor());
+    const RIuint32 c = ic.getPackedColor(getDescriptor());
+
+    if (r.width == getWidth() && r.height == getHeight() && !m_parent)
+        fillPacked(c);
+    else
+    {
+        fillPackedRectangle(r.x, r.y, r.width, r.height, c);
+    }
+}
+
+#if 0
+static RIfloat ditherChannel(RIfloat c, int bits, RIfloat m)
+{
+    RIfloat fc = c * (RIfloat)((1<<bits)-1);
+    RIfloat ic = (RIfloat)floor(fc);
+    if(fc - ic > m) ic += 1.0f;
+    return RI_MIN(ic / (RIfloat)((1<<bits)-1), 1.0f);
+}
+#endif
+
+static void computeBlitRegion(int& sx, int& sy, int& dx, int& dy, int& w, int& h, int srcWidth, int srcHeight, int dstWidth, int dstHeight)
+{
+    RI_ASSERT(w > 0 && h > 0);
+    sx = RI_INT_MIN(RI_INT_MAX(sx, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2));
+    sy = RI_INT_MIN(RI_INT_MAX(sy, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2));
+    dx = RI_INT_MIN(RI_INT_MAX(dx, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2));
+    dy = RI_INT_MIN(RI_INT_MAX(dy, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2));
+    w = RI_INT_MIN(w, (int)(RI_INT32_MAX>>2));
+    h = RI_INT_MIN(h, (int)(RI_INT32_MAX>>2));
+    int srcsx = sx, srcex = sx + w, dstsx = dx, dstex = dx + w;
+    if(srcsx < 0)
+    {
+        dstsx -= srcsx;
+        srcsx = 0;
+    }
+    if(srcex > srcWidth)
+    {
+        dstex -= srcex - srcWidth;
+        srcex = srcWidth;
+    }
+    if(dstsx < 0)
+    {
+        srcsx -= dstsx;
+        dstsx = 0;
+    }
+    if(dstex > dstWidth)
+    {
+        srcex -= dstex - dstWidth;
+        dstex = dstWidth;
+    }
+    RI_ASSERT(srcsx >= 0 && dstsx >= 0 && srcex <= srcWidth && dstex <= dstWidth);
+    w = srcex - srcsx;
+    RI_ASSERT(w == dstex - dstsx);
+
+    int srcsy = sy, srcey = sy + h, dstsy = dy, dstey = dy + h;
+    if(srcsy < 0)
+    {
+        dstsy -= srcsy;
+        srcsy = 0;
+    }
+    if(srcey > srcHeight)
+    {
+        dstey -= srcey - srcHeight;
+        srcey = srcHeight;
+    }
+    if(dstsy < 0)
+    {
+        srcsy -= dstsy;
+        dstsy = 0;
+    }
+    if(dstey > dstHeight)
+    {
+        srcey -= dstey - dstHeight;
+        dstey = dstHeight;
+    }
+    RI_ASSERT(srcsy >= 0 && dstsy >= 0 && srcey <= srcHeight && dstey <= dstHeight);
+    h = srcey - srcsy;
+    RI_ASSERT(h == dstey - dstsy);
+    sx = srcsx;
+    sy = srcsy;
+    dx = dstsx;
+    dy = dstsy;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Blits a source region to destination. Source and destination
+*			can overlap.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+// \todo Extract dithering kernel and put it into the blitter
+#if 0
+void Image::blit(VGContext* context, const Image* src, int sx, int sy, int dx, int dy, int w, int h, bool dither)
+{
+    //img=>img: vgCopyImage
+    //img=>user: vgGetImageSubData
+    //user=>img: vgImageSubData
+    
+    // \todo Implement dither to blitter.
+    this->blit(context, src, sx, sy, dx, dy, w, h, NULL, dither);
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    computeBlitRegion(sx, sy, dx, dy, w, h, src.m_width, src.m_height, m_width, m_height);
+    if(w <= 0 || h <= 0)
+        return;	//zero area
+
+    Array<Color> tmp;
+    tmp.resize(w*h);	//throws bad_alloc
+
+    //copy source region to tmp
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color c = src.readPixel(sx + i, sy + j);
+            c.convert(m_desc.internalFormat);
+            tmp[j*w+i] = c;
+        }
+    }
+
+    int rbits = m_desc.redBits, gbits = m_desc.greenBits, bbits = m_desc.blueBits, abits = m_desc.alphaBits;
+    if(m_desc.isLuminance())
+    {
+        rbits = gbits = bbits = m_desc.luminanceBits;
+        abits = 0;
+    }
+
+    //write tmp to destination region
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color col = tmp[j*w+i];
+
+            if(dither)
+            {
+                static const int matrix[16] = {
+                    0,  8,  2,  10,
+                    12, 4,  14, 6,
+                    3,  11, 1,  9,
+                    15, 7,  13, 5};
+                int x = i & 3;
+                int y = j & 3;
+                RIfloat m = matrix[y*4+x] / 16.0f;
+
+                if(rbits) col.r = ditherChannel(col.r, rbits, m);
+                if(gbits) col.g = ditherChannel(col.g, gbits, m);
+                if(bbits) col.b = ditherChannel(col.b, bbits, m);
+                if(abits) col.a = ditherChannel(col.a, abits, m);
+            }
+
+            writePixel(dx + i, dy + j, col);
+        }
+    }
+}
+#endif
+
+/**
+ * \brief   Common body for drawImage-functions (one is the actual drawImage, and the
+ *          other one is used for scissored image-set operations.
+ * \todo    Reorganize all image draw operations to use this function. 
+ */
+static bool drawImageBody(VGContext* context, Image* image, const Matrix3x3& userToSurfaceMatrix,
+    VGImageQuality imageQuality,
+    VGBlendMode blendMode,
+    bool hasMasking,
+    bool hasColorTransform,
+    VGImageMode imageMode)
+{
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+        return false;   //no EGL surface is current at the moment
+
+    Image* img = (Image*)image;
+    //transform image corners into the surface space
+    Vector3 p0(0, 0, 1);
+    Vector3 p1(0, (RIfloat)img->getHeight(), 1);
+    Vector3 p2((RIfloat)img->getWidth(), (RIfloat)img->getHeight(), 1);
+    Vector3 p3((RIfloat)img->getWidth(), 0, 1);
+
+    p0 = userToSurfaceMatrix * p0;
+    p1 = userToSurfaceMatrix * p1;
+    p2 = userToSurfaceMatrix * p2;
+    p3 = userToSurfaceMatrix * p3;
+    if(p0.z <= 0.0f || p1.z <= 0.0f || p2.z <= 0.0f || p3.z <= 0.0f)
+        return false;
+
+    //projection
+    p0 *= 1.0f/p0.z;
+    p1 *= 1.0f/p1.z;
+    p2 *= 1.0f/p2.z;
+    p3 *= 1.0f/p3.z;
+
+    Rasterizer& rasterizer = context->m_rasterizer;
+    rasterizer.clear();
+
+    if(context->m_scissoring)
+        rasterizer.setScissor(context->m_scissor);	//throws bad_alloc
+
+    PixelPipe& pixelPipe = context->m_pixelPipe;
+    pixelPipe.setTileFillColor(context->m_tileFillColor);
+    pixelPipe.setPaint((Paint*)context->m_fillPaint);
+    const bool aa = imageQuality == VG_IMAGE_QUALITY_NONANTIALIASED ? false : true;
+    rasterizer.setAntiAliasing(aa);
+    pixelPipe.setImageQuality(imageQuality);
+    pixelPipe.setBlendMode(blendMode);
+    pixelPipe.setRenderToMask(false);
+    pixelPipe.setDrawable(drawable);
+    pixelPipe.setMask(hasMasking);
+    pixelPipe.setColorTransform(hasColorTransform, context->m_colorTransformValues);
+
+    Matrix3x3 surfaceToImageMatrix = userToSurfaceMatrix;
+    Matrix3x3 surfaceToPaintMatrix = userToSurfaceMatrix * context->m_fillPaintToUser;
+    if(surfaceToImageMatrix.invert() && surfaceToPaintMatrix.invert())
+    {
+        VGImageMode imode = imageMode;
+
+        if(!surfaceToPaintMatrix.isAffine())
+            imode = VG_DRAW_IMAGE_NORMAL;	//if paint matrix is not affine, always use normal image mode
+
+        surfaceToPaintMatrix[2].set(0,0,1);	//force affine
+
+        pixelPipe.setImage(img, imode);
+        pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+        pixelPipe.setSurfaceToImageMatrix(surfaceToImageMatrix);
+        pixelPipe.prepareSpanUniforms(aa);
+        rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_EVEN_ODD, &pixelPipe);
+
+        rasterizer.addEdge(Vector2(p0.x,p0.y), Vector2(p1.x,p1.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p1.x,p1.y), Vector2(p2.x,p2.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p2.x,p2.y), Vector2(p3.x,p3.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p3.x,p3.y), Vector2(p0.x,p0.y));	//throws bad_alloc
+
+        rasterizer.fill();	//throws bad_alloc
+    }
+
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from multisampled format to display format.
+* \param    unsafeInput     Data may contain incorrect values (user data)     
+* \return
+* \note     May throw std::bad_alloc on cases where blitting within the
+*           same buffer and overlapping regions (this may change in the
+*           future).
+*//*-------------------------------------------------------------------*/
+
+void Image::blit(VGContext* context, const Image* src, 
+    int sx, int sy, int dx, int dy, int w, int h, 
+    Array<Rectangle>* scissors,
+    bool dither)
+{
+    bool overlap = false;
+    (void)dither;
+    DynamicBlitter& blitter = context->getBlitter();
+
+    //RI_ASSERT(!src->isInUse(this));
+    //int isx = sx, isy = sy, idx = dx, idy = dy, iw = w, ih = h;
+
+    computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), m_width, m_height);
+
+    if(w <= 0 || h <= 0)
+        return;	//zero area
+
+    if (this->m_data == src->m_data)
+    {
+        // The images may overlap.
+        int minsx = RI_INT_MIN(sx, dx);
+        int minsy = RI_INT_MIN(sy, dy);
+        int maxsx = RI_INT_MAX(sx, dx);
+        int maxsy = RI_INT_MAX(sy, dy);
+
+        if ((maxsx < (minsx + w)) && (maxsy < (minsy + h)))
+        {
+            overlap = true;
+        }
+    }
+
+    if (!scissors)
+    {
+        // Currently the blitter does not support scissors
+        if (!overlap)
+        {
+            blitter.prepareBlit(this, src, sx+src->m_storageOffsetX, sy+src->m_storageOffsetY, 
+                dx+m_storageOffsetX, dy+m_storageOffsetY, w, h);
+            blitter.blit();
+        } else
+        {
+            Image temp(src->getDescriptor(), w, h, VG_IMAGE_QUALITY_NONANTIALIASED);
+            blitter.prepareBlit(&temp, src, sx+src->m_storageOffsetX, sy+src->m_storageOffsetY, 0, 0, w, h);
+            blitter.blit();
+            blitter.prepareBlit(this, &temp, 0, 0, dx+m_storageOffsetX, dy+m_storageOffsetY, w, h);
+            blitter.blit();
+        }
+    } else
+    {
+        // For the moment, use the generic poly-rasterizer for scissored images.
+        if (!overlap)
+        {
+            // Create a child image
+            Image blitImage((Image*)src, sx, sy, w, h);
+            Matrix3x3 tx;
+            tx.set(1, 0, dx, 0, 1, dy, 0, 0, 1);
+
+            drawImageBody(context, &blitImage, tx,
+                        VG_IMAGE_QUALITY_NONANTIALIASED,
+                        VG_BLEND_SRC,
+                        false,
+                        false,
+                        VG_DRAW_IMAGE_NORMAL);
+        } else
+        {
+            // Create a copy of the source region
+            Image temp(src->getDescriptor(), w, h, VG_IMAGE_QUALITY_NONANTIALIASED);
+            blitter.prepareBlit(&temp, src, sx, sy, 0, 0, w, h);
+            blitter.blit();
+
+            Image blitImage((Image*)src, sx, sy, w, h);
+            Matrix3x3 tx;
+            tx.set(1, 0, dx, 0, 1, dy, 0, 0, 1);
+
+            drawImageBody(context, &blitImage, tx,
+                        VG_IMAGE_QUALITY_NONANTIALIASED,
+                        VG_BLEND_SRC,
+                        false,
+                        false,
+                        VG_DRAW_IMAGE_NORMAL);
+        }
+    }
+
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns the color at pixel (x,y).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Image::readPixel(int x, int y) const
+{
+    const RIuint32 p = readPackedPixel(x, y);
+
+    Color c;
+    c.unpack(p, m_desc);
+    return c;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Writes the color to pixel (x,y). Internal color formats must
+*			match.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::writePixel(int x, int y, const Color& c)
+{
+    RI_ASSERT(c.getInternalFormat() == m_desc.internalFormat);
+
+    RIuint32 p = c.pack(m_desc);
+    writePackedPixel(x, y, p);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Writes a filtered color to destination surface
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::writeFilteredPixel(int i, int j, const Color& color, VGbitfield channelMask)
+{
+    //section 3.4.4: before color space conversion, premultiplied colors are
+    //clamped to alpha, and the color is converted to nonpremultiplied format
+    //section 11.2: how to deal with channel mask
+    //step 1
+    Color f = color;
+    f.clamp();			//vgColorMatrix and vgLookups can produce colors that exceed alpha or [0,1] range
+
+    //step 2: color space conversion
+    f.convert((Color::InternalFormat)(m_desc.internalFormat & (Color::NONLINEAR | Color::LUMINANCE)));
+
+    //step 3: read the destination color and convert it to nonpremultiplied
+    Color d = readPixel(i,j);
+    d.unpremultiply();
+    RI_ASSERT(d.getInternalFormat() == f.getInternalFormat());
+
+    //step 4: replace the destination channels specified by the channelMask (channelmask is ignored for luminance formats)
+    if(!m_desc.isLuminance())
+    {   //rgba format => use channelmask
+        if(channelMask & VG_RED)
+            d.r = f.r;
+        if(channelMask & VG_GREEN)
+            d.g = f.g;
+        if(channelMask & VG_BLUE)
+            d.b = f.b;
+        if(channelMask & VG_ALPHA)
+            d.a = f.a;
+    }
+    else d = f;
+
+    //step 5: if destination is premultiplied, convert to premultiplied format
+    if(m_desc.isPremultiplied())
+        d.premultiply();
+    //write the color to destination
+    writePixel(i,j,d);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Reads the pixel (x,y) and converts it into an alpha mask value.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RIfloat Image::readMaskPixel(int x, int y) const
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(x >= 0 && x < m_width);
+    RI_ASSERT(y >= 0 && y < m_height);
+    RI_ASSERT(m_referenceCount > 0);
+
+    Color c = readPixel(x,y);
+    if(m_desc.isLuminance())
+    {
+        return c.r;
+    }
+    else
+    {	//rgba
+        if(m_desc.alphaBits)
+            return c.a;
+        return c.r;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Writes the alpha mask to pixel (x,y).
+* \param
+* \return
+* \note		Overwrites color.
+*//*-------------------------------------------------------------------*/
+
+void Image::writeMaskPixel(int x, int y, RIfloat m)
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(x >= 0 && x < m_width);
+    RI_ASSERT(y >= 0 && y < m_height);
+    RI_ASSERT(m_referenceCount > 0);
+
+    //if luminance or no alpha, red channel will be used, otherwise alpha channel will be used
+    writePixel(x, y, Color(m,m,m,m,m_desc.internalFormat));
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Reads a texel (u,v) at the given mipmap level. Tiling modes and
+*			color space conversion are applied. Outputs color in premultiplied
+*			format.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Image::readTexel(int u, int v, int level, VGTilingMode tilingMode, const Color& tileFillColor) const
+{
+    const Image* image = this;
+    if( level > 0 )
+    {
+        RI_ASSERT(false);
+    }
+    RI_ASSERT(image);
+
+    Color p;
+    if(tilingMode == VG_TILE_FILL)
+    {
+        if(u < 0 || v < 0 || u >= image->m_width || v >= image->m_height)
+            p = tileFillColor;
+        else
+            p = image->readPixel(u, v);
+    }
+    else if(tilingMode == VG_TILE_PAD)
+    {
+        u = RI_INT_MIN(RI_INT_MAX(u,0),image->m_width-1);
+        v = RI_INT_MIN(RI_INT_MAX(v,0),image->m_height-1);
+        p = image->readPixel(u, v);
+    }
+    else if(tilingMode == VG_TILE_REPEAT)
+    {
+        u = RI_INT_MOD(u, image->m_width);
+        v = RI_INT_MOD(v, image->m_height);
+        p = image->readPixel(u, v);
+    }
+    else
+    {
+        RI_ASSERT(tilingMode == VG_TILE_REFLECT);
+
+        u = RI_INT_MOD(u, image->m_width*2);
+        v = RI_INT_MOD(v, image->m_height*2);
+        if( u >= image->m_width ) u = image->m_width*2-1 - u;
+        if( v >= image->m_height ) v = image->m_height*2-1 - v;
+        p = image->readPixel(u, v);
+    }
+
+    p.premultiply();    //interpolate in premultiplied format
+    return p;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Maps point (x,y) to an image and returns a filtered,
+*			premultiplied color value.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Image::resample(RIfloat x, RIfloat y, const Matrix3x3& surfaceToImage, VGImageQuality quality, VGTilingMode tilingMode, const Color& tileFillColor)	//throws bad_alloc
+{
+    RI_ASSERT(m_referenceCount > 0);
+
+    VGbitfield aq = getAllowedQuality();
+    aq &= (VGbitfield)quality;
+
+    Vector3 uvw(x,y,1.0f);
+    uvw = surfaceToImage * uvw;
+    RIfloat oow = 1.0f / uvw.z;
+    uvw *= oow;
+
+#if 0
+    if(aq & VG_IMAGE_QUALITY_BETTER)
+    {	//EWA on mipmaps
+        makeMipMaps();	//throws bad_alloc
+
+        Color::InternalFormat procFormat = (Color::InternalFormat)(m_desc.internalFormat | Color::PREMULTIPLIED);
+
+        RIfloat m_pixelFilterRadius = 1.25f;
+        RIfloat m_resamplingFilterRadius = 1.25f;
+
+        RIfloat Ux = (surfaceToImage[0][0] - uvw.x * surfaceToImage[2][0]) * oow * m_pixelFilterRadius;
+        RIfloat Vx = (surfaceToImage[1][0] - uvw.y * surfaceToImage[2][0]) * oow * m_pixelFilterRadius;
+        RIfloat Uy = (surfaceToImage[0][1] - uvw.x * surfaceToImage[2][1]) * oow * m_pixelFilterRadius;
+        RIfloat Vy = (surfaceToImage[1][1] - uvw.y * surfaceToImage[2][1]) * oow * m_pixelFilterRadius;
+        RIfloat U0 = uvw.x;
+        RIfloat V0 = uvw.y;
+
+        //calculate mip level
+        int level = 0;
+        RIfloat axis1sq = Ux*Ux + Vx*Vx;
+        RIfloat axis2sq = Uy*Uy + Vy*Vy;
+        RIfloat minorAxissq = RI_MIN(axis1sq,axis2sq);
+        while(minorAxissq > 9.0f && level < m_mipmaps.size())	//half the minor axis must be at least three texels
+        {
+            level++;
+            minorAxissq *= 0.25f;
+        }
+
+        RIfloat sx = 1.0f;
+        RIfloat sy = 1.0f;
+        if(level > 0)
+        {
+            sx = (RIfloat)m_mipmaps[level-1]->m_width / (RIfloat)m_width;
+            sy = (RIfloat)m_mipmaps[level-1]->m_height / (RIfloat)m_height;
+        }
+        Ux *= sx;
+        Vx *= sx;
+        U0 *= sx;
+        Uy *= sy;
+        Vy *= sy;
+        V0 *= sy;
+
+        //clamp filter size so that filtering doesn't take excessive amount of time (clamping results in aliasing)
+        RIfloat lim = 100.0f;
+        axis1sq = Ux*Ux + Vx*Vx;
+        axis2sq = Uy*Uy + Vy*Vy;
+        if( axis1sq > lim*lim )
+        {
+            RIfloat s = lim / (RIfloat)sqrt(axis1sq);
+            Ux *= s;
+            Vx *= s;
+        }
+        if( axis2sq > lim*lim )
+        {
+            RIfloat s = lim / (RIfloat)sqrt(axis2sq);
+            Uy *= s;
+            Vy *= s;
+        }
+
+
+        //form elliptic filter by combining texel and pixel filters
+        RIfloat A = Vx*Vx + Vy*Vy + 1.0f;
+        RIfloat B = -2.0f*(Ux*Vx + Uy*Vy);
+        RIfloat C = Ux*Ux + Uy*Uy + 1.0f;
+        //scale by the user-defined size of the kernel
+        A *= m_resamplingFilterRadius;
+        B *= m_resamplingFilterRadius;
+        C *= m_resamplingFilterRadius;
+
+        //calculate bounding box in texture space
+        RIfloat usize = (RIfloat)sqrt(C);
+        RIfloat vsize = (RIfloat)sqrt(A);
+        int u1 = (int)floor(U0 - usize + 0.5f);
+        int u2 = (int)floor(U0 + usize + 0.5f);
+        int v1 = (int)floor(V0 - vsize + 0.5f);
+        int v2 = (int)floor(V0 + vsize + 0.5f);
+        if( u1 == u2 || v1 == v2 )
+            return Color(0,0,0,0,procFormat);
+
+        //scale the filter so that Q = 1 at the cutoff radius
+        RIfloat F = A*C - 0.25f * B*B;
+        if( F <= 0.0f )
+            return Color(0,0,0,0,procFormat);	//invalid filter shape due to numerical inaccuracies => return black
+        RIfloat ooF = 1.0f / F;
+        A *= ooF;
+        B *= ooF;
+        C *= ooF;
+
+        //evaluate filter by using forward differences to calculate Q = A*U^2 + B*U*V + C*V^2
+        Color color(0,0,0,0,procFormat);
+        RIfloat sumweight = 0.0f;
+        RIfloat DDQ = 2.0f * A;
+        RIfloat U = (RIfloat)u1 - U0 + 0.5f;
+        for(int v=v1;v<v2;v++)
+        {
+            RIfloat V = (RIfloat)v - V0 + 0.5f;
+            RIfloat DQ = A*(2.0f*U+1.0f) + B*V;
+            RIfloat Q = (C*V+B*U)*V + A*U*U;
+            for(int u=u1;u<u2;u++)
+            {
+                if( Q >= 0.0f && Q < 1.0f )
+                {	//Q = r^2, fit gaussian to the range [0,1]
+                    RIfloat weight = (RIfloat)exp(-0.5f * 10.0f * Q);	//gaussian at radius 10 equals 0.0067
+                    color += weight * readTexel(u, v, level, tilingMode, tileFillColor);
+                    sumweight += weight;
+                }
+                Q += DQ;
+                DQ += DDQ;
+            }
+        }
+        if( sumweight == 0.0f )
+            return Color(0,0,0,0,procFormat);
+        RI_ASSERT(sumweight > 0.0f);
+        sumweight = 1.0f / sumweight;
+        return color * sumweight;
+    }
+    else
+#endif
+        //if(aq & VG_IMAGE_QUALITY_FASTER)
+    if(aq & VG_IMAGE_QUALITY_BETTER)
+    {	//bilinear
+        uvw.x -= 0.5f;
+        uvw.y -= 0.5f;
+        int u = (int)floor(uvw.x);
+        int v = (int)floor(uvw.y);
+        Color c00 = readTexel(u,v, 0, tilingMode, tileFillColor);
+        Color c10 = readTexel(u+1,v, 0, tilingMode, tileFillColor);
+        Color c01 = readTexel(u,v+1, 0, tilingMode, tileFillColor);
+        Color c11 = readTexel(u+1,v+1, 0, tilingMode, tileFillColor);
+        RIfloat fu = uvw.x - (RIfloat)u;
+        RIfloat fv = uvw.y - (RIfloat)v;
+        Color c0 = c00 * (1.0f - fu) + c10 * fu;
+        Color c1 = c01 * (1.0f - fu) + c11 * fu;
+        return c0 * (1.0f - fv) + c1 * fv;
+    }
+    else //VG_IMAGE_QUALITY_FASTER and VG_IMAGE_QUALITY_NONANTIALIASED
+    {	//point sampling
+        return readTexel((int)floor(uvw.x), (int)floor(uvw.y), 0, tilingMode, tileFillColor);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies color matrix filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::colorMatrix(const Image& src, const RIfloat* matrix, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(matrix);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat srcFormat = src.m_desc.internalFormat;
+    Color::InternalFormat procFormat = (Color::InternalFormat)(srcFormat & ~Color::LUMINANCE);	//process in RGB, not luminance
+    if(filterFormatLinear)
+        procFormat = (Color::InternalFormat)(procFormat & ~Color::NONLINEAR);
+    else
+        procFormat = (Color::InternalFormat)(procFormat | Color::NONLINEAR);
+
+    if(filterFormatPremultiplied)
+        procFormat = (Color::InternalFormat)(procFormat | Color::PREMULTIPLIED);
+    else
+        procFormat = (Color::InternalFormat)(procFormat & ~Color::PREMULTIPLIED);
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color s = src.readPixel(i,j);	//convert to RGBA [0,1]
+            s.convert(procFormat);
+
+            Color d(0,0,0,0,procFormat);
+            d.r = matrix[0+4*0] * s.r + matrix[0+4*1] * s.g + matrix[0+4*2] * s.b + matrix[0+4*3] * s.a + matrix[0+4*4];
+            d.g = matrix[1+4*0] * s.r + matrix[1+4*1] * s.g + matrix[1+4*2] * s.b + matrix[1+4*3] * s.a + matrix[1+4*4];
+            d.b = matrix[2+4*0] * s.r + matrix[2+4*1] * s.g + matrix[2+4*2] * s.b + matrix[2+4*3] * s.a + matrix[2+4*4];
+            d.a = matrix[3+4*0] * s.r + matrix[3+4*1] * s.g + matrix[3+4*2] * s.b + matrix[3+4*3] * s.a + matrix[3+4*4];
+
+            writeFilteredPixel(i, j, d, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Reads a pixel from image with tiling mode applied.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static Color readTiledPixel(int x, int y, int w, int h, VGTilingMode tilingMode, const Array<Color>& image, const Color& edge)
+{
+    Color s;
+    if(x < 0 || x >= w || y < 0 || y >= h)
+    {	//apply tiling mode
+        switch(tilingMode)
+        {
+        case VG_TILE_FILL:
+            s = edge;
+            break;
+        case VG_TILE_PAD:
+            x = RI_INT_MIN(RI_INT_MAX(x, 0), w-1);
+            y = RI_INT_MIN(RI_INT_MAX(y, 0), h-1);
+            RI_ASSERT(x >= 0 && x < w && y >= 0 && y < h);
+            s = image[y*w+x];
+            break;
+        case VG_TILE_REPEAT:
+            x = RI_INT_MOD(x, w);
+            y = RI_INT_MOD(y, h);
+            RI_ASSERT(x >= 0 && x < w && y >= 0 && y < h);
+            s = image[y*w+x];
+            break;
+        default:
+            RI_ASSERT(tilingMode == VG_TILE_REFLECT);
+            x = RI_INT_MOD(x, w*2);
+            y = RI_INT_MOD(y, h*2);
+            if(x >= w) x = w*2-1-x;
+            if(y >= h) y = h*2-1-y;
+            RI_ASSERT(x >= 0 && x < w && y >= 0 && y < h);
+            s = image[y*w+x];
+            break;
+        }
+    }
+    else
+    {
+        RI_ASSERT(x >= 0 && x < w && y >= 0 && y < h);
+        s = image[y*w+x];
+    }
+    return s;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns processing format for filtering.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static Color::InternalFormat getProcessingFormat(Color::InternalFormat srcFormat, bool filterFormatLinear, bool filterFormatPremultiplied)
+{
+    Color::InternalFormat procFormat = (Color::InternalFormat)(srcFormat & ~Color::LUMINANCE);	//process in RGB, not luminance
+    if(filterFormatLinear)
+        procFormat = (Color::InternalFormat)(procFormat & ~Color::NONLINEAR);
+    else
+        procFormat = (Color::InternalFormat)(procFormat | Color::NONLINEAR);
+
+    if(filterFormatPremultiplied)
+        procFormat = (Color::InternalFormat)(procFormat | Color::PREMULTIPLIED);
+    else
+        procFormat = (Color::InternalFormat)(procFormat & ~Color::PREMULTIPLIED);
+    return procFormat;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies convolution filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::convolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernel, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(kernel && kernelWidth > 0 && kernelHeight > 0);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+
+    Color edge = edgeFillColor;
+    edge.clamp();
+    edge.convert(procFormat);
+
+    Array<Color> tmp;
+    tmp.resize(src.m_width*src.m_height);	//throws bad_alloc
+
+    //copy source region to tmp and do conversion
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<src.m_width;i++)
+        {
+            Color s = src.readPixel(i, j);
+            s.convert(procFormat);
+            tmp[j*src.m_width+i] = s;
+        }
+    }
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+
+            for(int kj=0;kj<kernelHeight;kj++)
+            {
+                for(int ki=0;ki<kernelWidth;ki++)
+                {
+                    int x = i+ki-shiftX;
+                    int y = j+kj-shiftY;
+                    Color s = readTiledPixel(x, y, src.m_width, src.m_height, tilingMode, tmp, edge);
+
+                    int kx = kernelWidth-ki-1;
+                    int ky = kernelHeight-kj-1;
+                    RI_ASSERT(kx >= 0 && kx < kernelWidth && ky >= 0 && ky < kernelHeight);
+
+                    sum += (RIfloat)kernel[kx*kernelHeight+ky] * s;
+                }
+            }
+
+            sum *= scale;
+            sum.r += bias;
+            sum.g += bias;
+            sum.b += bias;
+            sum.a += bias;
+
+            writeFilteredPixel(i, j, sum, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies separable convolution filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::separableConvolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernelX, const RIint16* kernelY, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(kernelX && kernelY && kernelWidth > 0 && kernelHeight > 0);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+
+    Color edge = edgeFillColor;
+    edge.clamp();
+    edge.convert(procFormat);
+
+    Array<Color> tmp;
+    tmp.resize(src.m_width*src.m_height);	//throws bad_alloc
+
+    //copy source region to tmp and do conversion
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<src.m_width;i++)
+        {
+            Color s = src.readPixel(i, j);
+            s.convert(procFormat);
+            tmp[j*src.m_width+i] = s;
+        }
+    }
+
+    Array<Color> tmp2;
+    tmp2.resize(w*src.m_height);	//throws bad_alloc
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+            for(int ki=0;ki<kernelWidth;ki++)
+            {
+                int x = i+ki-shiftX;
+                Color s = readTiledPixel(x, j, src.m_width, src.m_height, tilingMode, tmp, edge);
+
+                int kx = kernelWidth-ki-1;
+                RI_ASSERT(kx >= 0 && kx < kernelWidth);
+
+                sum += (RIfloat)kernelX[kx] * s;
+            }
+            tmp2[j*w+i] = sum;
+        }
+    }
+
+    if(tilingMode == VG_TILE_FILL)
+    {	//convolve the edge color
+        Color sum(0,0,0,0,procFormat);
+        for(int ki=0;ki<kernelWidth;ki++)
+        {
+            sum += (RIfloat)kernelX[ki] * edge;
+        }
+        edge = sum;
+    }
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+            for(int kj=0;kj<kernelHeight;kj++)
+            {
+                int y = j+kj-shiftY;
+                Color s = readTiledPixel(i, y, w, src.m_height, tilingMode, tmp2, edge);
+
+                int ky = kernelHeight-kj-1;
+                RI_ASSERT(ky >= 0 && ky < kernelHeight);
+
+                sum += (RIfloat)kernelY[ky] * s;
+            }
+
+            sum *= scale;
+            sum.r += bias;
+            sum.g += bias;
+            sum.b += bias;
+            sum.a += bias;
+
+            writeFilteredPixel(i, j, sum, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies Gaussian blur filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::gaussianBlur(const Image& src, RIfloat stdDeviationX, RIfloat stdDeviationY, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(stdDeviationX > 0.0f && stdDeviationY > 0.0f);
+    RI_ASSERT(stdDeviationX <= RI_MAX_GAUSSIAN_STD_DEVIATION && stdDeviationY <= RI_MAX_GAUSSIAN_STD_DEVIATION);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+
+    Color edge = edgeFillColor;
+    edge.clamp();
+    edge.convert(procFormat);
+
+    Array<Color> tmp;
+    tmp.resize(src.m_width*src.m_height);	//throws bad_alloc
+
+    //copy source region to tmp and do conversion
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<src.m_width;i++)
+        {
+            Color s = src.readPixel(i, j);
+            s.convert(procFormat);
+            tmp[j*src.m_width+i] = s;
+        }
+    }
+
+    RIfloat expScaleX = -1.0f / (2.0f*stdDeviationX*stdDeviationX);
+    RIfloat expScaleY = -1.0f / (2.0f*stdDeviationY*stdDeviationY);
+
+    int kernelWidth = (int)(stdDeviationX * 4.0f + 1.0f);
+    int kernelHeight = (int)(stdDeviationY * 4.0f + 1.0f);
+
+    //make a separable kernel
+    Array<RIfloat> kernelX;
+    kernelX.resize(kernelWidth*2+1);
+    int shiftX = kernelWidth;
+    RIfloat scaleX = 0.0f;
+    for(int i=0;i<kernelX.size();i++)
+    {
+        int x = i-shiftX;
+        kernelX[i] = (RIfloat)exp((RIfloat)x*(RIfloat)x * expScaleX);
+        scaleX += kernelX[i];
+    }
+    scaleX = 1.0f / scaleX;	//NOTE: using the mathematical definition of the scaling term doesn't work since we cut the filter support early for performance
+
+    Array<RIfloat> kernelY;
+    kernelY.resize(kernelHeight*2+1);
+    int shiftY = kernelHeight;
+    RIfloat scaleY = 0.0f;
+    for(int i=0;i<kernelY.size();i++)
+    {
+        int y = i-shiftY;
+        kernelY[i] = (RIfloat)exp((RIfloat)y*(RIfloat)y * expScaleY);
+        scaleY += kernelY[i];
+    }
+    scaleY = 1.0f / scaleY;	//NOTE: using the mathematical definition of the scaling term doesn't work since we cut the filter support early for performance
+
+    Array<Color> tmp2;
+    tmp2.resize(w*src.m_height);	//throws bad_alloc
+    //horizontal pass
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+            for(int ki=0;ki<kernelX.size();ki++)
+            {
+                int x = i+ki-shiftX;
+                sum += kernelX[ki] * readTiledPixel(x, j, src.m_width, src.m_height, tilingMode, tmp, edge);
+            }
+            tmp2[j*w+i] = sum * scaleX;
+        }
+    }
+    //vertical pass
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+            for(int kj=0;kj<kernelY.size();kj++)
+            {
+                int y = j+kj-shiftY;
+                sum += kernelY[kj] * readTiledPixel(i, y, w, src.m_height, tilingMode, tmp2, edge);
+            }
+            writeFilteredPixel(i, j, sum * scaleY, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns lookup table format for lookup filters.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static Color::InternalFormat getLUTFormat(bool outputLinear, bool outputPremultiplied)
+{
+    Color::InternalFormat lutFormat = Color::lRGBA;
+    if(outputLinear && outputPremultiplied)
+        lutFormat = Color::lRGBA_PRE;
+    else if(!outputLinear && !outputPremultiplied)
+        lutFormat = Color::sRGBA;
+    else if(!outputLinear && outputPremultiplied)
+        lutFormat = Color::sRGBA_PRE;
+    return lutFormat;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies multi-channel lookup table filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::lookup(const Image& src, const RIuint8 * redLUT, const RIuint8 * greenLUT, const RIuint8 * blueLUT, const RIuint8 * alphaLUT, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(redLUT && greenLUT && blueLUT && alphaLUT);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+    Color::InternalFormat lutFormat = getLUTFormat(outputLinear, outputPremultiplied);
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color s = src.readPixel(i,j);	//convert to RGBA [0,1]
+            s.convert(procFormat);
+
+            Color d(0,0,0,0,lutFormat);
+            d.r = intToColor(  redLUT[colorToInt(s.r, 255)], 255);
+            d.g = intToColor(greenLUT[colorToInt(s.g, 255)], 255);
+            d.b = intToColor( blueLUT[colorToInt(s.b, 255)], 255);
+            d.a = intToColor(alphaLUT[colorToInt(s.a, 255)], 255);
+
+            writeFilteredPixel(i, j, d, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies single channel lookup table filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::lookupSingle(const Image& src, const RIuint32 * lookupTable, VGImageChannel sourceChannel, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(lookupTable);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    if(src.m_desc.isLuminance())
+        sourceChannel = VG_RED;
+    else if(src.m_desc.redBits + src.m_desc.greenBits + src.m_desc.blueBits == 0)
+    {
+        RI_ASSERT(src.m_desc.alphaBits);
+        sourceChannel = VG_ALPHA;
+    }
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+    Color::InternalFormat lutFormat = getLUTFormat(outputLinear, outputPremultiplied);
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color s = src.readPixel(i,j);	//convert to RGBA [0,1]
+            s.convert(procFormat);
+            int e;
+            switch(sourceChannel)
+            {
+            case VG_RED:
+                e = colorToInt(s.r, 255);
+                break;
+            case VG_GREEN:
+                e = colorToInt(s.g, 255);
+                break;
+            case VG_BLUE:
+                e = colorToInt(s.b, 255);
+                break;
+            default:
+                RI_ASSERT(sourceChannel == VG_ALPHA);
+                e = colorToInt(s.a, 255);
+                break;
+            }
+
+            RIuint32 l = ((const RIuint32*)lookupTable)[e];
+            Color d(0,0,0,0,lutFormat);
+            d.r = intToColor((l>>24), 255);
+            d.g = intToColor((l>>16), 255);
+            d.b = intToColor((l>> 8), 255);
+            d.a = intToColor((l    ), 255);
+
+            writeFilteredPixel(i, j, d, channelMask);
+        }
+    }
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Surface::Surface(const Color::Descriptor& desc, int width, int height, int numSamples) :
+    m_width(width),
+    m_height(height),
+    m_numSamples(numSamples),
+    m_referenceCount(0),
+    m_image(NULL)
+{
+    RI_ASSERT(width > 0 && height > 0 && numSamples > 0 && numSamples <= 32);
+    m_image = RI_NEW(Image, (desc, width*numSamples, height, 0));	//throws bad_alloc
+    m_image->addReference();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Surface::Surface(Image* image) :
+    m_width(0),
+    m_height(0),
+    m_numSamples(1),
+    m_referenceCount(0),
+    m_image(image)
+{
+    RI_ASSERT(image);
+    m_width = image->getWidth();
+    m_height = image->getHeight();
+    m_image->addReference();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Surface::Surface(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data) :
+    m_width(width),
+    m_height(height),
+    m_numSamples(1),
+    m_referenceCount(0),
+    m_image(NULL)
+{
+    RI_ASSERT(width > 0 && height > 0);
+    m_image = RI_NEW(Image, (desc, width, height, stride, data));	//throws bad_alloc
+    m_image->addReference();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Surface::~Surface()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    if(!m_image->removeReference())
+        RI_DELETE(m_image);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Surface::clear(const Color& clearColor, int x, int y, int w, int h, const Array<Rectangle>* scissors)
+{
+    RI_ASSERT(m_numSamples == 1);
+
+    Image* image = m_image;
+
+    Color col = clearColor;
+    col.clamp();
+    col.convert(m_image->getDescriptor().internalFormat);
+
+    IntegerColor ic = IntegerColor(col);
+    ic.truncateColor(m_image->getDescriptor());
+    const RIuint32 c = ic.getPackedColor(m_image->getDescriptor());
+
+    if (x != 0 || y != 0 || w != image->getWidth() || h != image->getHeight() || scissors)
+    {
+        // Simple implementation: intersect with surface and clip rects -> may clear the
+        // same area several times. Best if scissors are non-overlapping
+        Rectangle r(0,0,getWidth(),getHeight());
+        r.intersect(Rectangle(x,y,w,h));
+
+        if (r.isEmpty() || (scissors && scissors->size() == 0))
+            return;
+
+        if (scissors && scissors->size())
+        {
+            for (int i = 0; i < scissors->size(); i++)
+            {
+                Rectangle s = (*scissors)[i];
+                s.intersect(r);
+
+                if (s.isEmpty())
+                    continue;
+
+                image->fillPackedRectangle(s.x, s.y, s.width, s.height, c);
+            }
+        }
+        else
+        {
+            image->fillPackedRectangle(r.x, r.y, r.width, r.height, c);
+        }
+    }
+    else
+    {
+        // Clear the whole buffer
+
+        m_image->fillPacked(c);
+   }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#if 0
+void Surface::blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h)
+{
+    Rectangle rect;
+    rect.x = 0;
+    rect.y = 0;
+    rect.width = getWidth();
+    rect.height = getHeight();
+    Array<Rectangle> scissors;
+    scissors.push_back(rect);
+    blit(src, sx, sy, dx, dy, w, h, scissors);
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note		no overlap is possible. Single sample to single or multisample (replicate)
+*//*-------------------------------------------------------------------*/
+
+#if 0
+void Surface::blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h, const Array<Rectangle>& scissors)
+{
+    //img=>fb: vgSetPixels
+    //user=>fb: vgWritePixels
+    computeBlitRegion(sx, sy, dx, dy, w, h, src.getWidth(), src.getHeight(), getWidth(), getHeight());
+    if(w <= 0 || h <= 0)
+        return;	//zero area
+
+    Array<ScissorEdge> scissorEdges;
+    for(int i=0;i<scissors.size();i++)
+    {
+        if(scissors[i].width > 0 && scissors[i].height > 0)
+        {
+            ScissorEdge e;
+            e.miny = scissors[i].y;
+            e.maxy = RI_INT_ADDSATURATE(scissors[i].y, scissors[i].height);
+
+            e.x = scissors[i].x;
+            e.direction = 1;
+            scissorEdges.push_back(e);	//throws bad_alloc
+            e.x = RI_INT_ADDSATURATE(scissors[i].x, scissors[i].width);
+            e.direction = -1;
+            scissorEdges.push_back(e);	//throws bad_alloc
+        }
+    }
+    if(!scissorEdges.size())
+        return;	//there are no scissor rectangles => nothing is visible
+
+    //sort scissor edges by edge x
+    scissorEdges.sort();
+
+    Array<ScissorEdge> scissorAet;
+    for(int j=0;j<h;j++)
+    {
+        //gather scissor edges intersecting this scanline
+        scissorAet.clear();
+        for(int e=0;e<scissorEdges.size();e++)
+        {
+            const ScissorEdge& se = scissorEdges[e];
+            if(dy + j >= se.miny && dy + j < se.maxy)
+                scissorAet.push_back(scissorEdges[e]);	//throws bad_alloc
+        }
+        if(!scissorAet.size())
+            continue;	//scissoring is on, but there are no scissor rectangles on this scanline
+
+        //blit a scanline
+        int scissorWinding = 0;
+        int scissorIndex = 0;
+        for(int i=0;i<w;i++)
+        {
+            while(scissorIndex < scissorAet.size() && scissorAet[scissorIndex].x <= dx + i)
+                scissorWinding += scissorAet[scissorIndex++].direction;
+            RI_ASSERT(scissorWinding >= 0);
+
+            if(scissorWinding)
+            {
+                Color c = src.readPixel(sx + i, sy + j);
+                c.convert(getDescriptor().internalFormat);
+                for(int s=0;s<m_numSamples;s++)
+                    writeSample(dx + i, dy + j, s, c);
+            }
+        }
+    }
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#if 0
+void Surface::blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h)
+{
+    Rectangle rect;
+    rect.x = 0;
+    rect.y = 0;
+    rect.width = getWidth();
+    rect.height = getHeight();
+    Array<Rectangle> scissors;
+    scissors.push_back(rect);
+    blit(src, sx, sy, dx, dy, w, h, scissors);
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#if 0
+void Surface::blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h, const Array<Rectangle>& scissors)
+{
+    RI_ASSERT(m_numSamples == src->m_numSamples);
+
+    //fb=>fb: vgCopyPixels
+    computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), getWidth(), getHeight());
+    if(w <= 0 || h <= 0)
+        return;	//zero area
+
+    Array<ScissorEdge> scissorEdges;
+    for(int i=0;i<scissors.size();i++)
+    {
+        if(scissors[i].width > 0 && scissors[i].height > 0)
+        {
+            ScissorEdge e;
+            e.miny = scissors[i].y;
+            e.maxy = RI_INT_ADDSATURATE(scissors[i].y, scissors[i].height);
+
+            e.x = scissors[i].x;
+            e.direction = 1;
+            scissorEdges.push_back(e);	//throws bad_alloc
+            e.x = RI_INT_ADDSATURATE(scissors[i].x, scissors[i].width);
+            e.direction = -1;
+            scissorEdges.push_back(e);	//throws bad_alloc
+        }
+    }
+    if(!scissorEdges.size())
+        return;	//there are no scissor rectangles => nothing is visible
+
+    //sort scissor edges by edge x
+    scissorEdges.sort();
+
+    Array<Color> tmp;
+    tmp.resize(w*m_numSamples*h);	//throws bad_alloc
+
+    //copy source region to tmp
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            int numSamples = m_numSamples;
+            for(int s=0;s<numSamples;s++)
+            {
+                Color c = src->m_image->readPixel((sx + i)*m_numSamples+s, sy + j);
+                c.convert(m_image->getDescriptor().internalFormat);
+                tmp[(j*w+i)*m_numSamples+s] = c;
+            }
+        }
+    }
+
+    Array<ScissorEdge> scissorAet;
+    for(int j=0;j<h;j++)
+    {
+        //gather scissor edges intersecting this scanline
+        scissorAet.clear();
+        for(int e=0;e<scissorEdges.size();e++)
+        {
+            const ScissorEdge& se = scissorEdges[e];
+            if(dy + j >= se.miny && dy + j < se.maxy)
+                scissorAet.push_back(scissorEdges[e]);	//throws bad_alloc
+        }
+        if(!scissorAet.size())
+            continue;	//scissoring is on, but there are no scissor rectangles on this scanline
+
+        //blit a scanline
+        int scissorWinding = 0;
+        int scissorIndex = 0;
+        for(int i=0;i<w;i++)
+        {
+            while(scissorIndex < scissorAet.size() && scissorAet[scissorIndex].x <= dx + i)
+                scissorWinding += scissorAet[scissorIndex++].direction;
+            RI_ASSERT(scissorWinding >= 0);
+
+            if(scissorWinding)
+            {
+                int numSamples = m_numSamples;
+                for(int s=0;s<numSamples;s++)
+                {
+                    m_image->writePixel((dx + i)*m_numSamples+s, dy + j, tmp[(j*w+i)*m_numSamples+s]);
+                }
+            }
+        }
+    }
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Surface::mask(DynamicBlitter& blitter, const Image* src, VGMaskOperation operation, int x, int y, int w, int h)
+{
+    RI_ASSERT(w > 0 && h > 0);
+    RI_ASSERT(m_numSamples == 1);
+
+    if(operation == VG_CLEAR_MASK || operation == VG_FILL_MASK)
+    {
+        //intersect clear region with image bounds
+        Rectangle r(0,0,getWidth(),getHeight());
+        r.intersect(Rectangle(x,y,w,h));
+
+        if(!r.width || !r.height)
+            return;		//intersection is empty or one of the rectangles is invalid
+
+        {
+            Color mcolor(1.0f, 1.0f, 1.0f, 1.0f, Color::sRGBA_PRE);
+            if (operation == VG_CLEAR_MASK)
+                mcolor = Color(0,0,0,0, Color::sRGBA_PRE);
+            IntegerColor ic = IntegerColor(mcolor);
+            RIuint32 p = ic.getPackedMaskColor(m_image->getDescriptor());
+            m_image->fillPackedRectangle(r.x, r.y, r.width, r.height, p);
+        }
+    }
+    else
+    {
+        int sx = 0, sy = 0, dx = x, dy = y;
+
+        computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), getWidth(), getHeight());
+
+        if(w <= 0 || h <= 0)
+            return;	//zero area
+
+        blitter.enableMaskOperation(true);
+        blitter.setMaskOperation(operation);
+        blitter.prepareBlit(this->m_image, src, sx, sy, dx, dy, w, h);
+        blitter.blit();
+        blitter.enableMaskOperation(false);
+#if 0
+        RI_ASSERT(src);
+
+        int sx = 0, sy = 0, dx = x, dy = y;
+        computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), getWidth(), getHeight());
+        if(w <= 0 || h <= 0)
+            return;	//zero area
+
+        {
+            for(int j=0;j<h;j++)
+            {
+                for(int i=0;i<w;i++)
+                {
+                    RIfloat amask = src->readMaskPixel(sx + i, sy + j);
+                    if(operation == VG_SET_MASK)
+                        writeMaskCoverage(dx + i, dy + j, amask);
+                    else
+                    {
+                        RIfloat aprev = readMaskCoverage(dx + i, dy + j);
+                        RIfloat anew = 0.0f;
+                        switch(operation)
+                        {
+                        case VG_UNION_MASK:		anew = 1.0f - (1.0f - amask)*(1.0f - aprev); break;
+                        case VG_INTERSECT_MASK:	anew = amask * aprev; break;
+                        default:				anew = aprev * (1.0f - amask); RI_ASSERT(operation == VG_SUBTRACT_MASK); break;
+                        }
+                        writeMaskCoverage(dx + i, dy + j, anew);
+                    }
+                }
+            }
+        }
+#endif
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RIfloat Surface::readMaskCoverage(int x, int y) const
+{
+    RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height);
+    RI_ASSERT(m_numSamples == 1);
+    return m_image->readMaskPixel(x, y);
+}
+
+void Surface::writeMaskCoverage(int x, int y, RIfloat m)
+{
+    RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height);
+    RI_ASSERT(m_numSamples == 1);
+    m_image->writeMaskPixel(x, y, m);    //TODO support other than alpha formats but don't write to color channels?
+}
+
+unsigned int Surface::readMaskMSAA(int x, int y) const
+{
+    RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height);
+    RI_ASSERT(m_numSamples > 1);
+    unsigned int m = 0;
+    for(int i=0;i<m_numSamples;i++)
+    {
+        if(m_image->readMaskPixel(x*m_numSamples+i, y) > 0.5f)   //TODO is this the right formula for converting alpha to bit mask? does it matter?
+            m |= 1<<i;
+    }
+    return m;
+}
+
+void Surface::writeMaskMSAA(int x, int y, unsigned int m)
+{
+    RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height);
+    RI_ASSERT(m_numSamples > 1);
+    for(int i=0;i<m_numSamples;i++)
+    {
+        RIfloat a = 0.0f;
+        if(m & (1<<i))
+            a = 1.0f;
+        m_image->writeMaskPixel(x*m_numSamples+i, y, a);    //TODO support other than alpha formats but don't write to color channels?
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Surface::FSAAResolve(int x, int y) const
+{
+    if(m_numSamples == 1)
+        return readSample(x, y, 0);
+
+    Color::InternalFormat aaFormat = getDescriptor().isLuminance() ? Color::lLA_PRE : Color::lRGBA_PRE;	//antialias in linear color space
+    Color r(0.0f, 0.0f, 0.0f, 0.0f, aaFormat);
+    for(int i=0;i<m_numSamples;i++)
+    {
+        Color d = readSample(x, y, i);
+        d.convert(aaFormat);
+        r += d;
+    }
+    r *= 1.0f/m_numSamples;
+    return r;
+}
+
+
+/**
+ *	\brief	Return a resolved sample in packed format.
+ *	\note	Further operations on color may require unpack.
+ */
+RI_INLINE RIuint32 Surface::FSAAResolvePacked(int x, int y) const
+{
+    if (m_numSamples == 1)
+        return readPackedSample(x, y, 0);
+
+    RI_ASSERT(false); /* Not implemented yet. */
+    return 0xffffffffu;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Drawable::Drawable(const Color::Descriptor& desc, int width, int height, int numSamples, int maskBits) :
+    m_referenceCount(0),
+    m_color(NULL),
+    m_mask(NULL)
+{
+    RI_ASSERT(width > 0 && height > 0 && numSamples > 0 && numSamples <= 32);
+    RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8);
+    m_color = RI_NEW(Surface, (desc, width, height, numSamples));	//throws bad_alloc
+    m_color->addReference();
+    if(maskBits)
+    {
+        VGImageFormat mf = VG_A_1;
+        if(maskBits == 4)
+            mf = VG_A_4;
+        else if(maskBits == 8)
+            mf = VG_A_8;
+        m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), width, height, numSamples));
+        m_mask->addReference();
+        m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Drawable::Drawable(Image* image, int maskBits) :
+    m_referenceCount(0),
+    m_color(NULL),
+    m_mask(NULL)
+{
+    RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8);
+    RI_ASSERT(image);
+    m_color = RI_NEW(Surface, (image));
+    m_color->addReference();
+    if(maskBits)
+    {
+        VGImageFormat mf = VG_A_1;
+        if(maskBits == 4)
+            mf = VG_A_4;
+        else if(maskBits == 8)
+            mf = VG_A_8;
+        m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), image->getWidth(), image->getHeight(), 1));
+        m_mask->addReference();
+        m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, image->getWidth(), image->getHeight());
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Drawable::Drawable(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data, int maskBits) :
+    m_referenceCount(0),
+    m_color(NULL),
+    m_mask(NULL)
+{
+    RI_ASSERT(width > 0 && height > 0);
+    RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8);
+    m_color = RI_NEW(Surface, (desc, width, height, stride, data));	//throws bad_alloc
+    m_color->addReference();
+    if(maskBits)
+    {
+        VGImageFormat mf = VG_A_1;
+        if(maskBits == 4)
+            mf = VG_A_4;
+        else if(maskBits == 8)
+            mf = VG_A_8;
+        m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), width, height, 1));
+        m_mask->addReference();
+        m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Drawable::~Drawable()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    if(!m_color->removeReference())
+        RI_DELETE(m_color);
+    if(m_mask)
+        if(!m_mask->removeReference())
+            RI_DELETE(m_mask);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Drawable::resize(VGContext* context, int newWidth, int newHeight)
+{
+    Surface* oldcolor = m_color;
+    Surface* oldmask = m_mask;
+    int oldWidth = m_color->getWidth();
+    int oldHeight = m_color->getHeight();
+
+    //TODO check that image is not a proxy
+    m_color = RI_NEW(Surface, (m_color->getDescriptor(), newWidth, newHeight, m_color->getNumSamples()));
+    m_color->addReference();
+    if(m_mask)
+    {
+        m_mask = RI_NEW(Surface, (m_mask->getDescriptor(), newWidth, newHeight, m_mask->getNumSamples()));
+        m_mask->addReference();
+    }
+
+    int wmin = RI_INT_MIN(newWidth,oldWidth);
+    int hmin = RI_INT_MIN(newHeight,oldHeight);
+    m_color->clear(Color(0.0f, 0.0f, 0.0f, 0.0f, getDescriptor().internalFormat), 0, 0, m_color->getWidth(), m_color->getHeight());
+    m_color->m_image->blit(context, oldcolor->m_image, 0, 0, 0, 0, wmin, hmin);
+    if(m_mask)
+    {
+        m_mask->clear(Color(1.0f, 1.0f, 1.0f, 1.0f, getDescriptor().internalFormat), 0, 0, m_mask->getWidth(), m_mask->getHeight());
+        m_mask->m_image->blit(context, oldmask->m_image, 0, 0, 0, 0, wmin, hmin);
+    }
+
+    if(!oldcolor->removeReference())
+        RI_DELETE(oldcolor);
+    if(oldmask)
+        if(!oldmask->removeReference())
+            RI_DELETE(oldmask);
+}
+
+#ifndef RI_COMPILE_LLVM_BYTECODE
+
+#endif /* RI_COMPILE_LLVM_BYTECODE */
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+//==============================================================================================
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riImage.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1593 @@
+#ifndef __RIIMAGE_H
+#define __RIIMAGE_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Color and Image classes.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _OPENVG_H
+#include "VG/openvg.h"
+#endif
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#include "sfAlphaRcp.h"
+#include "sfGammaLUT.h"
+#include "riUtils.h"
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+class VGContext;
+class DynamicBlitter;
+
+/*-------------------------------------------------------------------*//*!
+* \brief	A class representing rectangles.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Rectangle
+{
+public:
+    Rectangle() : x(0), y(0), width(0), height(0) {}
+    Rectangle(int rx, int ry, int rw, int rh) : x(rx), y(ry), width(rw), height(rh) {}
+    void		intersect(const Rectangle& r)
+    {
+        if(width >= 0 && r.width >= 0 && height >= 0 && r.height >= 0)
+        {
+            int x1 = RI_INT_MIN(RI_INT_ADDSATURATE(x, width), RI_INT_ADDSATURATE(r.x, r.width));
+            x = RI_INT_MAX(x, r.x);
+            width = RI_INT_MAX(x1 - x, 0);
+
+            int y1 = RI_INT_MIN(RI_INT_ADDSATURATE(y, height), RI_INT_ADDSATURATE(r.y, r.height));
+            y = RI_INT_MAX(y, r.y);
+            height = RI_INT_MAX(y1 - y, 0);
+        }
+        else
+        {
+            x = 0;
+            y = 0;
+            width = 0;
+            height = 0;
+        }
+    }
+    bool isEmpty() const { return width == 0 || height == 0; }
+
+    int			x;
+    int			y;
+    int			width;
+    int			height;
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief	A class representing color for processing and converting it
+*			to and from various surface formats.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Color
+{
+public:
+    enum FormatSize
+    {
+        SIZE_1      = 0,
+        SIZE_4      = 1,
+        SIZE_8      = 2,
+        SIZE_16     = 3,
+        SIZE_24     = 4,
+        SIZE_32     = 5
+    };
+
+    enum Shape
+    {
+        SHAPE_RGBA            = 0,
+        SHAPE_RGBX            = 1,
+        SHAPE_RGB             = 2,
+        SHAPE_LA              = 3,
+        SHAPE_L               = 4,
+        SHAPE_A               = 5,
+        SHAPE_ARGB            = 6,
+        SHAPE_XRGB            = 7,
+        SHAPE_AL              = 8,
+        SHAPE_BGRA            = 9,
+        SHAPE_BGRX            = 10,
+        SHAPE_BGR             = 11,
+        SHAPE_ABGR            = 12,
+        SHAPE_XBGR            = 13
+    };
+    enum InternalFormat
+    {
+        lRGBA			= 0,
+        sRGBA			= 1,
+        lRGBA_PRE		= 2,
+        sRGBA_PRE		= 3,
+        lLA				= 4,
+        sLA				= 5,
+        lLA_PRE			= 6,
+        sLA_PRE			= 7
+    };
+    enum FormatBits
+    {
+        NONLINEAR		= (1<<0),
+        PREMULTIPLIED	= (1<<1),
+        LUMINANCE		= (1<<2)
+    };
+    struct SmallDescriptor
+    {
+        RIuint32        toUint32()
+        {
+            RIuint32 ret = 0;
+            ret = (RIuint32)size;
+            ret |= (RIuint32)shape << 3;
+            ret |= (RIuint32)internalFormat << (3 + 4);
+            return ret;
+        }
+        FormatSize      size;
+        Shape           shape;
+        InternalFormat  internalFormat;
+    };
+    class Descriptor
+    {
+    public:
+        Descriptor() {};
+        RI_INLINE Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp, Shape shape);
+        RI_INLINE bool      isNonlinear() const                                 { return (internalFormat & NONLINEAR) ? true : false; }
+        RI_INLINE void      setNonlinear(bool nonlinear);
+        RI_INLINE bool      isPremultiplied() const                             { return (internalFormat & PREMULTIPLIED) ? true : false; }
+        RI_INLINE bool      isLuminance() const                                 { return (internalFormat & LUMINANCE) ? true : false; }
+        RI_INLINE bool      isAlphaOnly() const                                 { return (alphaBits && (redBits+greenBits+blueBits+luminanceBits) == 0) ? true : false; }
+        RI_INLINE bool      isBW() const { return isLuminance() && (luminanceBits == 1); }
+        RI_INLINE bool      hasAlpha() const { return alphaBits > 0; }
+        RI_INLINE bool      operator==(const Descriptor& rhs) const;
+        RI_INLINE bool      isShiftConversionToLower(const Descriptor& rhs) const;
+        RI_INLINE bool      isShiftConversion(const Descriptor& rhs) const;
+        RI_INLINE bool      isZeroConversion(const Descriptor& rhs) const;
+        RI_INLINE bool      maybeUnsafe() const { return internalFormat & PREMULTIPLIED ? true : false; };
+        static RI_INLINE RIuint32  crossConvertToLower(RIuint32 c, const Descriptor& src, const Descriptor& dst);
+        void                toSmallDescriptor(SmallDescriptor& smallDesc) const;
+        RI_INLINE RIuint32  toIndex() const;
+        static Descriptor   getDummyDescriptor();
+        Shape               getShape() const;
+
+        int				redBits;
+        int				redShift;
+        int				greenBits;
+        int				greenShift;
+        int				blueBits;
+        int				blueShift;
+        int				alphaBits;
+        int				alphaShift;
+        int				luminanceBits;
+        int				luminanceShift;
+        Shape           shape;
+        VGImageFormat   vgFormat; // \note Storage only
+        InternalFormat	internalFormat;
+        int				bitsPerPixel;
+        // Derived info:
+        int             bytesPerPixel;
+        int             maskBits;
+        int             maskShift;
+    };
+
+    RI_INLINE Color() : r(0.0f), g(0.0f), b(0.0f), a(0.0f), m_format(sRGBA_PRE)													{}
+    RI_INLINE Color(RIfloat cl, RIfloat ca, InternalFormat cs) : r(cl), g(cl), b(cl), a(ca), m_format(cs)							{ RI_ASSERT(cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); }
+    RI_INLINE Color(RIfloat cr, RIfloat cg, RIfloat cb, RIfloat ca, InternalFormat cs) : r(cr), g(cg), b(cb), a(ca), m_format(cs)	{ RI_ASSERT(cs == lRGBA || cs == sRGBA || cs == lRGBA_PRE || cs == sRGBA_PRE || cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); }
+    RI_INLINE Color(const Color& c) : r(c.r), g(c.g), b(c.b), a(c.a), m_format(c.m_format)									{}
+    RI_INLINE Color& operator=(const Color&c)										{ r = c.r; g = c.g; b = c.b; a = c.a; m_format = c.m_format; return *this; }
+    RI_INLINE void operator*=(RIfloat f)											{ r *= f; g *= f; b *= f; a*= f; }
+    RI_INLINE void operator+=(const Color& c1)										{ RI_ASSERT(m_format == c1.getInternalFormat()); r += c1.r; g += c1.g; b += c1.b; a += c1.a; }
+    RI_INLINE void operator-=(const Color& c1)										{ RI_ASSERT(m_format == c1.getInternalFormat()); r -= c1.r; g -= c1.g; b -= c1.b; a -= c1.a; }
+
+    void						set(RIfloat cl, RIfloat ca, InternalFormat cs)							{ RI_ASSERT(cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); r = cl; g = cl; b = cl; a = ca; m_format = cs; }
+    void						set(RIfloat cr, RIfloat cg, RIfloat cb, RIfloat ca, InternalFormat cs)	{ RI_ASSERT(cs == lRGBA || cs == sRGBA || cs == lRGBA_PRE || cs == sRGBA_PRE); r = cr; g = cg; b = cb; a = ca; m_format = cs; }
+    void						unpack(unsigned int inputData, const Descriptor& inputDesc);
+    unsigned int				pack(const Descriptor& outputDesc) const;
+    RI_INLINE InternalFormat	getInternalFormat() const							{ return m_format; }
+
+    //clamps nonpremultiplied colors and alpha to [0,1] range, and premultiplied alpha to [0,1], colors to [0,a]
+    void						clamp()												{ a = RI_CLAMP(a,0.0f,1.0f); RIfloat u = (m_format & PREMULTIPLIED) ? a : (RIfloat)1.0f; r = RI_CLAMP(r,0.0f,u); g = RI_CLAMP(g,0.0f,u); b = RI_CLAMP(b,0.0f,u); }
+    void						convert(InternalFormat outputFormat);
+    void						premultiply()										{ if(!(m_format & PREMULTIPLIED)) { r *= a; g *= a; b *= a; m_format = (InternalFormat)(m_format | PREMULTIPLIED); } }
+    void						unpremultiply()										{ if(m_format & PREMULTIPLIED) { RIfloat ooa = (a != 0.0f) ? 1.0f/a : (RIfloat)0.0f; r *= ooa; g *= ooa; b *= ooa; m_format = (InternalFormat)(m_format & ~PREMULTIPLIED); } }
+    void                        luminanceToRGB()                                    { if(m_format & LUMINANCE) { RI_ASSERT(r == g && g == b); m_format = (InternalFormat)(m_format & ~LUMINANCE); } }
+
+    bool                        isNonlinear() const                                 { return (m_format & NONLINEAR) ? true : false; }
+    bool                        isPremultiplied() const                             { return (m_format & PREMULTIPLIED) ? true : false; }
+    bool                        isLuminance() const                                 { return (m_format & LUMINANCE) ? true : false; }
+
+    RI_INLINE void              assertConsistency() const;
+
+    // \note Why are these in the color class instead of descriptor?
+    static VGImageFormat        descriptorToVGImageFormat(const Descriptor& desc);
+    RI_INLINE static Descriptor formatToDescriptorConst(VGImageFormat format);
+    static Descriptor			formatToDescriptor(VGImageFormat format);
+    static bool					isValidDescriptor(const Descriptor& desc);
+
+    RIfloat		r;
+    RIfloat		g;
+    RIfloat		b;
+    RIfloat		a;
+private:
+    InternalFormat	m_format;
+};
+
+RI_INLINE Color::Descriptor::Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp, Shape shape) :
+    redBits(dredBits),
+    redShift(dredShift),
+    greenBits(dgreenBits),
+    greenShift(dgreenShift),
+    blueBits(dblueBits),
+    blueShift(dblueShift),
+    alphaBits(dalphaBits),
+    alphaShift(dalphaShift),
+    luminanceBits(dluminanceBits),
+    luminanceShift(dluminanceShift),
+    shape(shape),
+    internalFormat(dinternalFormat),
+    bitsPerPixel(dbpp)
+{
+    bytesPerPixel = bitsPerPixel / 8;
+
+    if (alphaBits)
+    {
+        maskBits = alphaBits;
+        maskShift = alphaShift;
+    }
+    else if (!this->isLuminance())
+    {
+        maskBits = redBits;
+        maskShift = redShift;
+    }
+    else
+    {
+        maskBits = luminanceBits;
+        maskShift = luminanceShift;
+    }
+    RI_ASSERT(getShape() == shape);
+}
+
+RI_INLINE void Color::Descriptor::setNonlinear(bool nonlinear)
+{
+    if (nonlinear)
+        internalFormat = (InternalFormat)(((RIuint32)internalFormat)|NONLINEAR);
+    else
+        internalFormat = (InternalFormat)(((RIuint32)internalFormat)&(~NONLINEAR));
+}
+
+/**
+ * \brief	Creates a pixel format descriptor out of VGImageFormat
+ * \todo    The formats without alpha were non-premultiplied in the reference
+ *          implementation, but wouldn't it make more sense to consider them
+ *          premultiplied? This would make sense at least when blitting to
+ *          windows, etc., where the output color should have the alpha
+ *          multiplied "in".
+ */
+RI_INLINE Color::Descriptor Color::formatToDescriptorConst(VGImageFormat format)
+{
+    switch(format)
+    {
+    case VG_sRGBX_8888:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_RGBX);
+    case VG_sRGBA_8888:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::sRGBA, 32, SHAPE_RGBA);
+    case VG_sRGBA_8888_PRE:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::sRGBA_PRE, 32, SHAPE_RGBA);
+    case VG_sRGB_565:
+        return Color::Descriptor(5, 11, 6, 5, 5, 0, 0, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGB);
+    case VG_sRGBA_5551:
+        return Color::Descriptor(5, 11, 5, 6, 5, 1, 1, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGBA);
+    case VG_sRGBA_4444:
+        return Color::Descriptor(4, 12, 4, 8, 4, 4, 4, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGBA);
+    case VG_sL_8:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, Color::sLA, 8, SHAPE_L);
+    case VG_lRGBX_8888:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_RGBX);
+    case VG_lRGBA_8888:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::lRGBA, 32, SHAPE_RGBA);
+    case VG_lRGBA_8888_PRE:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::lRGBA_PRE, 32, SHAPE_RGBA);
+    case VG_lL_8:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, Color::lLA, 8, SHAPE_L);
+    case VG_A_8:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 8, 0, 0, 0, Color::lRGBA, 8, SHAPE_A);
+    case VG_BW_1:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, Color::lLA, 1, SHAPE_L);
+    case VG_A_1:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, Color::lRGBA, 1, SHAPE_A);
+    case VG_A_4:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 4, 0, 0, 0, Color::lRGBA, 4, SHAPE_A);
+
+  /* {A,X}RGB channel ordering */
+    case VG_sXRGB_8888:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_XRGB);
+    case VG_sARGB_8888:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::sRGBA, 32, SHAPE_ARGB);
+    case VG_sARGB_8888_PRE:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::sRGBA_PRE, 32, SHAPE_ARGB);
+    case VG_sARGB_1555:
+        return Color::Descriptor(5, 10, 5, 5, 5, 0, 1, 15, 0, 0, Color::sRGBA, 16, SHAPE_ARGB);
+    case VG_sARGB_4444:
+        return Color::Descriptor(4, 8, 4, 4, 4, 0, 4, 12, 0, 0, Color::sRGBA, 16, SHAPE_ARGB);
+    case VG_lXRGB_8888:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_XRGB);
+    case VG_lARGB_8888:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::lRGBA, 32, SHAPE_ARGB);
+    case VG_lARGB_8888_PRE:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::lRGBA_PRE, 32, SHAPE_ARGB);
+
+  /* BGR{A,X} channel ordering */
+    case VG_sBGRX_8888:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_BGRX);
+    case VG_sBGRA_8888:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::sRGBA, 32, SHAPE_BGRA);
+    case VG_sBGRA_8888_PRE:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::sRGBA_PRE, 32, SHAPE_BGRA);
+    case VG_sBGR_565:
+        return Color::Descriptor(5, 0, 6, 5, 5, 11, 0, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGR);
+    case VG_sBGRA_5551:
+        return Color::Descriptor(5, 1, 5, 6, 5, 11, 1, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGRA);
+    case VG_sBGRA_4444:
+        return Color::Descriptor(4, 4, 4, 8, 4, 12, 4, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGRA);
+    case VG_lBGRX_8888:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_BGRX);
+    case VG_lBGRA_8888:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::lRGBA, 32, SHAPE_BGRA);
+    case VG_lBGRA_8888_PRE:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::lRGBA_PRE, 32, SHAPE_BGRA);
+
+  /* {A,X}BGR channel ordering */
+    case VG_sXBGR_8888:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_XBGR);
+    case VG_sABGR_8888:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::sRGBA, 32, SHAPE_ABGR);
+    case VG_sABGR_8888_PRE:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::sRGBA_PRE, 32, SHAPE_ABGR);
+    case VG_sABGR_1555:
+        return Color::Descriptor(5, 0, 5, 5, 5, 10, 1, 15, 0, 0, Color::sRGBA, 16, SHAPE_ABGR);
+    case VG_sABGR_4444:
+        return Color::Descriptor(4, 0, 4, 4, 4, 8, 4, 12, 0, 0, Color::sRGBA, 16, SHAPE_ABGR);
+    case VG_lXBGR_8888:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_XBGR);
+    case VG_lABGR_8888:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::lRGBA, 32, SHAPE_ABGR);
+    default:
+    //case VG_lABGR_8888_PRE:
+        RI_ASSERT(format == VG_lABGR_8888_PRE);
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::lRGBA_PRE, 32, SHAPE_ABGR);
+    }
+}
+
+RI_INLINE bool 	Color::Descriptor::operator==(const Descriptor& rhs) const
+{
+    return memcmp(this, &rhs, sizeof(Descriptor)) ? false : true;
+}
+
+RI_INLINE bool Color::Descriptor::isZeroConversion(const Descriptor& rhs) const
+{
+    return (shape == rhs.shape) &&
+        (internalFormat == rhs.internalFormat) &&
+        (redBits == rhs.redBits) &&
+        (greenBits == rhs.greenBits) &&
+        (blueBits == rhs.blueBits) &&
+        (alphaBits == rhs.alphaBits) &&
+        (luminanceBits == rhs.luminanceBits);
+}
+
+RI_INLINE bool Color::Descriptor::isShiftConversion(const Descriptor& rhs) const
+{
+    // \note BW conversion is always forced to full at the moment.
+    if (isBW() != rhs.isBW()) 
+        return false;
+
+    return (isPremultiplied() == rhs.isPremultiplied())
+            && (isNonlinear() == rhs.isNonlinear())
+            && (isLuminance() == rhs.isLuminance());
+}
+
+RI_INLINE bool Color::Descriptor::isShiftConversionToLower(const Descriptor& rhs) const
+{
+    // \note BW conversion is always forced to full at the moment.
+    if (isBW() != rhs.isBW()) 
+        return false;
+    // \note Mask bits are not checked because they are derived information.
+    return (isShiftConversion(rhs)
+            && (rhs.redBits <= redBits)
+            && (rhs.greenBits <= greenBits)
+            && (rhs.blueBits <= blueBits)
+            && (rhs.alphaBits <= alphaBits)
+            && (rhs.luminanceBits <= luminanceBits));
+
+}
+
+/**
+ * \brief   In-place conversion of packed color to lower bit-depth
+ * \param   c   Input packed color
+ * \param   src Source color descriptor
+ * \param   dst Destination color descriptor
+ */
+RI_INLINE RIuint32  Color::Descriptor::crossConvertToLower(RIuint32 c, const Descriptor& src, const Descriptor& dst)
+{
+    RIuint32 r = 0;
+
+    RI_ASSERT(dst.redBits <= src.redBits);
+    RI_ASSERT(dst.greenBits <= src.greenBits);
+    RI_ASSERT(dst.blueBits <= src.blueBits);
+    RI_ASSERT(dst.alphaBits <= src.alphaBits);
+
+    if (src.isLuminance())
+    {
+        RI_ASSERT(dst.isLuminance());
+        r = ((c >> (src.luminanceShift + src.luminanceBits - dst.luminanceBits)) & ((1u<<dst.luminanceBits)-1)) << dst.luminanceShift;
+    } else
+    {
+        r = ((c >> (src.redShift + src.redBits - dst.redBits)) & ((1u<<dst.redBits)-1)) << dst.redShift;
+        r |= ((c >> (src.greenShift + src.greenBits - dst.greenBits)) & ((1u<<dst.greenBits)-1)) << dst.greenShift;
+        r |= ((c >> (src.blueShift + src.blueBits - dst.blueBits)) & ((1u<<dst.blueBits)-1)) << dst.blueShift;
+    }
+
+    if (src.hasAlpha())
+    {
+        if (dst.hasAlpha())
+            r |= ((c >> (src.alphaShift + src.alphaBits - dst.alphaBits)) & ((1u<<dst.alphaBits)-1)) << dst.alphaShift;
+        else
+        {
+            // Make sure that the alpha is applied to the color if doing only a shift conversion.
+            RI_ASSERT(src.isPremultiplied() == dst.isPremultiplied());
+        }
+    }
+
+    return r;
+}
+
+RI_INLINE RIuint32 Color::Descriptor::toIndex() const
+{
+    SmallDescriptor smallDesc;
+    toSmallDescriptor(smallDesc);
+    return smallDesc.toUint32();
+}
+
+RI_INLINE Color operator*(const Color& c, RIfloat f)			{ return Color(c.r*f, c.g*f, c.b*f, c.a*f, c.getInternalFormat()); }
+RI_INLINE Color operator*(RIfloat f, const Color& c)			{ return Color(c.r*f, c.g*f, c.b*f, c.a*f, c.getInternalFormat()); }
+RI_INLINE Color operator+(const Color& c0, const Color& c1)		{ RI_ASSERT(c0.getInternalFormat() == c1.getInternalFormat()); return Color(c0.r+c1.r, c0.g+c1.g, c0.b+c1.b, c0.a+c1.a, c0.getInternalFormat()); }
+RI_INLINE Color operator-(const Color& c0, const Color& c1)		{ RI_ASSERT(c0.getInternalFormat() == c1.getInternalFormat()); return Color(c0.r-c1.r, c0.g-c1.g, c0.b-c1.b, c0.a-c1.a, c0.getInternalFormat()); }
+RI_INLINE void  Color::assertConsistency() const
+{
+    RI_ASSERT(r >= 0.0f && r <= 1.0f);
+    RI_ASSERT(g >= 0.0f && g <= 1.0f);
+    RI_ASSERT(b >= 0.0f && b <= 1.0f);
+    RI_ASSERT(a >= 0.0f && a <= 1.0f);
+    RI_ASSERT(!isPremultiplied() || (r <= a && g <= a && b <= a));	//premultiplied colors must have color channels less than or equal to alpha
+    RI_ASSERT((isLuminance() && r == g && r == b) || !isLuminance());	//if luminance, r=g=b
+}
+
+class IntegerColor
+{
+public:
+
+    IntegerColor() {r = g = b = a = 0;}
+    IntegerColor(const Color& color);
+
+    RI_INLINE           IntegerColor(RIuint32 packedColor, const Color::Descriptor& desc) { fromPackedColor(packedColor, desc); }
+    RI_INLINE           IntegerColor(RIuint32 cr, RIuint32 cg, RIuint32 cb, RIuint32 ca) { r = cr; g = cg; b = cb; a = ca; }
+    RI_INLINE void      asFixedPoint(const Color& color);
+    RI_INLINE void      fromPackedColor(RIuint32 packedColor, const Color::Descriptor& desc);
+    RI_INLINE void      expandColor(const Color::Descriptor& desc);
+    RI_INLINE void      truncateColor(const Color::Descriptor& desc);
+    RI_INLINE void      clampToAlpha();
+    RI_INLINE RIuint32  getPackedColor(const Color::Descriptor& desc) const;
+    RI_INLINE RIuint32  getPackedMaskColor(const Color::Descriptor& desc) const;
+    RI_INLINE void      premultiply(bool luminance = false);
+    RI_INLINE void      unpremultiply(bool luminance = false);
+    //RI_INLINE void      linearToGamma(bool luminance, bool premultipliedIn, bool premultipliedOut);
+    RI_INLINE void      linearToGamma(bool luminance = false);
+    RI_INLINE void      gammaToLinear(bool luminance = false);
+    RI_INLINE void      fromPackedMask(RIuint32 packedColor, const Color::Descriptor& desc);
+    RI_INLINE void      expandMask(const Color::Descriptor& desc);
+    RI_INLINE void      truncateMask(const Color::Descriptor& desc);
+    RI_INLINE void      fullLuminanceToRGB(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut);
+    RI_INLINE void      fullRGBToLuminance(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut);
+    RI_INLINE void      luminanceToRGB();
+    RI_INLINE void      rgbToLuminance();
+    RI_INLINE void      convertToFrom(const Color::Descriptor& dst, const Color::Descriptor& src, bool srcIsMask);
+
+    RI_INLINE static IntegerColor linearBlendNS(const IntegerColor& c0, const IntegerColor& c1, int k);
+
+    RIuint32 r;
+    RIuint32 g;
+    RIuint32 b;
+    RIuint32 a;
+
+};
+
+/**
+ * \brief   Blend two colors linearly. The output will not be scaled into original range.
+ * \param   k   Blend coefficient. Must be [0..255] for correct results.
+ * \todo    Parameterize against bits in k? To perform well, that setup must be compiled rt.
+ */
+RI_INLINE IntegerColor IntegerColor::linearBlendNS(const IntegerColor& c0, const IntegerColor& c1, int k)
+{
+    RI_ASSERT(k >= 0 && k <= 255);
+    IntegerColor ret;
+    RIuint32 ik = 255 - k;
+
+    ret.r = ik * c0.r + k * c1.r;
+    ret.g = ik * c0.g + k * c1.g;
+    ret.b = ik * c0.b + k * c1.b;
+    ret.a = ik * c0.a + k * c1.a;
+
+    return ret;
+}
+
+/**
+ *	\note 	Assumes that each individual component is in proper range (usually indicated by the
+ *			corresponding shift).
+ */
+RI_INLINE RIuint32 packRGBAInteger(RIuint32 cr, int rs, RIuint32 cg, int gs, RIuint32 cb, int bs, RIuint32 ca, int as)
+{
+    return (cr << rs) | (cg << gs) | (cb << bs) | (ca << as);
+}
+
+/**
+ * \brief   Packs a color into RIuint32.
+ * \note    The color must have been truncated to contain correct amount of bits per channel
+ * \note    This function is efficient only if runtime compilation is used.
+ */
+RI_INLINE RIuint32 IntegerColor::getPackedColor(const Color::Descriptor& desc) const
+{
+    RIuint32 res = 0;
+    if (desc.luminanceBits)
+    {
+        RI_ASSERT(desc.redBits == 0 && desc.greenBits == 0 && desc.blueBits == 0);
+        RI_ASSERT(r < (1u<<desc.luminanceBits));
+        res = r << desc.luminanceShift;
+    }
+    else if (desc.redBits)
+    {
+        RI_ASSERT(r < (1u<<desc.redBits));
+        res = r << desc.redShift;
+        if (desc.greenBits)
+        {
+            RI_ASSERT(desc.blueBits);
+            RI_ASSERT(g < (1u<<desc.greenBits));
+            RI_ASSERT(b < (1u<<desc.blueBits));
+            res |= g << desc.greenShift;
+            res |= b << desc.blueShift;
+        }
+    }
+
+    if (desc.alphaBits)
+    {
+        RI_ASSERT(a < (1u<<desc.alphaBits));
+        res |= a << desc.alphaShift;
+    }
+
+    return res;
+}
+
+RI_INLINE RIuint32 IntegerColor::getPackedMaskColor(const Color::Descriptor& desc) const
+{
+    if (desc.alphaBits)
+        return packRGBAInteger(0, desc.redShift, 0, desc.greenShift, 0, desc.blueShift, a, desc.alphaShift);
+    else if(desc.redBits)
+        return packRGBAInteger(a, desc.redShift, 0, desc.greenShift, 0, desc.blueShift, 0, desc.alphaShift);
+    else
+    {
+        RI_ASSERT(desc.luminanceBits);
+        return packRGBAInteger(a, desc.luminanceBits, 0, desc.greenShift, 0, desc.blueShift, 0, desc.alphaShift);
+    }
+
+}
+
+RI_INLINE void IntegerColor::premultiply(bool luminance)
+{
+    // \todo Check the round!!!
+    RIuint32 fxa = a + (a>>7);
+    r = (r * fxa); r = (r + (1<<7))>>8;
+
+    if (!luminance)
+    {
+        g = (g * fxa); g = (g + (1<<7))>>8;
+        b = (b * fxa); b = (b + (1<<7))>>8;
+    }
+}
+
+RI_INLINE void IntegerColor::unpremultiply(bool luminance)
+{
+    RI_ASSERT(a <= 255);
+
+    RIuint32 rcp = sc_alphaRcp[a];
+    r = (r * rcp) >> 8;
+
+    if (!luminance)
+    {
+        g = (g * rcp) >> 8;
+        b = (b * rcp) >> 8;
+    }
+}
+
+RI_INLINE void IntegerColor::linearToGamma(bool luminance)
+{
+    RI_ASSERT(r <= 255 && g <= 255 && b <= 255 && a <= 255);
+
+    r = sc_lRGB_to_sRGB[r];
+
+    if (!luminance)
+    {
+        g = sc_lRGB_to_sRGB[g];
+        b = sc_lRGB_to_sRGB[b];
+    }
+
+    // \note Alpha is _not_ converted and it must be considered linear always
+}
+
+RI_INLINE void IntegerColor::gammaToLinear(bool luminance)
+{
+    RI_ASSERT(r <= 255 && g <= 255 && b <= 255 && a <= 255);
+
+    r = sc_sRGB_to_lRGB[r];
+    if (!luminance)
+    {
+        g = sc_sRGB_to_lRGB[g];
+        b = sc_sRGB_to_lRGB[b];
+    }
+
+    // \note Alpha is _not_ converted and it must be considered linear always
+}
+
+RI_INLINE void IntegerColor::asFixedPoint(const Color& color)
+{
+    r = (RIuint32)(color.r * 256.0f + 0.5f);
+    g = (RIuint32)(color.g * 256.0f + 0.5f);
+    b = (RIuint32)(color.b * 256.0f + 0.5f);
+    a = (RIuint32)(color.a * 256.0f + 0.5f);
+}
+
+RI_INLINE void IntegerColor::fromPackedColor(RIuint32 packedColor, const Color::Descriptor& desc)
+{
+    /* \note Expand MUST be done separately! */
+
+    if (desc.luminanceBits)
+    {
+        r = (packedColor >> desc.luminanceShift) & ((1u << desc.luminanceBits)-1);
+        g = b = r;
+    }
+    else
+    {
+        r = (packedColor >> desc.redShift) & ((1u << desc.redBits)-1);
+        g = (packedColor >> desc.greenShift) & ((1u << desc.greenBits)-1);
+        b = (packedColor >> desc.blueShift) & ((1u << desc.blueBits)-1);
+    }
+
+    if (desc.alphaBits)
+        a = (packedColor >> desc.alphaShift) & ((1u << desc.alphaBits)-1);
+    else
+        a = 255;
+}
+
+/**
+ * \brief   Expand color to larger (or same) bit depth as in the OpenVG specification.
+ * \todo    1 and 2 bpp!
+ */
+RI_INLINE RIuint32 expandComponent(RIuint32 c, RIuint32 srcBits)
+{
+    const RIuint32 destBits = 8;
+    RI_ASSERT(destBits >= srcBits);
+
+    if (!srcBits) return 0;
+
+    if (srcBits == destBits) return c;
+
+    switch (srcBits)
+    {
+    case 6:
+        return (c << 2) | (c >> 4);
+    case 5:
+        return (c << 3) | (c >> 2);
+    case 4:
+        return (c << 4) | c;
+    case 2:
+        return c | (c << 2) | (c << 4) | (c << 6);
+    default:
+        RI_ASSERT(srcBits == 1);
+        if (c) return 0xff;
+        return 0;
+    }
+}
+
+/**
+ * \brief   Expands integer color representation to internal format (8-bits per component atm.).
+ * \todo    Do nothing when bits == 8.
+ */
+RI_INLINE void IntegerColor::expandColor(const Color::Descriptor& desc)
+{
+    if (desc.luminanceBits)
+    {
+        r = expandComponent(r, desc.luminanceBits);
+        g = b = r;
+        a = 255;
+    } else
+    {
+        if (desc.redBits < 8 || desc.luminanceBits < 8)
+            r = expandComponent(r, desc.redBits);
+        if (desc.greenBits < 8)
+            g = expandComponent(g, desc.greenBits);
+        if (desc.blueBits < 8)
+            b = expandComponent(b, desc.blueBits);
+    }
+
+    if (desc.alphaBits && desc.alphaBits < 8)
+        a = expandComponent(a, desc.alphaBits);
+
+    if (desc.isAlphaOnly())
+    {
+        if (!desc.isPremultiplied())
+            r = g = b = 255;
+        else
+            r = g = b = a;
+    }
+}
+
+/**
+ * \brief   Convert IntegerColor components to destination bitdepth (from internal) by
+ *          shifting. Rounding does not take place.
+ */
+RI_INLINE void IntegerColor::truncateColor(const Color::Descriptor& desc)
+{
+    if (desc.luminanceBits)
+    {
+        RI_ASSERT(desc.redBits == 0 && desc.greenBits == 0 && desc.blueBits == 0);
+        if (desc.luminanceBits == 1)
+        {
+            // Round the 1-bit case a bit better?
+            r = (r + 128)>>8;
+        } else if (desc.luminanceBits < 8)
+            r >>= (8 - desc.luminanceBits);
+    }
+    else
+    {
+        if (desc.redBits < 8)
+            r >>= (8 - desc.redBits);
+        if (desc.greenBits < 8)
+            g >>= (8 - desc.greenBits);
+        if (desc.blueBits < 8)
+            b >>= (8 - desc.blueBits);
+    }
+
+    if (desc.alphaBits < 8)
+    {
+        if (desc.alphaBits == 1)
+            a = (a+128)>>8;
+        else
+            a >>= (8 - desc.alphaBits);
+    }
+}
+
+RI_INLINE void IntegerColor::truncateMask(const Color::Descriptor& desc)
+{
+    if (desc.redBits < 8 || desc.luminanceBits < 8)
+        r >>= (8 - desc.maskBits);
+    if (desc.greenBits < 8)
+        g >>= (8 - desc.maskBits);
+    if (desc.blueBits < 8)
+        b >>= (8 - desc.maskBits);
+    if (desc.alphaBits < 8)
+        a >>= (8 - desc.maskBits);
+}
+
+RI_INLINE void IntegerColor::clampToAlpha()
+{
+    if (r > a) r = a;
+    if (g > a) g = a;
+    if (b > a) b = a;
+}
+
+RI_INLINE void IntegerColor::fromPackedMask(RIuint32 packedMask, const Color::Descriptor& desc)
+{
+    RI_ASSERT(desc.maskBits);
+    a = (packedMask >> desc.maskShift) & ((1u << desc.maskBits)-1);
+}
+
+RI_INLINE void IntegerColor::expandMask(const Color::Descriptor& desc)
+{
+    a = expandComponent(a, desc.maskBits);
+    r = g = b = a;
+}
+
+#if 0
+RI_INLINE void IntegerColor::truncateMask(const Color::Descriptor& desc)
+{
+    a >>= (8 - desc.maskBits);
+}
+#endif
+
+RI_INLINE void IntegerColor::fullLuminanceToRGB(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut)
+{
+    if (premultipliedIn)
+        unpremultiply();
+
+    luminanceToRGB();
+
+    if (gammaIn != gammaOut)
+    {
+        if (gammaIn)
+            gammaToLinear();
+        else
+            linearToGamma();
+    }
+
+    if (premultipliedOut)
+        premultiply();
+
+}
+
+RI_INLINE void IntegerColor::fullRGBToLuminance(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut)
+{
+    if (premultipliedIn)
+        unpremultiply();
+
+    if (gammaIn)
+        gammaToLinear();
+
+    rgbToLuminance();
+
+    if (gammaOut)
+        linearToGamma();
+
+    if (premultipliedOut)
+        premultiply();
+
+}
+
+
+// \todo This should not be needed (only r-channel is used anyway)
+RI_INLINE void IntegerColor::luminanceToRGB()
+{
+    g = b = r;
+}
+
+// \todo Only write to R!
+RI_INLINE void IntegerColor::rgbToLuminance()
+{
+    enum { Rx = 871, Gx = 2929, Bx = 296, Bits = 12 };
+    //enum { Rx = 54, Gx = 183, Bx = 18, Bits = 8 };
+    RIuint32 l = Rx * r + Gx * g + Bx * b;
+    r = g = b = l >> Bits;
+}
+
+#if 0
+RI_INLINE void IntegerColor::convertFromInternal(const Color::Descriptor& dst)
+{
+}
+#endif
+
+/**
+ * \brief   Convert color from one format to another using integer operations.
+ * \note    Currently expands the color to intermediate format first (8 bits
+ *          per component.
+ */
+RI_INLINE void IntegerColor::convertToFrom(const Color::Descriptor& dst, const Color::Descriptor& src, bool srcIsMask)
+{
+    if (src.isZeroConversion(dst))
+        return;
+
+    if (src.isShiftConversionToLower(dst))
+    {
+        if (dst.luminanceBits)
+        {
+            if (dst.luminanceBits == 1)
+            {
+                RI_ASSERT(src.luminanceBits == 8);
+                r = (r + 128)>>8;
+            }
+            else
+                r = r >> (src.luminanceBits - dst.luminanceBits);
+        } else
+        {
+            r = r >> (src.redBits - dst.redBits);
+            g = g >> (src.greenBits - dst.greenBits);
+            b = b >> (src.blueBits - dst.blueBits);
+        }
+        if (dst.alphaBits)
+        {
+                //a = (a+128)>>8;
+            if (dst.alphaBits == 1)
+                a = (a+(1<<(src.alphaBits-1)))>>src.alphaBits;
+            else
+                a = a >> (src.alphaBits - dst.alphaBits);
+        }
+
+        return;
+    }
+
+    if (!srcIsMask)
+        expandColor(src);
+    else
+        expandMask(src);
+
+
+    if (dst.isLuminance() != src.isLuminance())
+    {
+        if (src.isLuminance())
+            fullLuminanceToRGB(src.isPremultiplied(), src.isNonlinear(), dst.isPremultiplied(), dst.isNonlinear());
+        else
+            fullRGBToLuminance(src.isPremultiplied(), src.isNonlinear(), dst.isPremultiplied(), dst.isNonlinear());
+    }
+    else if (dst.isNonlinear() != src.isNonlinear())
+    {
+        // No luminance/rgb change.
+        // Change of gamma requires unpremultiplication:
+        if (src.isPremultiplied() && !(src.isAlphaOnly()))
+            unpremultiply();
+
+        if (src.isNonlinear())
+            gammaToLinear(src.isLuminance());
+        else
+            linearToGamma(src.isLuminance());
+
+        if (dst.isPremultiplied() && !(dst.isAlphaOnly()))
+            premultiply();
+    }
+    else
+    if ((dst.isPremultiplied() != src.isPremultiplied()) && !(dst.isAlphaOnly() || dst.isAlphaOnly()))
+    {
+        // \todo Make sure non-alpha formats are properly handled.
+        if (src.isPremultiplied())
+            unpremultiply(dst.isLuminance());
+        else
+            premultiply(dst.isLuminance());
+    }
+
+    truncateColor(dst);
+}
+
+//==============================================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Storage and operations for VGImage.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Surface;
+class Image
+{
+public:
+    Image(const Color::Descriptor& desc, int width, int height, VGbitfield allowedQuality);	//throws bad_alloc
+    //use data from a memory buffer. NOTE: data is not copied, so it is user's responsibility to make sure the data remains valid while the Image is in use.
+    Image(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data);	//throws bad_alloc
+    //child image constructor
+    Image(Image* parent, int x, int y, int width, int height);	//throws bad_alloc
+    ~Image();
+
+    const Color::Descriptor&	getDescriptor() const		{ return m_desc; }
+    int					getWidth() const					{ return m_width; }
+    int					getHeight() const					{ return m_height; }
+    int					getStride() const					{ return m_stride; }
+    Image*				getParent() const					{ return m_parent; }
+    VGbitfield			getAllowedQuality() const			{ return m_allowedQuality; }
+    void				addInUse()							{ m_inUse++; }
+    void				removeInUse()						{ RI_ASSERT(m_inUse > 0); m_inUse--; }
+    int					isInUse() const						{ return m_inUse; }
+    RIuint8*			getData() const						{ return m_data; }
+    void				addReference()						{ m_referenceCount++; }
+    int					removeReference()					{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+    bool				overlaps(const Image* src) const;
+    void                setUnsafe(bool unsafe) { if (unsafe && m_desc.maybeUnsafe()) m_unsafeData = unsafe; else m_unsafeData = false; }
+    bool                isUnsafe() const { return m_unsafeData; }
+
+    void				clear(const Color& clearColor, int x, int y, int w, int h);
+    void				blit(VGContext* context, const Image* src, int sx, int sy, int dx, int dy, int w, int h, Array<Rectangle>* scissors = NULL, bool dither = false);	//throws bad_alloc
+
+    RI_INLINE static const void* incrementPointer(const void* ptr, int bpp, RIint32 x);
+    RI_INLINE static void* calculateAddress(const void* basePtr, int bpp, int x, int y, int stride);
+
+    static RI_INLINE RIuint32   readPackedPixelFromAddress(const void *ptr, int bpp, int x);
+    static RI_INLINE void       writePackedPixelToAddress(void* ptr, int bpp, int x, RIuint32 packedColor);
+
+    RI_INLINE RIuint32 			readPackedPixel(int x, int y) const;
+    Color				readPixel(int x, int y) const;
+    RI_INLINE void      writePackedPixelToAddress(void* ptr, int x, RIuint32 packedColor);
+    void				writePackedPixel(int x, int y, RIuint32 packedColor);
+    void				writePixel(int x, int y, const Color& c);
+
+    void                fillPacked(RIuint32 packedColor);
+
+    static RI_INLINE void   fillPackedPixels(void* data, int bpp, int x, int y, int stride, int nPixels, RIuint32 packedColor);
+    RI_INLINE void		    fillPackedPixels(int x, int y, int nPixels, RIuint32 packedColor);
+    RI_INLINE void          fillPackedRectangle(int x0, int y0, int width, int height, RIuint32 packedColor);
+
+    void				writeFilteredPixel(int x, int y, const Color& c, VGbitfield channelMask);
+
+    RIfloat				readMaskPixel(int x, int y) const;		//can read any image format
+    void				writeMaskPixel(int x, int y, RIfloat m);	//can write only to VG_A_x
+
+    Color				resample(RIfloat x, RIfloat y, const Matrix3x3& surfaceToImage, VGImageQuality quality, VGTilingMode tilingMode, const Color& tileFillColor);	//throws bad_alloc
+    void				makeMipMaps();	//throws bad_alloc
+
+    void				colorMatrix(const Image& src, const RIfloat* matrix, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				convolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernel, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				separableConvolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernelX, const RIint16* kernelY, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				gaussianBlur(const Image& src, RIfloat stdDeviationX, RIfloat stdDeviationY, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				lookup(const Image& src, const RIuint8 * redLUT, const RIuint8 * greenLUT, const RIuint8 * blueLUT, const RIuint8 * alphaLUT, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				lookupSingle(const Image& src, const RIuint32 * lookupTable, VGImageChannel sourceChannel, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+
+    RI_INLINE static int descriptorToStride(const Color::Descriptor& desc, int width) { return (width*desc.bitsPerPixel+7)/8; };
+
+    void getStorageOffset(int& x, int& y) const { x = m_storageOffsetX; y = m_storageOffsetY; }
+
+private:
+    Image(const Image&);					//!< Not allowed.
+    void operator=(const Image&);			//!< Not allowed.
+
+#if defined(RI_DEBUG)
+    bool                ptrInImage(const void* ptr) const;
+#endif
+    Color				readTexel(int u, int v, int level, VGTilingMode tilingMode, const Color& tileFillColor) const;
+
+    Color::Descriptor	m_desc;
+    int					m_width;
+    int					m_height;
+    VGbitfield			m_allowedQuality;
+    int					m_inUse;
+    int					m_stride;
+    RIuint8*			m_data;
+    int					m_referenceCount;
+    bool				m_ownsData;
+    Image*				m_parent;
+    int					m_storageOffsetX;
+    int					m_storageOffsetY;
+    bool                m_unsafeData; // Data may contain incorrect pixel data
+
+#ifndef RI_COMPILE_LLVM_BYTECODE
+
+#endif /* RI_COMPILE_LLVM_BYTECODE */
+};
+
+#if defined(RI_DEBUG)
+RI_INLINE bool Image::ptrInImage(const void* ptr) const
+{
+    RIuint8* p = (RIuint8*)ptr;
+
+    if (p < m_data) return false;
+    if (p >= (m_data + m_height * m_stride)) return false;
+    return true;
+}
+#endif
+
+RI_INLINE const void* Image::incrementPointer(const void* ptr, int bpp, int x)
+{
+    if (bpp >= 8)
+        return (((RIuint8*)ptr) + (bpp >> 3));
+    // Increment the pointer only when the byte is actually about to change.
+    int mask;
+    if (bpp == 4)
+        mask = 1;
+    else if (bpp == 2)
+        mask = 3;
+    else
+        mask = 7;
+    if ((x & mask) == mask)
+        return ((RIuint8*)ptr + 1);
+    return ptr;
+}
+
+RI_INLINE void* Image::calculateAddress(const void* basePtr, int bpp, int x, int y, int stride)
+{
+    if (bpp >= 8)
+    {
+        return (void*)((RIuint8*)basePtr + y * stride + x * (bpp >> 3));
+    } else
+    {
+        // 4, 2, or 1 bits per pixel
+        RI_ASSERT(bpp == 4 || bpp == 2 || bpp == 1);
+        return (void*)((RIuint8*)basePtr + y * stride + ((x * bpp) >> 3));
+    }
+}
+
+RI_INLINE RIuint32 Image::readPackedPixel(int x, int y) const
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(x >= 0 && x < m_width);
+    RI_ASSERT(y >= 0 && y < m_height);
+    RI_ASSERT(m_referenceCount > 0);
+
+    RIuint32 p = 0;
+
+    void* ptr = Image::calculateAddress(m_data, m_desc.bitsPerPixel, x+m_storageOffsetX, y+m_storageOffsetY, m_stride);
+    p = readPackedPixelFromAddress(ptr, m_desc.bitsPerPixel, x+m_storageOffsetX);
+
+    return p;
+}
+
+
+RI_INLINE void Image::writePackedPixelToAddress(void* ptr, int bpp, int x, RIuint32 packedColor)
+{
+    // \note packedColor must contain the whole data (including < 8 bpp data)?
+    switch(bpp)
+    {
+    case 32:
+    {
+        RIuint32* s = ((RIuint32*)ptr);
+        *s = (RIuint32)packedColor;
+        break;
+    }
+
+    case 16:
+    {
+        RIuint16* s = ((RIuint16*)ptr);
+        *s = (RIuint16)packedColor;
+        break;
+    }
+
+    case 8:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        *s = (RIuint8)packedColor;
+        break;
+    }
+    case 4:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+        break;
+    }
+
+    case 2:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1))));
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(bpp == 1);
+        RIuint8* s = ((RIuint8*)ptr);
+        *s = (RIuint8)((packedColor << (x&7)) | ((unsigned int)*s & ~(0x1 << (x&7))));
+        break;
+    }
+    }
+    // m_mipmapsValid = false; // \note Will never do this, must be handled outside this class somehow!
+}
+
+/**
+ * \brief   Write packed pixel into address.
+ * \param   x   Which x-coordinate (starting from the start of the scanline
+ *              pointed to) is addressed? This is only required for formats
+ *              that have less than 8 bpp.
+ */
+void Image::writePackedPixelToAddress(void* address, int x, RIuint32 packedColor)
+{
+    writePackedPixelToAddress(address, m_desc.bitsPerPixel, x, packedColor);
+}
+
+/**
+ * \brief   Read a packed pixel from a given address. Notice the use of param x!
+ * \param   x   Check which part of byte to return if bpp < 8
+ */
+RI_INLINE RIuint32 Image::readPackedPixelFromAddress(const void *ptr, int bpp, int x)
+{
+    switch(bpp)
+    {
+    case 32:
+    {
+        RIuint32* s = (RIuint32*)ptr;
+        return *s;
+    }
+
+    case 16:
+    {
+        RIuint16* s = (RIuint16*)ptr;
+        return (RIuint32)*s;
+    }
+
+    case 8:
+    {
+        RIuint8* s = (RIuint8*)ptr;
+        return (RIuint32)*s;
+    }
+    case 4:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        return (RIuint32)(*s >> ((x&1)<<2)) & 0xf;
+    }
+
+    case 2:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        return (RIuint32)(*s >> ((x&3)<<1)) & 0x3;
+    }
+
+    default:
+    {
+        RI_ASSERT(bpp == 1);
+        RIuint8* s = ((RIuint8*)ptr);
+        return (RIuint32)(*s >> (x&7)) & 0x1;
+    }
+    }
+}
+
+RI_INLINE void Image::writePackedPixel(int x, int y, RIuint32 packedColor)
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(x >= 0 && x < m_width);
+    RI_ASSERT(y >= 0 && y < m_height);
+    RI_ASSERT(m_referenceCount > 0);
+
+    x += m_storageOffsetX;
+    y += m_storageOffsetY;
+
+    RIuint8* scanline = m_data + y * m_stride;
+    switch(m_desc.bitsPerPixel)
+    {
+    case 32:
+    {
+        RIuint32* s = ((RIuint32*)scanline) + x;
+        *s = (RIuint32)packedColor;
+        break;
+    }
+
+    case 16:
+    {
+        RIuint16* s = ((RIuint16*)scanline) + x;
+        *s = (RIuint16)packedColor;
+        break;
+    }
+
+    case 8:
+    {
+        RIuint8* s = ((RIuint8*)scanline) + x;
+        *s = (RIuint8)packedColor;
+        break;
+    }
+    case 4:
+    {
+        RIuint8* s = ((RIuint8*)scanline) + (x>>1);
+        *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+        break;
+    }
+
+    case 2:
+    {
+        RIuint8* s = ((RIuint8*)scanline) + (x>>2);
+        *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1))));
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(m_desc.bitsPerPixel == 1);
+        RIuint8* s = ((RIuint8*)scanline) + (x>>3);
+        *s = (RIuint8)((packedColor << (x&7)) | ((unsigned int)*s & ~(0x1 << (x&7))));
+        break;
+    }
+    }
+    //m_mipmapsValid = false;
+}
+
+
+/**
+ * \brief   Unsafe static method for setting image pixels
+ */
+RI_INLINE void Image::fillPackedPixels(void* data, int bpp, int x, int y, int stride, int nPixels, RIuint32 packedColor)
+{
+    RI_ASSERT(nPixels > 0);
+    RI_ASSERT(data);
+
+    RIuint8* scanline = (RIuint8*)data + y * stride;
+
+    switch(bpp)
+    {
+    case 32:
+    {
+        RIuint32* s = ((RIuint32*)scanline) + x;
+
+        for (int i = 0; i < nPixels; i++)
+            s[i] = packedColor;
+
+        break;
+    }
+
+    case 16:
+    {
+        RIuint16* s = ((RIuint16*)scanline) + x;
+
+        for (int i = 0; i < nPixels; i++)
+            s[i] = (RIuint16)packedColor;
+
+        break;
+    }
+
+    case 8:
+    {
+        RIuint8* s = ((RIuint8*)scanline) + x;
+
+        for (int i = 0; i < nPixels; i++)
+            s[i] = (RIuint8)packedColor;
+
+        break;
+    }
+    case 4:
+    {
+        //RI_ASSERT((packedColor & 0xf) == 0);
+        //packedColor &= 0xf;
+        RIuint8* s = ((RIuint8*)scanline) + (x>>1);
+        if (x & 1)
+        {
+            *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+            s++;
+            x++;
+            nPixels--;
+        }
+        RI_ASSERT(!(x&1));
+
+        int c = nPixels / 2;
+        RIuint8 bytePacked = packedColor | (packedColor << 4);
+        while (c)
+        {
+            *s++ = bytePacked;
+            c--;
+            x+=2;
+        }
+        nPixels &= 1;
+
+        if (nPixels)
+        {
+            *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+            s++;
+            x++;
+            nPixels--;
+        }
+        RI_ASSERT(nPixels == 0);
+        break;
+    }
+
+    case 2:
+    {
+        // This case should not be needed!
+        RI_ASSERT(false);
+        RIuint8* s = ((RIuint8*)scanline) + (x>>2);
+        *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1))));
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(bpp == 1);
+        RIuint8* s = ((RIuint8*)scanline) + (x>>3);
+        // \todo Get this as input instead?
+        RI_ASSERT(packedColor == 1 || packedColor == 0);
+        RIuint8 fullyPacked = (RIuint8)(-(RIint8)packedColor);
+
+        if (x & 7)
+        {
+            // Handle the first byte:
+            RIuint8 o = *s;
+            int a = x&7;
+            RI_ASSERT(a>=1);
+            int b = RI_INT_MIN(a + nPixels, 8);
+            RI_ASSERT(b > a);
+            RIuint8 emask = (1u << b)-1;
+            RIuint8 mask = (0xffu<<a) & emask;
+            RI_ASSERT(mask>0);
+            RI_ASSERT(mask<=254);
+            *s++ = (o&(~mask))|(fullyPacked & mask);
+            nPixels -= 8-(x&7);
+            x += 8-(x&7);
+        }
+
+        if (nPixels < 0)
+            return;
+
+        RI_ASSERT(!(x&1));
+
+        int c = nPixels/8;
+        while (c)
+        {
+            *s++ = fullyPacked;
+            c--;
+            x+=8;
+        }
+        nPixels -= ((nPixels/8) * 8);
+
+
+        if (nPixels)
+        {
+            RI_ASSERT((x&7) == 0);
+
+            RIuint8 o = *s;
+            int b = nPixels;
+            RI_ASSERT(b<=7);
+            RIuint8 mask = (1u<<b)-1;
+            RI_ASSERT(mask <= 127);
+            *s++ = (o&(~mask))|(fullyPacked & mask);
+        }
+        break;
+    }
+    }
+    //m_mipmapsValid = false;
+}
+RI_INLINE void Image::fillPackedPixels(int x, int y, int nPixels, RIuint32 packedColor)
+{
+    fillPackedPixels((void*)m_data, m_desc.bitsPerPixel, x + m_storageOffsetX, y + m_storageOffsetY, m_stride, nPixels, packedColor);
+}
+
+RI_INLINE void Image::fillPackedRectangle(int x0, int y0, int width, int height, RIuint32 packedColor)
+{
+    int y = y0;
+    while (height)
+    {
+        fillPackedPixels(x0, y, width, packedColor);
+        y++;
+        height--;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Surface class abstracting multisampled rendering surface.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Surface
+{
+public:
+    Surface(const Color::Descriptor& desc, int width, int height, int numSamples);	//throws bad_alloc
+    Surface(Image* image);	//throws bad_alloc
+    Surface(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data);	//throws bad_alloc
+    ~Surface();
+
+    RI_INLINE const Image* getImage() const {return m_image;}
+    RI_INLINE const Color::Descriptor&	getDescriptor() const		{ return m_image->getDescriptor(); }
+    RI_INLINE int		getWidth() const							{ return m_width; }
+    RI_INLINE int		getHeight() const							{ return m_height; }
+    RI_INLINE int		getNumSamples() const						{ return m_numSamples; }
+    RI_INLINE void		addReference()								{ m_referenceCount++; }
+    RI_INLINE int		removeReference()							{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+    RI_INLINE int		isInUse() const								{ return m_image->isInUse(); }
+    RI_INLINE bool		isInUse(Image* image) const					{ return image == m_image ? true : false; }
+
+    void				clear(const Color& clearColor, int x, int y, int w, int h, const Array<Rectangle>* scissors = NULL);
+#if 0
+    // Currently does not support msaa surfaces
+    void				blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h);	//throws bad_alloc
+    void				blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h, const Array<Rectangle>& scissors);	//throws bad_alloc
+    void				blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h);	//throws bad_alloc
+    void				blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h, const Array<Rectangle>& scissors);	//throws bad_alloc
+#endif
+    void				mask(DynamicBlitter& blitter, const Image* src, VGMaskOperation operation, int x, int y, int w, int h);
+
+    RI_INLINE void      writePackedPixelToAddress(void* address, int x, RIuint32 p)        { m_image->writePackedPixelToAddress(address, x, p); }
+   RI_INLINE RIuint32 	readPackedSample(int x, int y, int sample) const			 { return m_image->readPackedPixel(x*m_numSamples+sample, y); }
+    RI_INLINE Color		readSample(int x, int y, int sample) const                   { return m_image->readPixel(x*m_numSamples+sample, y); }
+    RI_INLINE void		writePackedSample(int x, int y, int sample, RIuint32 p)		 { m_image->writePackedPixel(x*m_numSamples+sample, y, p); }
+    RI_INLINE void		writeSample(int x, int y, int sample, const Color& c)        { m_image->writePixel(x*m_numSamples+sample, y, c); }
+    RI_INLINE void		fillPackedSamples(int x, int y, int nPixels, RIuint32 p);
+
+    RIfloat				readMaskCoverage(int x, int y) const;
+    void				writeMaskCoverage(int x, int y, RIfloat m);
+    unsigned int		readMaskMSAA(int x, int y) const;
+    void				writeMaskMSAA(int x, int y, unsigned int m);
+
+    RIuint32 			FSAAResolvePacked(int x, int y) const;
+    Color				FSAAResolve(int x, int y) const;	//for fb=>img: vgGetPixels, vgReadPixels
+
+private:
+    Surface(const Surface&);			//!< Not allowed.
+    void operator=(const Surface&);			//!< Not allowed.
+
+    struct ScissorEdge
+    {
+        ScissorEdge() : x(0), miny(0), maxy(0), direction(0) {}
+        bool operator<(const ScissorEdge& e) const	{ return x < e.x; }
+        int			x;
+        int			miny;
+        int			maxy;
+        int			direction;		//1 start, -1 end
+    };
+
+    int				m_width;
+    int				m_height;
+    int				m_numSamples;
+    int				m_referenceCount;
+
+public:
+    // \todo TERO: Broke the design of this by making it public, make proper
+    // friend/etc. C++ accessor for optimized pixel-pipelines. Combine with the
+    // removal of (remnants of) the FSAA support.
+    Image*			m_image;
+};
+
+RI_INLINE void Surface::fillPackedSamples(int x, int y, int nPixels, RIuint32 p)
+{
+    m_image->fillPackedPixels(x, y, nPixels, p);
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Drawable class for encapsulating color and mask buffers.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Drawable
+{
+public:
+    Drawable(const Color::Descriptor& desc, int width, int height, int numSamples, int maskBits);	//throws bad_alloc
+    Drawable(Image* image, int maskBits);	//throws bad_alloc
+    Drawable(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data, int maskBits);	//throws bad_alloc
+    ~Drawable();
+
+    RI_INLINE const Color::Descriptor&	getDescriptor() const		{ return m_color->getDescriptor(); }
+    RI_INLINE int       getNumMaskBits() const                      { if(!m_mask) return 0; return m_mask->getDescriptor().alphaBits; }
+    RI_INLINE int		getWidth() const							{ return m_color->getWidth(); }
+    RI_INLINE int		getHeight() const							{ return m_color->getHeight(); }
+    RI_INLINE int		getNumSamples() const						{ return m_color->getNumSamples(); }
+    RI_INLINE void		addReference()								{ m_referenceCount++; }
+    RI_INLINE int		removeReference()							{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+    RI_INLINE int		isInUse() const								{ return m_color->isInUse() || (m_mask && m_mask->isInUse()); }
+    RI_INLINE bool		isInUse(Image* image) const					{ return m_color->isInUse(image) || (m_mask && m_mask->isInUse(image)); }
+    RI_INLINE Surface*  getColorBuffer() const                      { return m_color; }
+    RI_INLINE Surface*  getMaskBuffer() const                       { return m_mask; }
+
+    void				resize(VGContext* context, int newWidth, int newHeight);	//throws bad_alloc
+private:
+    Drawable(const Drawable&);			//!< Not allowed.
+    void operator=(const Drawable&);	//!< Not allowed.
+
+    int                 m_referenceCount;
+    Surface*			m_color;
+    Surface*            m_mask;
+};
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+//==============================================================================================
+
+#endif /* __RIIMAGE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riMath.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,102 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of non-inline matrix functions.
+ * \note	
+ *//*-------------------------------------------------------------------*/
+
+#include "riDefs.h"
+#include "riMath.h"
+
+#if 0
+#include <stdio.h>
+
+static void printMatrix(const Matrix3x3& m)
+{
+    // For tracing a bug in matrix inverse in release-builds.
+    for(int i = 0; i < 3; i++)
+    {
+        printf("[%.4f %.4f %.4f]\n", m[i][0], m[i][1], m[i][2]);
+    }
+}
+
+#endif
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Inverts a 3x3 matrix. Returns false if the matrix is singular.
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+bool Matrix3x3::invert()
+{
+    // \todo Save computation on affine matrices?
+	bool affine = isAffine();
+	RIfloat det00 = matrix[1][1]*matrix[2][2] - matrix[2][1]*matrix[1][2];
+	RIfloat det01 = matrix[2][0]*matrix[1][2] - matrix[1][0]*matrix[2][2];
+	RIfloat det02 = matrix[1][0]*matrix[2][1] - matrix[2][0]*matrix[1][1];
+
+	RIfloat d = matrix[0][0]*det00 + matrix[0][1]*det01 + matrix[0][2]*det02;
+	if( d == 0.0f ) return false;	//singular, leave the matrix unmodified and return false
+	d = 1.0f / d;
+
+	Matrix3x3 t;
+
+    // \note There is some bug (in GCC?) in accessing matrix elements: If data
+    // is accessed like: t[i][j], then the following will produce incorrect
+    // resulst on optimized builds. If the data is accessed through t.matrix,
+    // then the output is correct. Debug build works correctly, and if print
+    // calls are inserted, the code also works correctly. The context to get
+    // this bug appear are fill paints (linear and radial gradient test
+    // functions).
+
+	t.matrix[0][0] = d * det00;
+	t.matrix[1][0] = d * det01;
+	t.matrix[2][0] = d * det02;
+    //printf("t\n");
+    //printMatrix(t);
+	t.matrix[0][1] = d * (matrix[2][1]*matrix[0][2] - matrix[0][1]*matrix[2][2]);
+	t.matrix[1][1] = d * (matrix[0][0]*matrix[2][2] - matrix[2][0]*matrix[0][2]);
+	t.matrix[2][1] = d * (matrix[2][0]*matrix[0][1] - matrix[0][0]*matrix[2][1]);
+	t.matrix[0][2] = d * (matrix[0][1]*matrix[1][2] - matrix[1][1]*matrix[0][2]);
+	t.matrix[1][2] = d * (matrix[1][0]*matrix[0][2] - matrix[0][0]*matrix[1][2]);
+	t.matrix[2][2] = d * (matrix[0][0]*matrix[1][1] - matrix[1][0]*matrix[0][1]);
+	if(affine)
+		t[2].set(0,0,1);	//affine matrix stays affine
+	*this = t;
+	return true;
+}
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riMath.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,452 @@
+#ifndef __RIMATH_H
+#define __RIMATH_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Math functions, Vector and Matrix classes.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIDEFS_H
+#include "riDefs.h"
+#endif
+
+#include <math.h>
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RI_INLINE int		RI_ISNAN(float a)
+{
+    RIfloatInt p;
+    p.f = a;
+    unsigned int exponent = (p.i>>23) & 0xff;
+    unsigned int mantissa = p.i & 0x7fffff;
+    if(exponent == 255 && mantissa)
+        return 1;
+    return 0;
+}
+
+#if (RI_MANTISSA_BITS > 23)
+#error RI_MANTISSA_BITS is greater than 23
+#elif (RI_EXPONENT_BITS > 8)
+#error RI_EXPONENT_BITS is greater than 8
+#elif (RI_MANTISSA_BITS != 23) || (RI_EXPONENT_BITS != 8)
+
+class RIfloat
+{
+public:
+    RIfloat() : v(0.0f)						{ removeBits(); }
+    RIfloat(float a) : v(a)					{ removeBits(); }
+    RIfloat(double a) : v((float)a)			{ removeBits(); }
+    RIfloat(int a) : v((float)a)			{ removeBits(); }
+    RIfloat(unsigned int a) : v((float)a)	{ removeBits(); }
+    RIfloat&	operator=(const RIfloat &a)	{ v = a.v; removeBits(); return *this; }
+    RIfloat&	operator+=(const RIfloat &a){ v += a.v; removeBits(); return *this; }
+    RIfloat&	operator-=(const RIfloat &a){ v -= a.v; removeBits(); return *this; }
+    RIfloat&	operator*=(const RIfloat &a){ v *= a.v; removeBits(); return *this; }
+    RIfloat&	operator/=(const RIfloat &a){ v /= a.v; removeBits(); return *this; }
+    RIfloat		operator-() const			{ return -v; }
+    operator float() const					{ return v; }
+    operator double() const					{ return (double)v; }
+    operator int() const					{ return (int)v; }
+
+    friend RIfloat	operator+(const RIfloat &a, const RIfloat &b);
+    friend RIfloat	operator+(float a, const RIfloat &b);
+    friend RIfloat	operator+(const RIfloat &a, float b);
+    friend RIfloat	operator-(const RIfloat &a, const RIfloat &b);
+    friend RIfloat	operator-(float a, const RIfloat &b);
+    friend RIfloat	operator-(const RIfloat &a, float b);
+    friend RIfloat	operator*(const RIfloat &a, const RIfloat &b);
+    friend RIfloat	operator*(float a, const RIfloat &b);
+    friend RIfloat	operator*(const RIfloat &a, float b);
+    friend RIfloat	operator/(const RIfloat &a, const RIfloat &b);
+    friend RIfloat	operator/(float a, const RIfloat &b);
+    friend RIfloat	operator/(const RIfloat &a, float b);
+
+    friend bool		operator<(const RIfloat &a, const RIfloat &b);
+    friend bool		operator<(float a, const RIfloat &b);
+    friend bool		operator<(const RIfloat &a, float b);
+    friend bool		operator>(const RIfloat &a, const RIfloat &b);
+    friend bool		operator>(float a, const RIfloat &b);
+    friend bool		operator>(const RIfloat &a, float b);
+    friend bool		operator<=(const RIfloat &a, const RIfloat &b);
+    friend bool		operator<=(float a, const RIfloat &b);
+    friend bool		operator<=(const RIfloat &a, float b);
+    friend bool		operator>=(const RIfloat &a, const RIfloat &b);
+    friend bool		operator>=(float a, const RIfloat &b);
+    friend bool		operator>=(const RIfloat &a, float b);
+    friend bool		operator==(const RIfloat &a, const RIfloat &b);
+    friend bool		operator==(float a, const RIfloat &b);
+    friend bool		operator==(const RIfloat &a, float b);
+    friend bool		operator!=(const RIfloat &a, const RIfloat &b);
+    friend bool		operator!=(float a, const RIfloat &b);
+    friend bool		operator!=(const RIfloat &a, float b);
+private:
+    void	removeBits()
+    {
+        RIfloatInt p;
+        p.f = v;
+        unsigned int exponent = (p.i>>23) & 0xff;
+        if(exponent == 0 || exponent == 255)
+            return;	//zero, denormal, infinite, or NaN
+
+        p.i &= ~((1<<(23-RI_MANTISSA_BITS))-1);
+
+#if (RI_EXPONENT_BITS != 8)
+        if (exponent > 127 + (1 << (RI_EXPONENT_BITS-1)))
+            exponent = 127 + (1 << (RI_EXPONENT_BITS-1));
+
+        if (exponent < 127 + 1 - (1 << (RI_EXPONENT_BITS-1)))
+            exponent = 127 + 1 - (1 << (RI_EXPONENT_BITS-1));
+
+        p.i &= ~(0xff<<23);
+        p.i |= exponent<<23;
+#endif
+        v = p.f;
+    }
+
+    float		v;
+};
+
+RI_INLINE RIfloat operator+(const RIfloat &a, const RIfloat &b)	{ return RIfloat(a.v+b.v); }
+RI_INLINE RIfloat operator+(float a, const RIfloat &b)			{ return RIfloat(a+b.v); }
+RI_INLINE RIfloat operator+(const RIfloat &a, float b)			{ return RIfloat(a.v+b); }
+RI_INLINE RIfloat operator-(const RIfloat &a, const RIfloat &b)	{ return RIfloat(a.v-b.v); }
+RI_INLINE RIfloat operator-(float a, const RIfloat &b)			{ return RIfloat(a-b.v); }
+RI_INLINE RIfloat operator-(const RIfloat &a, float b)			{ return RIfloat(a.v-b); }
+RI_INLINE RIfloat operator*(const RIfloat &a, const RIfloat &b)	{ return RIfloat(a.v*b.v); }
+RI_INLINE RIfloat operator*(float a, const RIfloat &b)			{ return RIfloat(a*b.v); }
+RI_INLINE RIfloat operator*(const RIfloat &a, float b)			{ return RIfloat(a.v*b); }
+RI_INLINE RIfloat operator/(const RIfloat &a, const RIfloat &b)	{ return RIfloat(a.v/b.v); }
+RI_INLINE RIfloat operator/(float a, const RIfloat &b)			{ return RIfloat(a/b.v); }
+RI_INLINE RIfloat operator/(const RIfloat &a, float b)			{ return RIfloat(a.v/b); }
+
+RI_INLINE bool operator<(const RIfloat &a, const RIfloat &b)	{ return a.v < b.v ? true : false; }
+RI_INLINE bool operator<(float a, const RIfloat &b)				{ return a < b.v ? true : false; }
+RI_INLINE bool operator<(const RIfloat &a, float b)				{ return a.v < b ? true : false; }
+RI_INLINE bool operator>(const RIfloat &a, const RIfloat &b)	{ return a.v > b.v ? true : false; }
+RI_INLINE bool operator>(float a, const RIfloat &b)				{ return a > b.v ? true : false; }
+RI_INLINE bool operator>(const RIfloat &a, float b)				{ return a.v > b ? true : false; }
+RI_INLINE bool operator<=(const RIfloat &a, const RIfloat &b)	{ return a.v <= b.v ? true : false; }
+RI_INLINE bool operator<=(float a, const RIfloat &b)			{ return a <= b.v ? true : false; }
+RI_INLINE bool operator<=(const RIfloat &a, float b)			{ return a.v <= b ? true : false; }
+RI_INLINE bool operator>=(const RIfloat &a, const RIfloat &b)	{ return a.v >= b.v ? true : false; }
+RI_INLINE bool operator>=(float a, const RIfloat &b)			{ return a >= b.v ? true : false; }
+RI_INLINE bool operator>=(const RIfloat &a, float b)			{ return a.v >= b ? true : false; }
+RI_INLINE bool operator==(const RIfloat &a, const RIfloat &b)	{ return a.v == b.v ? true : false; }
+RI_INLINE bool operator==(float a, const RIfloat &b)			{ return a == b.v ? true : false; }
+RI_INLINE bool operator==(const RIfloat &a, float b)			{ return a.v == b ? true : false; }
+RI_INLINE bool operator!=(const RIfloat &a, const RIfloat &b)	{ return a.v != b.v ? true : false; }
+RI_INLINE bool operator!=(float a, const RIfloat &b)			{ return a != b.v ? true : false; }
+RI_INLINE bool operator!=(const RIfloat &a, float b)			{ return a.v != b ? true : false; }
+
+#else
+typedef float RIfloat;
+#endif
+
+#define	RI_PI						3.141592654f
+
+RI_INLINE RIfloat   RI_FRAC(RIfloat f)                          { return f - (RIfloat)(int)f; }
+RI_INLINE int       RI_ROUND_TO_INT(RIfloat v)                  { return (v >= 0.0f) ? (int)(v+0.5f) : (int)(v-0.5f); }
+RI_INLINE RIfloat	RI_MAX(RIfloat a, RIfloat b)				{ return (a > b) ? a : b; }
+RI_INLINE int		RI_MAX(int a, int b)						{ return (a > b) ? a : b; }
+RI_INLINE RIfloat	RI_MIN(RIfloat a, RIfloat b)				{ return (a < b) ? a : b; }
+RI_INLINE int		RI_MIN(int a, int b)						{ return (a < b) ? a : b; }
+RI_INLINE RIfloat	RI_CLAMP(RIfloat a, RIfloat l, RIfloat h)	{ if(RI_ISNAN(a)) return l; RI_ASSERT(l <= h); return (a < l) ? l : (a > h) ? h : a; }
+RI_INLINE int       RI_CEIL(RIfloat a) {return (int)ceilf(a);}
+RI_INLINE int       RI_FLOOR(RIfloat a) { return (int)floorf(a); }
+RI_INLINE void		RI_SWAP(RIfloat &a, RIfloat &b)				{ RIfloat tmp = a; a = b; b = tmp; }
+RI_INLINE RIfloat	RI_ABS(RIfloat a)							{ return (a < 0.0f) ? -a : a; }
+RI_INLINE RIfloat	RI_SQR(RIfloat a)							{ return a * a; }
+RI_INLINE RIfloat	RI_DEG_TO_RAD(RIfloat a)					{ return a * RI_PI / 180.0f; }
+RI_INLINE RIfloat	RI_RAD_TO_DEG(RIfloat a)					{ return a * 180.0f/ RI_PI; }
+RI_INLINE RIfloat	RI_MOD(RIfloat a, RIfloat b)				{ if(RI_ISNAN(a) || RI_ISNAN(b)) return 0.0f; RI_ASSERT(b >= 0.0f); if(b == 0.0f) return 0.0f; RIfloat f = (RIfloat)fmod(a, b); if(f < 0.0f) f += b; RI_ASSERT(f >= 0.0f && f <= b); return f; }
+
+#define RI_ANY_SWAP(type, a, b) {type tmp = a; a = b; b = tmp;}
+
+RI_INLINE void      RI_INT16_SWAP(RIint16 &a, RIint16 &b) {RIint16 tmp = a; a = b; b = tmp;}
+RI_INLINE int       RI_INT_ABS(int a)                   { return (a >= 0) ? a : -a; }
+RI_INLINE int		RI_INT_MAX(int a, int b)			{ return (a > b) ? a : b; }
+RI_INLINE int		RI_INT_MIN(int a, int b)			{ return (a < b) ? a : b; }
+RI_INLINE int       RI_INT_CLAMP(int a, int l, int h)   { return (a < l) ? l : (a > h) ? h : a; }
+RI_INLINE void		RI_INT_SWAP(int &a, int &b)			{ int tmp = a; a = b; b = tmp; }
+RI_INLINE int		RI_INT_MOD(int a, int b)			{ RI_ASSERT(b >= 0); if(!b) return 0; int i = a % b; if(i < 0) i += b; RI_ASSERT(i >= 0 && i < b); return i; }
+RI_INLINE int		RI_INT_ADDSATURATE(int a, int b)	{ RI_ASSERT(b >= 0); int r = a + b; return (r >= a) ? r : RI_INT32_MAX; }
+
+RI_INLINE RIfloat validateFloat(RIfloat f)
+{
+    //this function is used for all floating point input values
+    if(RI_ISNAN(f)) return 0.0f;	//convert NaN to zero
+    return RI_CLAMP(f, -RI_FLOAT_MAX, RI_FLOAT_MAX);	//clamp +-inf to +-RIfloat max
+}
+
+
+
+RI_INLINE int       RI_SHL(int a, int sh)
+{
+    RI_ASSERT(sh >= 0 && sh <= 31);
+    int r = a << sh;
+    RI_ASSERT(a >= 0 ? (r >= 0) : (r < 0));
+    return r;
+}
+
+RI_INLINE int RI_SAT_SHL(RIint32 a, int sh)
+{
+    RI_ASSERT(sh >= 0 && sh <= 31);
+
+    RIint64 r = ((RIint64)a) << sh;
+
+    if (r > 0x7fffffff)
+        return 0x7fffffff;
+    else if (r < (long long)(int)0x80000000)
+        return 0x80000000;
+
+    return (RIint32)r;
+}
+
+RI_INLINE int RI_SHR(int a, int sh)
+{
+    RI_ASSERT(sh >= 0 && sh <= 31);
+    int r = a >> sh;
+    return r;
+}
+
+RI_INLINE RIfloat RI_FLOAT_TO_FX(RIfloat f, unsigned int n) { return (RIfloat)RI_ROUND_TO_INT(f * (RIfloat)RI_SHL(1, n)); }
+
+class Matrix3x3;
+class Vector2;
+class Vector3;
+
+//==============================================================================================
+
+//MatrixRxC, R = number of rows, C = number of columns
+//indexing: matrix[row][column]
+//Matrix3x3 inline functions cannot be inside the class because Vector3 is not defined yet when Matrix3x3 is defined
+
+class Matrix3x3
+{
+public:
+    RI_INLINE					Matrix3x3		();						//initialized to identity
+    RI_INLINE					Matrix3x3		( const Matrix3x3& m );
+    RI_INLINE					Matrix3x3		( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 );
+    RI_INLINE					~Matrix3x3		();
+    RI_INLINE Matrix3x3&		operator=		( const Matrix3x3& m );
+    RI_INLINE Vector3&			operator[]		( int i );				//returns a row vector
+    RI_INLINE const Vector3&	operator[]		( int i ) const;
+    RI_INLINE void				set				( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 );
+    RI_INLINE const Vector3		getRow			( int i ) const;
+    RI_INLINE const Vector3		getColumn		( int i ) const;
+    RI_INLINE void				setRow			( int i, const Vector3& v );
+    RI_INLINE void				setColumn		( int i, const Vector3& v );
+    RI_INLINE void				operator*=		( const Matrix3x3& m );
+    RI_INLINE void				operator*=		( RIfloat f );
+    RI_INLINE void				operator+=		( const Matrix3x3& m );
+    RI_INLINE void				operator-=		( const Matrix3x3& m );
+    RI_INLINE const Matrix3x3	operator-		() const;
+    RI_INLINE void				identity		();
+    RI_INLINE void				transpose		();
+    bool						invert			();	//if the matrix is singular, returns false and leaves it unmodified
+    RI_INLINE RIfloat				det				() const;
+    RI_INLINE bool				isAffine		() const;
+    RI_INLINE void              assertValid     () const;
+    RI_INLINE void              validate        ();
+
+private:
+    RIfloat						matrix[3][3];
+};
+
+//==============================================================================================
+
+class Vector2
+{
+public:
+    RI_INLINE					Vector2			() : x(0.0f), y(0.0f)					{}
+    RI_INLINE					Vector2			( const Vector2& v ) : x(v.x), y(v.y)	{}
+    RI_INLINE					Vector2			( RIfloat fx, RIfloat fy ) : x(fx), y(fy)	{}
+    RI_INLINE					~Vector2		()								{}
+    RI_INLINE Vector2&			operator=		( const Vector2& v )			{ x = v.x; y = v.y; return *this; }
+    RI_INLINE RIfloat&			operator[]		( int i )						{ RI_ASSERT(i>=0&&i<2); return (&x)[i]; }
+    RI_INLINE const RIfloat&	operator[]		( int i ) const					{ RI_ASSERT(i>=0&&i<2); return (&x)[i]; }
+    RI_INLINE void				set				( RIfloat fx, RIfloat fy )			{ x = fx; y = fy; }
+    RI_INLINE void				operator*=		( RIfloat f )						{ x *= f; y *= f; }
+    RI_INLINE void				operator+=		( const Vector2& v )			{ x += v.x; y += v.y; }
+    RI_INLINE void				operator-=		( const Vector2& v )			{ x -= v.x; y -= v.y; }
+    RI_INLINE const Vector2		operator-		() const						{ return Vector2(-x,-y); }
+    //if the vector is zero, returns false and leaves it unmodified
+    RI_INLINE bool				normalize		()								{ double l = (double)x*(double)x+(double)y*(double)y; if( l == 0.0 ) return false; l = 1.0 / sqrt(l); x = (RIfloat)((double)x * l); y = (RIfloat)((double)y * l); return true; }
+    RI_INLINE RIfloat			length			() const						{ return (RIfloat)sqrt((double)x*(double)x+(double)y*(double)y); }
+    RI_INLINE void				scale			( const Vector2& v )			{ x *= v.x; y *= v.y; }	//component-wise scale
+    RI_INLINE void				negate			()								{ x = -x; y = -y; }
+
+    RIfloat						x,y;
+};
+
+//==============================================================================================
+
+class Vector3
+{
+public:
+    RI_INLINE					Vector3			() : x(0.0f), y(0.0f), z(0.0f)							{}
+    RI_INLINE					Vector3			( const Vector3& v ) : x(v.x), y(v.y), z(v.z)			{}
+    RI_INLINE					Vector3			( RIfloat fx, RIfloat fy, RIfloat fz ) : x(fx), y(fy), z(fz)	{}
+    RI_INLINE					~Vector3		()								{}
+    RI_INLINE Vector3&			operator=		( const Vector3& v )			{ x = v.x; y = v.y; z = v.z; return *this; }
+    RI_INLINE RIfloat&			operator[]		( int i )						{ RI_ASSERT(i>=0&&i<3); return (&x)[i]; }
+    RI_INLINE const RIfloat&	operator[]		( int i ) const					{ RI_ASSERT(i>=0&&i<3); return (&x)[i]; }
+    RI_INLINE void				set				( RIfloat fx, RIfloat fy, RIfloat fz ){ x = fx; y = fy; z = fz; }
+    RI_INLINE void				operator*=		( RIfloat f )						{ x *= f; y *= f; z *= f; }
+    RI_INLINE void				operator+=		( const Vector3& v )			{ x += v.x; y += v.y; z += v.z; }
+    RI_INLINE void				operator-=		( const Vector3& v )			{ x -= v.x; y -= v.y; z -= v.z; }
+    RI_INLINE const Vector3		operator-		() const						{ return Vector3(-x,-y,-z); }
+    //if the vector is zero, returns false and leaves it unmodified
+    RI_INLINE bool				normalize		()								{ double l = (double)x*(double)x+(double)y*(double)y+(double)z*(double)z; if( l == 0.0 ) return false; l = 1.0 / sqrt(l); x = (RIfloat)((double)x * l); y = (RIfloat)((double)y * l); z = (RIfloat)((double)z * l); return true; }
+    RI_INLINE RIfloat			length			() const						{ return (RIfloat)sqrt((double)x*(double)x+(double)y*(double)y+(double)z*(double)z); }
+    RI_INLINE void				scale			( const Vector3& v )			{ x *= v.x; y *= v.y; z *= v.z; }	//component-wise scale
+    RI_INLINE void				negate			()								{ x = -x; y = -y; z = -z; }
+
+    RIfloat						x,y,z;
+};
+
+//==============================================================================================
+
+//Vector2 global functions
+RI_INLINE bool			operator==	( const Vector2& v1, const Vector2& v2 )	{ return (v1.x == v2.x) && (v1.y == v2.y); }
+RI_INLINE bool			operator!=	( const Vector2& v1, const Vector2& v2 )	{ return (v1.x != v2.x) || (v1.y != v2.y); }
+RI_INLINE bool			isEqual		( const Vector2& v1, const Vector2& v2, RIfloat epsilon )	{ return RI_SQR(v2.x-v1.x) + RI_SQR(v2.y-v1.y) <= epsilon*epsilon; }
+RI_INLINE bool			isZero		( const Vector2& v )						{ return (v.x == 0.0f) && (v.y == 0.0f); }
+RI_INLINE const Vector2	operator*	( RIfloat f, const Vector2& v )				{ return Vector2(v.x*f,v.y*f); }
+RI_INLINE const Vector2	operator*	( const Vector2& v, RIfloat f )				{ return Vector2(v.x*f,v.y*f); }
+RI_INLINE const Vector2	operator+	( const Vector2& v1, const Vector2& v2 )	{ return Vector2(v1.x+v2.x, v1.y+v2.y); }
+RI_INLINE const Vector2	operator-	( const Vector2& v1, const Vector2& v2 )	{ return Vector2(v1.x-v2.x, v1.y-v2.y); }
+RI_INLINE RIfloat		dot			( const Vector2& v1, const Vector2& v2 )	{ return v1.x*v2.x+v1.y*v2.y; }
+//if v is a zero vector, returns a zero vector
+RI_INLINE const Vector2	normalize	( const Vector2& v )						{ double l = (double)v.x*(double)v.x+(double)v.y*(double)v.y; if( l != 0.0 ) l = 1.0 / sqrt(l); return Vector2((RIfloat)((double)v.x * l), (RIfloat)((double)v.y * l)); }
+//if onThis is a zero vector, returns a zero vector
+RI_INLINE const Vector2	project		( const Vector2& v, const Vector2& onThis ) { RIfloat l = dot(onThis,onThis); if( l != 0.0f ) l = dot(v, onThis)/l; return onThis * l; }
+RI_INLINE const Vector2	lerp		( const Vector2& v1, const Vector2& v2, RIfloat ratio )	{ return v1 + ratio * (v2 - v1); }
+RI_INLINE const Vector2	scale		( const Vector2& v1, const Vector2& v2 )	{ return Vector2(v1.x*v2.x, v1.y*v2.y); }
+//matrix * column vector. The input vector2 is implicitly expanded to (x,y,1)
+RI_INLINE const Vector2 affineTransform( const Matrix3x3& m, const Vector2& v )	{ RI_ASSERT(m.isAffine()); return Vector2(v.x * m[0][0] + v.y * m[0][1] + m[0][2], v.x * m[1][0] + v.y * m[1][1] + m[1][2]); }
+//matrix * column vector. The input vector2 is implicitly expanded to (x,y,0)
+RI_INLINE const Vector2 affineTangentTransform(const Matrix3x3& m, const Vector2& v)	{ RI_ASSERT(m.isAffine()); return Vector2(v.x * m[0][0] + v.y * m[0][1], v.x * m[1][0] + v.y * m[1][1]); }
+RI_INLINE const Vector2 perpendicularCW(const Vector2& v)						{ return Vector2(v.y, -v.x); }
+RI_INLINE const Vector2 perpendicularCCW(const Vector2& v)						{ return Vector2(-v.y, v.x); }
+RI_INLINE const Vector2 perpendicular(const Vector2& v, bool cw)				{ if(cw) return Vector2(v.y, -v.x); return Vector2(-v.y, v.x); }
+
+//==============================================================================================
+
+//Vector3 global functions
+RI_INLINE bool			operator==	( const Vector3& v1, const Vector3& v2 )	{ return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); }
+RI_INLINE bool			operator!=	( const Vector3& v1, const Vector3& v2 )	{ return (v1.x != v2.x) || (v1.y != v2.y) || (v1.z != v2.z); }
+RI_INLINE bool			isEqual		( const Vector3& v1, const Vector3& v2, RIfloat epsilon )	{ return RI_SQR(v2.x-v1.x) + RI_SQR(v2.y-v1.y) + RI_SQR(v2.z-v1.z) <= epsilon*epsilon; }
+RI_INLINE const Vector3	operator*	( RIfloat f, const Vector3& v )				{ return Vector3(v.x*f,v.y*f,v.z*f); }
+RI_INLINE const Vector3	operator*	( const Vector3& v, RIfloat f )				{ return Vector3(v.x*f,v.y*f,v.z*f); }
+RI_INLINE const Vector3	operator+	( const Vector3& v1, const Vector3& v2 )	{ return Vector3(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z); }
+RI_INLINE const Vector3	operator-	( const Vector3& v1, const Vector3& v2 )	{ return Vector3(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z); }
+RI_INLINE RIfloat		dot			( const Vector3& v1, const Vector3& v2 )	{ return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z; }
+RI_INLINE const Vector3	cross		( const Vector3& v1, const Vector3& v2 )	{ return Vector3( v1.y*v2.z-v1.z*v2.y, v1.z*v2.x-v1.x*v2.z, v1.x*v2.y-v1.y*v2.x ); }
+//if v is a zero vector, returns a zero vector
+RI_INLINE const Vector3	normalize	( const Vector3& v )						{ double l = (double)v.x*(double)v.x+(double)v.y*(double)v.y+(double)v.z*(double)v.z; if( l != 0.0 ) l = 1.0 / sqrt(l); return Vector3((RIfloat)((double)v.x * l), (RIfloat)((double)v.y * l), (RIfloat)((double)v.z * l)); }
+RI_INLINE const Vector3	lerp		( const Vector3& v1, const Vector3& v2, RIfloat ratio )	{ return v1 + ratio * (v2 - v1); }
+RI_INLINE const Vector3	scale		( const Vector3& v1, const Vector3& v2 )	{ return Vector3(v1.x*v2.x, v1.y*v2.y, v1.z*v2.z); }
+
+//==============================================================================================
+
+//matrix * column vector
+RI_INLINE const Vector3	operator*	( const Matrix3x3& m, const Vector3& v)		{ return Vector3( v.x*m[0][0]+v.y*m[0][1]+v.z*m[0][2], v.x*m[1][0]+v.y*m[1][1]+v.z*m[1][2], v.x*m[2][0]+v.y*m[2][1]+v.z*m[2][2] ); }
+
+//==============================================================================================
+
+//Matrix3x3 global functions
+RI_INLINE bool				operator==	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) if( m1[i][j] != m2[i][j] ) return false; return true; }
+RI_INLINE bool				operator!=	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ return !(m1 == m2); }
+RI_INLINE const Matrix3x3	operator*	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ Matrix3x3 t; for(int i=0;i<3;i++) for(int j=0;j<3;j++) t[i][j] = m1[i][0] * m2[0][j] + m1[i][1] * m2[1][j] + m1[i][2] * m2[2][j]; return t; }
+RI_INLINE const Matrix3x3	operator*	( RIfloat f, const Matrix3x3& m )					{ Matrix3x3 t(m); t *= f; return t; }
+RI_INLINE const Matrix3x3	operator*	( const Matrix3x3& m, RIfloat f )					{ Matrix3x3 t(m); t *= f; return t; }
+RI_INLINE const Matrix3x3	operator+	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ Matrix3x3 t(m1); t += m2; return t; }
+RI_INLINE const Matrix3x3	operator-	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ Matrix3x3 t(m1); t -= m2; return t; }
+RI_INLINE const Matrix3x3	transpose	( const Matrix3x3& m )							{ Matrix3x3 t(m); t.transpose(); return t; }
+// if the matrix is singular, returns it unmodified
+RI_INLINE const Matrix3x3	invert		( const Matrix3x3& m )							{ Matrix3x3 t(m); t.invert(); return t; }
+
+//==============================================================================================
+
+//Matrix3x3 inline functions (cannot be inside the class because Vector3 is not defined yet when Matrix3x3 is defined)
+RI_INLINE					Matrix3x3::Matrix3x3	()									{ identity(); }
+RI_INLINE					Matrix3x3::Matrix3x3	( const Matrix3x3& m )				{ *this = m; }
+RI_INLINE					Matrix3x3::Matrix3x3	( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 )	{ set(m00,m01,m02,m10,m11,m12,m20,m21,m22); }
+RI_INLINE					Matrix3x3::~Matrix3x3	()									{}
+RI_INLINE Matrix3x3&		Matrix3x3::operator=	( const Matrix3x3& m )				{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] = m.matrix[i][j]; return *this; }
+RI_INLINE Vector3&			Matrix3x3::operator[]	( int i )							{ RI_ASSERT(i>=0&&i<3); return (Vector3&)matrix[i][0]; }
+RI_INLINE const Vector3&	Matrix3x3::operator[]	( int i ) const						{ RI_ASSERT(i>=0&&i<3); return (const Vector3&)matrix[i][0]; }
+RI_INLINE void				Matrix3x3::set			( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 ) { matrix[0][0] = m00; matrix[0][1] = m01; matrix[0][2] = m02; matrix[1][0] = m10; matrix[1][1] = m11; matrix[1][2] = m12; matrix[2][0] = m20; matrix[2][1] = m21; matrix[2][2] = m22; }
+RI_INLINE const Vector3		Matrix3x3::getRow		( int i ) const						{ RI_ASSERT(i>=0&&i<3); return Vector3(matrix[i][0], matrix[i][1], matrix[i][2]); }
+RI_INLINE const Vector3		Matrix3x3::getColumn	( int i ) const						{ RI_ASSERT(i>=0&&i<3); return Vector3(matrix[0][i], matrix[1][i], matrix[2][i]); }
+RI_INLINE void				Matrix3x3::setRow		( int i, const Vector3& v )			{ RI_ASSERT(i>=0&&i<3); matrix[i][0] = v.x; matrix[i][1] = v.y; matrix[i][2] = v.z; }
+RI_INLINE void				Matrix3x3::setColumn	( int i, const Vector3& v )			{ RI_ASSERT(i>=0&&i<3); matrix[0][i] = v.x; matrix[1][i] = v.y; matrix[2][i] = v.z; }
+RI_INLINE void				Matrix3x3::operator*=	( const Matrix3x3& m )				{ *this = *this * m; }
+RI_INLINE void				Matrix3x3::operator*=	( RIfloat f )							{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] *= f; }
+RI_INLINE void				Matrix3x3::operator+=	( const Matrix3x3& m )				{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] += m.matrix[i][j]; }
+RI_INLINE void				Matrix3x3::operator-=	( const Matrix3x3& m )				{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] -= m.matrix[i][j]; }
+RI_INLINE const Matrix3x3	Matrix3x3::operator-	() const							{ return Matrix3x3( -matrix[0][0],-matrix[0][1],-matrix[0][2], -matrix[1][0],-matrix[1][1],-matrix[1][2], -matrix[2][0],-matrix[2][1],-matrix[2][2]); }
+RI_INLINE void				Matrix3x3::identity		()									{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] = (i == j) ? 1.0f : 0.0f; }
+RI_INLINE void				Matrix3x3::transpose	()									{ RI_SWAP(matrix[1][0], matrix[0][1]); RI_SWAP(matrix[2][0], matrix[0][2]); RI_SWAP(matrix[2][1], matrix[1][2]); }
+RI_INLINE RIfloat			Matrix3x3::det			() const							{ return matrix[0][0] * (matrix[1][1]*matrix[2][2] - matrix[2][1]*matrix[1][2]) + matrix[0][1] * (matrix[2][0]*matrix[1][2] - matrix[1][0]*matrix[2][2]) + matrix[0][2] * (matrix[1][0]*matrix[2][1] - matrix[2][0]*matrix[1][1]); }
+RI_INLINE bool				Matrix3x3::isAffine		() const							{ if(matrix[2][0] == 0.0f && matrix[2][1] == 0.0f && matrix[2][2] == 1.0f) return true; return false; }
+
+RI_INLINE void Matrix3x3::validate()
+{
+    for (int i = 0; i < 3; i++)
+        for (int j = 0; j < 3; j++)
+            matrix[i][j] = validateFloat(matrix[i][j]);
+}
+
+RI_INLINE void Matrix3x3::assertValid() const
+{
+#if defined(RI_DEBUG)
+    for (int i = 0; i < 3; i++)
+        for (int j = 0; j < 3; j++)
+            RI_ASSERT(!RI_ISNAN(matrix[i][j]));
+#endif
+}
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+#endif /* __RIMATH_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riMiniEGL.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2210 @@
+/*------------------------------------------------------------------------
+ *
+ * EGL 1.3
+ * -------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Simple implementation of EGL 1.3
+ * \note	caveats:
+            - always renders into the backbuffer and blits it to window (no single buffered rendering)
+            - no native Windows or Mac OS X pixmap support
+            - no power management events
+            - no support for swap interval
+ * \todo	what happens in egl functions when eglTerminate has been called but the context and surface are still in use?
+ * \todo	OSDeinitMutex should be called in case getEGL fails.
+ *//*-------------------------------------------------------------------*/
+
+#include "EGL/egl.h"
+#include "openvg.h"
+#include "riArray.h"
+#include "riMath.h"
+#include "riContext.h"
+#include "riImage.h"
+
+#include "riEGLOS.h"
+
+// Temp: A blitter is kept in the egl context for surface copies, but it will
+// be placed into the EGL to VG interface in the future.
+#ifndef __SFDYNAMICBLITTER_H
+#   include "sfDynamicBlitter.h"
+#endif
+
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+#if 0
+void* OSGetCurrentThreadID(void);
+void OSAcquireMutex(void);
+void OSReleaseMutex(void);
+void OSDeinitMutex(void);
+
+EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id);
+void* OSCreateWindowContext(EGLNativeWindowType window);
+void OSDestroyWindowContext(void* context);
+bool OSIsWindow(const void* context);
+void OSGetWindowSize(const void* context, int& width, int& height);
+void OSBlitToWindow(void* context, const Drawable* drawable);
+#else
+
+
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class RIEGLConfig
+{
+public:
+    RIEGLConfig() : m_desc(Color::formatToDescriptor(VG_sRGBA_8888)), m_configID(0)	{}
+    ~RIEGLConfig()							{}
+    void		set(int r, int g, int b, int a, int l, int bpp, int samples, int maskBits, int ID)
+    {
+        Color::Shape shape;
+        m_desc.redBits = r;
+        m_desc.greenBits = g;
+        m_desc.blueBits = b;
+        m_desc.alphaBits = a;
+        m_desc.luminanceBits = l;
+#if !defined(_WIN32) && 0
+        m_desc.alphaShift = 0;
+        m_desc.luminanceShift = 0;
+        m_desc.blueShift = b ? a : 0;
+        m_desc.greenShift = g ? a + b : 0;
+        m_desc.redShift = r ? a + b + g : 0;
+#else
+        m_desc.luminanceShift = 0;
+        m_desc.redShift = 0;
+        m_desc.greenShift = g ? r : 0;
+        m_desc.blueShift = b ? r + g : 0;
+        m_desc.alphaShift = a ? r + g + b : 0;
+
+#endif
+        m_desc.internalFormat = l ? (a ? Color::sLA : Color::lLA) : ((r || g || b ) ? Color::sRGBA : Color::lRGBA);
+
+        m_desc.bitsPerPixel = bpp;
+        m_desc.bytesPerPixel = bpp / 8;
+
+        {
+            // Determine shape
+            if (m_desc.hasAlpha())
+            {
+                if (m_desc.redBits > 0)
+                    shape = Color::SHAPE_ARGB;
+                else if (m_desc.isLuminance())
+                    shape = Color::SHAPE_AL;
+                else
+                {
+                    RI_ASSERT(m_desc.isAlphaOnly());
+                    shape = Color::SHAPE_A;
+                }
+            } else
+            {
+                if (m_desc.redBits > 0)
+                {
+                    if (m_desc.bitsPerPixel == 32)
+                        shape = Color::SHAPE_XRGB;
+                    else
+                    {
+                        RI_ASSERT(m_desc.bitsPerPixel == 24 || m_desc.bitsPerPixel == 16);
+                        shape = Color::SHAPE_RGB;
+                    }
+                } else if (m_desc.isLuminance())
+                {
+                    shape = Color::SHAPE_L;
+                } else
+                {
+                    RI_ASSERT(false);
+                }
+            }
+        }
+
+        m_desc.shape = shape;
+        //m_desc.format = Color::descriptorToVGImageFormat(m_desc);
+        m_desc.vgFormat = (VGImageFormat)-1;
+        RI_ASSERT(Color::isValidDescriptor(m_desc));
+        m_samples = samples;
+        m_maskBits = maskBits;
+        m_configID = ID;
+        m_config = (EGLConfig)ID;
+    }
+
+    Color::Descriptor configToDescriptor(bool sRGB, bool premultiplied) const
+    {
+        Color::Descriptor desc = m_desc;
+        unsigned int f = m_desc.luminanceBits ? Color::LUMINANCE : 0;
+        f |= sRGB ? Color::NONLINEAR : 0;
+        f |= premultiplied ? Color::PREMULTIPLIED : 0;
+        desc.internalFormat = (Color::InternalFormat)f;
+        return desc;
+    }
+
+    //EGL RED SIZE bits of Red in the color buffer
+    //EGL GREEN SIZE bits of Green in the color buffer
+    //EGL BLUE SIZE bits of Blue in the color buffer
+    //EGL ALPHA SIZE bits of Alpha in the color buffer
+    //EGL LUMINANCE SIZE bits of Luminance in the color buffer
+    Color::Descriptor	m_desc;
+    int					m_samples;
+    int                 m_maskBits;
+    EGLint				m_configID;			//EGL CONFIG ID unique EGLConfig identifier
+    EGLConfig           m_config;
+    //EGL BUFFER SIZE depth of the color buffer (sum of channel bits)
+    //EGL ALPHA MASK SIZE number alpha mask bits (always 8)
+    //EGL BIND TO TEXTURE RGB boolean True if bindable to RGB textures. (always EGL_FALSE)
+    //EGL BIND TO TEXTURE RGBA boolean True if bindable to RGBA textures. (always EGL_FALSE)
+    //EGL COLOR BUFFER TYPE enum color buffer type (EGL_RGB_BUFFER, EGL_LUMINANCE_BUFFER)
+    //EGL CONFIG CAVEAT enum any caveats for the configuration (always EGL_NONE)
+    //EGL DEPTH SIZE integer bits of Z in the depth buffer (always 0)
+    //EGL LEVEL integer frame buffer level (always 0)
+    //EGL MAX PBUFFER WIDTH integer maximum width of pbuffer (always INT_MAX)
+    //EGL MAX PBUFFER HEIGHT integer maximum height of pbuffer (always INT_MAX)
+    //EGL MAX PBUFFER PIXELS integer maximum size of pbuffer (always INT_MAX)
+    //EGL MAX SWAP INTERVAL integer maximum swap interval (always 1)
+    //EGL MIN SWAP INTERVAL integer minimum swap interval (always 1)
+    //EGL NATIVE RENDERABLE boolean EGL TRUE if native rendering APIs can render to surface (always EGL_FALSE)
+    //EGL NATIVE VISUAL ID integer handle of corresponding native visual (always 0)
+    //EGL NATIVE VISUAL TYPE integer native visual type of the associated visual (always EGL_NONE)
+    //EGL RENDERABLE TYPE bitmask which client rendering APIs are supported. (always EGL_OPENVG_BIT)
+    //EGL SAMPLE BUFFERS integer number of multisample buffers (always 0)
+    //EGL SAMPLES integer number of samples per pixel (always 0)
+    //EGL STENCIL SIZE integer bits of Stencil in the stencil buffer (always 0)
+    //EGL SURFACE TYPE bitmask which types of EGL surfaces are supported. (always EGL WINDOW BIT | EGL PIXMAP BIT | EGL PBUFFER BIT)
+    //EGL TRANSPARENT TYPE enum type of transparency supported (always EGL_NONE)
+    //EGL TRANSPARENT RED VALUE integer transparent red value (undefined)
+    //EGL TRANSPARENT GREEN VALUE integer transparent green value (undefined)
+    //EGL TRANSPARENT BLUE VALUE integer transparent blue value (undefined)
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class RIEGLContext
+{
+public:
+    RIEGLContext(OpenVGRI::VGContext* vgctx, const EGLConfig config);
+    ~RIEGLContext();
+    void	addReference()				{ m_referenceCount++; }
+    int		removeReference()			{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+    VGContext*      getVGContext() const      { return m_vgContext; }
+    EGLConfig       getConfig() const         { return m_config; }
+    DynamicBlitter& getBlitter()              { return m_blitter; }
+private:
+    RIEGLContext(const RIEGLContext&);
+    RIEGLContext& operator=(const RIEGLContext&);
+    VGContext*		m_vgContext;
+    const EGLConfig	m_config;
+    int				m_referenceCount;
+    DynamicBlitter  m_blitter;
+};
+
+RIEGLContext::RIEGLContext(OpenVGRI::VGContext* vgctx, const EGLConfig config) :
+    m_vgContext(vgctx),
+    m_config(config),
+    m_referenceCount(0)
+{
+}
+RIEGLContext::~RIEGLContext()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    RI_DELETE(m_vgContext);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class RIEGLSurface
+{
+public:
+    RIEGLSurface(void* OSWindowContext, const EGLConfig config, Drawable* drawable, bool largestPbuffer, int renderBuffer);
+    ~RIEGLSurface();
+    void	addReference()				{ m_referenceCount++; }
+    int		removeReference()			{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+    void*           getOSWindowContext() const { return m_OSWindowContext; }
+    EGLConfig       getConfig() const          { return m_config; }
+    Drawable*       getDrawable() const        { return m_drawable; }
+    bool            isLargestPbuffer() const   { return m_largestPbuffer; }
+    int             getRenderBuffer() const    { return m_renderBuffer; }
+
+private:
+    RIEGLSurface(const RIEGLSurface&);
+    RIEGLSurface& operator=(const RIEGLSurface&);
+    void*            m_OSWindowContext;
+    const EGLConfig	 m_config;
+    Drawable*        m_drawable;
+    bool			 m_largestPbuffer;
+    int				 m_renderBuffer;		//EGL_BACK_BUFFER or EGL_SINGLE_BUFFER
+    int				 m_referenceCount;
+};
+
+RIEGLSurface::RIEGLSurface(void* OSWindowContext, const EGLConfig config, Drawable* drawable, bool largestPbuffer, int renderBuffer) :
+    m_OSWindowContext(OSWindowContext),
+    m_config(config),
+    m_drawable(drawable),
+    m_largestPbuffer(largestPbuffer),
+    m_renderBuffer(renderBuffer),
+    m_referenceCount(0)
+{
+    RI_ASSERT(m_renderBuffer == EGL_BACK_BUFFER);   //only back buffer rendering is supported
+    m_drawable->addReference();
+}
+
+RIEGLSurface::~RIEGLSurface()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    OSDestroyWindowContext((OSWindowContext*)m_OSWindowContext);
+    if(m_drawable)
+    {
+        if(!m_drawable->removeReference())
+            RI_DELETE(m_drawable);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define EGL_NUMCONFIGS		5
+
+class RIEGLDisplay
+{
+public:
+    RIEGLDisplay(EGLDisplay id);
+    ~RIEGLDisplay();
+
+    int                getNumConfigs() const              { return EGL_NUMCONFIGS; }
+    const RIEGLConfig& getConfig(int i) const             { RI_ASSERT(i >= 0 && i < EGL_NUMCONFIGS); return m_configs[i]; }
+    const RIEGLConfig& getConfig(const EGLConfig config) const        { for(int i=0;i<EGL_NUMCONFIGS;i++) { if(m_configs[i].m_config == config) return m_configs[i]; } RI_ASSERT(0); return m_configs[0]; }
+
+    EGLDisplay         getID() const                       { return m_id; }
+
+    void              addContext(RIEGLContext* ctx)       { RI_ASSERT(ctx); m_contexts.push_back(ctx); }  //throws bad_alloc
+    void              removeContext(RIEGLContext* ctx)    { RI_ASSERT(ctx); bool res = m_contexts.remove(ctx); RI_ASSERT(res); RI_UNREF(res); }
+
+    void              addSurface(RIEGLSurface* srf)       { RI_ASSERT(srf); m_surfaces.push_back(srf); }  //throws bad_alloc
+    void              removeSurface(RIEGLSurface* srf)    { RI_ASSERT(srf); bool res = m_surfaces.remove(srf); RI_ASSERT(res); RI_UNREF(res); }
+
+    EGLBoolean        contextExists(const EGLContext ctx) const;
+    EGLBoolean        surfaceExists(const EGLSurface srf) const;
+    EGLBoolean        configExists(const EGLConfig cfg) const;
+
+private:
+    RIEGLDisplay(const RIEGLDisplay& t);
+    RIEGLDisplay& operator=(const RIEGLDisplay&t);
+
+    EGLDisplay              m_id;
+
+    Array<RIEGLContext*>	m_contexts;
+    Array<RIEGLSurface*>	m_surfaces;
+
+    RIEGLConfig             m_configs[EGL_NUMCONFIGS];
+};
+
+RIEGLDisplay::RIEGLDisplay(EGLDisplay id) :
+    m_id(id),
+    m_contexts(),
+    m_surfaces()
+{
+
+    //sorted by RGB/LUMINANCE (exact), larger total number of color bits (at least), buffer size (at least), config ID (exact)
+    //NOTE: 16 bit configs need to be sorted on the fly if the request ignores some channels
+    //NOTE: config IDs start from 1
+    //                 R  B  G  A  L  bpp samples maskBits ID
+    int i = 0;
+    m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 8, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 32
+    m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++;    // RGBX
+    m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 8, i+1); i++;	// 565
+    m_configs[i].set(0, 0, 0, 0, 8, 8,  1, 8, i+1); i++;	// L8
+    m_configs[i].set(0, 0, 0, 8, 0, 8,  1, 8, i+1); i++;	// A8
+    // \note The reference implementation does not support LA16 config, so it is currently
+    // not possible to test it. See if the format fits the specification.
+    //m_configs[i].set(0, 0, 0, 8, 8, 16,  1, 8, i+1); i++;	// LA16
+#if 0
+    m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 8, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 32
+    m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++;    // RGBX
+    m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 24
+    //m_configs[i].set(5, 5, 5, 1, 0, 16, 1, 4, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 4, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    //m_configs[i].set(4, 4, 4, 4, 0, 16, 1, 4, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    m_configs[i].set(0, 0, 0, 8, 0, 8,  1, 8, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 4, 0, 4,  1, 4, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 1, 0, 1,  1, 1, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 0, 8, 8,  1, 8, i+1); i++;	//EGL_LUMINANCE_BUFFER, buffer size = 8
+    //m_configs[i].set(0, 0, 0, 0, 1, 1,  1, 1, i+1); i++;	//EGL_LUMINANCE_BUFFER, buffer size = 1
+
+    //configs without mask
+    m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 32
+    m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 24
+    //m_configs[i].set(5, 5, 5, 1, 0, 16, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    //m_configs[i].set(4, 4, 4, 4, 0, 16, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    m_configs[i].set(0, 0, 0, 8, 0, 8,  1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 4, 0, 4,  1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 1, 0, 1,  1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 0, 8, 8,  1, 0, i+1); i++;	//EGL_LUMINANCE_BUFFER, buffer size = 8
+    //m_configs[i].set(0, 0, 0, 0, 1, 1,  1, 0, 20);	//EGL_LUMINANCE_BUFFER, buffer size = 1
+#endif
+
+    RI_ASSERT(EGL_NUMCONFIGS == i);
+
+/*
+attrib                default        criteria order   priority
+--------------------------------------------------------------
+EGL_COLOR_BUFFER_TYPE EGL_RGB_BUFFER Exact    None    2
+EGL_RED_SIZE          0              AtLeast  Special 3
+EGL_GREEN_SIZE        0              AtLeast  Special 3
+EGL_BLUE_SIZE         0              AtLeast  Special 3
+EGL_LUMINANCE_SIZE    0              AtLeast  Special 3
+EGL_ALPHA_SIZE        0              AtLeast  Special 3
+EGL_BUFFER_SIZE       0              AtLeast  Smaller 4
+EGL_ALPHA_MASK_SIZE   0              AtLeast  Smaller 9
+EGL_CONFIG_ID         EGL_DONT_CARE  Exact    Smaller 11
+*/
+}
+
+RIEGLDisplay::~RIEGLDisplay()
+{
+    //mark everything for deletion, but don't delete the current context and surface
+    for(int i=0;i<m_contexts.size();i++)
+    {
+        if(!m_contexts[i]->removeReference())
+            RI_DELETE(m_contexts[i]);
+    }
+    m_contexts.clear();	//remove all contexts from the list (makes further references to the current contexts invalid)
+
+    for(int i=0;i<m_surfaces.size();i++)
+    {
+        if(!m_surfaces[i]->removeReference())
+            RI_DELETE(m_surfaces[i]);
+    }
+    m_surfaces.clear();	//remove all surfaces from the list (makes further references to the current surfaces invalid)
+}
+
+EGLBoolean RIEGLDisplay::contextExists(const EGLContext ctx) const
+{
+    for(int i=0;i<m_contexts.size();i++)
+    {
+        if(m_contexts[i] == ctx)
+            return EGL_TRUE;
+    }
+    return EGL_FALSE;
+}
+
+EGLBoolean RIEGLDisplay::surfaceExists(const EGLSurface surf) const
+{
+    for(int i=0;i<m_surfaces.size();i++)
+    {
+        if(m_surfaces[i] == surf)
+            return EGL_TRUE;
+    }
+    return EGL_FALSE;
+}
+
+EGLBoolean RIEGLDisplay::configExists(const EGLConfig config) const
+{
+    for(int i=0;i<EGL_NUMCONFIGS;i++)
+    {
+        if(m_configs[i].m_config == config)
+        return EGL_TRUE;
+    }
+    return EGL_FALSE;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class RIEGLThread
+{
+public:
+    RIEGLThread(void* currentThreadID);
+    ~RIEGLThread();
+
+    void*           getThreadID() const       { return m_threadID; }
+
+    void            makeCurrent(RIEGLContext* c, RIEGLSurface* s)       { m_context = c; m_surface = s; }
+    RIEGLContext*	getCurrentContext() const   { return m_context; }
+    RIEGLSurface*	getCurrentSurface() const   { return m_surface; }
+
+    void            setError(EGLint error)      { m_error = error; }
+    EGLint          getError() const            { return m_error; }
+
+    void            bindAPI(EGLint api)         { m_boundAPI = api; }
+    EGLint          getBoundAPI() const         { return m_boundAPI; }
+
+private:
+    RIEGLThread(const RIEGLThread&);
+    RIEGLThread operator=(const RIEGLThread&);
+
+    RIEGLContext*		m_context;
+    RIEGLSurface*		m_surface;
+    EGLint              m_error;
+    void*               m_threadID;
+    EGLint              m_boundAPI;
+};
+
+RIEGLThread::RIEGLThread(void* currentThreadID) :
+    m_context(NULL),
+    m_surface(NULL),
+    m_error(EGL_SUCCESS),
+    m_threadID(currentThreadID),
+    m_boundAPI(EGL_NONE)
+{
+}
+
+RIEGLThread::~RIEGLThread()
+{
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class EGL
+{
+public:
+    EGL();
+    ~EGL();
+
+    void	addReference()				{ m_referenceCount++; }
+    int		removeReference()			{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+    void                addDisplay(RIEGLDisplay* display)           { RI_ASSERT(display); m_displays.push_back(display); }  //throws bad alloc
+    void                removeDisplay(RIEGLDisplay* display)        { RI_ASSERT(display); bool res = m_displays.remove(display); RI_ASSERT(res); RI_UNREF(res); }
+    RIEGLDisplay*       getDisplay(const EGLDisplay displayID) const;
+    EGLDisplay          findDisplay(const EGLContext ctx) const;
+
+    void                addCurrentThread(RIEGLThread* thread)       { RI_ASSERT(thread); m_currentThreads.push_back(thread); }  //throws bad alloc
+    void                removeCurrentThread(RIEGLThread* thread)    { RI_ASSERT(thread); bool res = m_currentThreads.remove(thread); RI_ASSERT(res); RI_UNREF(res); }
+    RIEGLThread*        getCurrentThread() const;
+
+    RIEGLThread*        getThread();
+    void                destroyThread();
+
+    bool                isInUse(const void* image) const;
+
+private:
+    EGL(const EGL&);						// Not allowed.
+    const EGL& operator=(const EGL&);		// Not allowed.
+
+    Array<RIEGLThread*>		m_threads;			//threads that have called EGL
+    Array<RIEGLThread*>		m_currentThreads;	//threads that have a bound context
+    Array<RIEGLDisplay*>	m_displays;
+
+    int                     m_referenceCount;
+};
+
+EGL::EGL() :
+    m_threads(),
+    m_currentThreads(),
+    m_displays(),
+    m_referenceCount(0)
+{
+}
+EGL::~EGL()
+{
+    for(int i=0;i<m_displays.size();i++)
+    {
+        RI_DELETE(m_displays[i]);
+    }
+    for(int i=0;i<m_threads.size();i++)
+    {
+        RI_DELETE(m_threads[i]);
+    }
+    //currentThreads contain just pointers to threads we just deleted
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static EGL* g_egl = NULL;	//never use this directly
+static EGL* getEGL()
+{
+    if(!g_egl)
+    {
+        try
+        {
+            g_egl = RI_NEW(EGL, ());				//throws bad_alloc
+            g_egl->addReference();
+        }
+        catch(std::bad_alloc)
+        {
+            g_egl = NULL;
+        }
+    }
+    return g_egl;
+}
+static void releaseEGL()
+{
+    if(g_egl)
+    {
+        if(!g_egl->removeReference())
+        {
+            RI_DELETE(g_egl);
+            g_egl = NULL;
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Given a display ID, return the corresponding object, or NULL
+*			if the ID hasn't been initialized.
+* \param
+* \return
+* \note		if egl has been initialized for this display, the display ID can
+*			be found from egl->m_displays
+*//*-------------------------------------------------------------------*/
+
+RIEGLDisplay* EGL::getDisplay(EGLDisplay displayID) const
+{
+    for(int i=0;i<m_displays.size();i++)
+    {
+        if(displayID == m_displays[i]->getID())
+            return m_displays[i];
+    }
+    return NULL;		//error: the display hasn't been eglInitialized
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	return EGLDisplay for the current context
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLDisplay EGL::findDisplay(EGLContext ctx) const
+{
+    for(int i=0;i<m_displays.size();i++)
+    {
+        if(m_displays[i]->contextExists(ctx))
+            return m_displays[i]->getID();
+    }
+    return EGL_NO_DISPLAY;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	return an EGL thread struct for the thread made current, or
+*            NULL if there's no current context.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RIEGLThread* EGL::getCurrentThread() const
+{
+    void* currentThreadID = OSGetCurrentThreadID();
+    for(int i=0;i<m_currentThreads.size();i++)
+    {
+        if(currentThreadID == m_currentThreads[i]->getThreadID())
+            return m_currentThreads[i];
+    }
+    return NULL;		//thread is not current
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	return an EGL thread struct corresponding to current OS thread.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RIEGLThread* EGL::getThread()
+{
+    void* currentThreadID = OSGetCurrentThreadID();
+    for(int i=0;i<m_threads.size();i++)
+    {
+        if(currentThreadID == m_threads[i]->getThreadID())
+            return m_threads[i];
+    }
+
+    //EGL doesn't have a struct for the thread yet, add it to EGL's list
+    RIEGLThread* newThread = NULL;
+    try
+    {
+        newThread = RI_NEW(RIEGLThread, (OSGetCurrentThreadID()));	//throws bad_alloc
+        m_threads.push_back(newThread);	//throws bad_alloc
+        return newThread;
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(newThread);
+        return NULL;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	destroy an EGL thread struct
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void EGL::destroyThread()
+{
+    void* currentThreadID = OSGetCurrentThreadID();
+    for(int i=0;i<m_threads.size();i++)
+    {
+        if(currentThreadID == m_threads[i]->getThreadID())
+        {
+            RIEGLThread* thread = m_threads[i];
+            bool res = m_threads.remove(thread);
+            RI_ASSERT(res);
+            RI_UNREF(res);
+            RI_DELETE(thread);
+            break;
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool EGL::isInUse(const void* image) const
+{
+    for(int i=0;i<m_currentThreads.size();i++)
+    {
+        RIEGLSurface* s = m_currentThreads[i]->getCurrentSurface();
+        if(s && s->getDrawable() && s->getDrawable()->isInUse((Image*)image))
+            return true;
+    }
+    return false;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define EGL_GET_DISPLAY(DISPLAY, RETVAL) \
+    OSAcquireMutex(); \
+    EGL* egl = getEGL(); \
+    if(!egl) \
+    { \
+        OSReleaseMutex(); \
+        return RETVAL; \
+    } \
+    RIEGLDisplay* display = egl->getDisplay(DISPLAY); \
+
+#define EGL_GET_EGL(RETVAL) \
+    OSAcquireMutex(); \
+    EGL* egl = getEGL(); \
+    if(!egl) \
+    { \
+        OSReleaseMutex(); \
+        return RETVAL; \
+    } \
+
+#define EGL_IF_ERROR(COND, ERRORCODE, RETVAL) \
+    if(COND) { eglSetError(egl, ERRORCODE); OSReleaseMutex(); return RETVAL; } \
+
+#define EGL_RETURN(ERRORCODE, RETVAL) \
+    { \
+        eglSetError(egl, ERRORCODE); \
+        OSReleaseMutex(); \
+        return RETVAL; \
+    }
+
+// Note: egl error handling model differs from OpenVG. The latest error is stored instead of the oldest one.
+static void eglSetError(EGL* egl, EGLint error)
+{
+    RIEGLThread* thread = egl->getThread();
+    if(thread)
+        thread->setError(error);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns the OpenVG context current to the calling thread.
+* \param
+* \return
+* \note		This function is always called from a mutexed API function
+*//*-------------------------------------------------------------------*/
+
+void* eglvgGetCurrentVGContext(void)
+{
+    EGL* egl = getEGL();
+    if(egl)
+    {
+        RIEGLThread* thread = egl->getCurrentThread();
+        if(thread)
+        {
+            RI_ASSERT(thread->getCurrentContext() && thread->getCurrentSurface());
+            return thread->getCurrentContext()->getVGContext();
+        }
+    }
+    return NULL;	//not initialized or made current
+}
+
+bool  eglvgLockSurface(bool read, bool write)
+{
+    (void)read;
+    (void)write;
+    return true;
+}
+
+bool  eglvgUnlockSurface()
+{
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Check if the image is current in any of the displays
+* \param
+* \return
+* \note		This function is always called from a mutexed API function
+*//*-------------------------------------------------------------------*/
+
+bool eglvgIsInUse(void* image)
+{
+    EGL* egl = getEGL();
+    if(egl)
+    {
+        return egl->isInUse(image);
+    }
+    return false;
+}
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+using namespace OpenVGRI;
+
+
+
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLint EGLAPIENTRY eglGetError()
+{
+    OSAcquireMutex();
+    EGLint ret = EGL_SUCCESS;
+    EGL* egl = getEGL();
+    if(egl)
+    {
+        RIEGLThread* thread = egl->getThread();
+        if(thread)
+            ret = thread->getError();	//initialized, return error code
+    }
+    else ret = EGL_NOT_INITIALIZED;
+    OSReleaseMutex();
+    return ret;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id)
+{
+    return OSGetDisplay(display_id);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(display, EGL_SUCCESS, EGL_TRUE);	//already initialized
+
+    //create the current display
+    //if a context and a surface are bound by the time of eglTerminate, they remain bound until eglMakeCurrent is called
+    RIEGLDisplay* newDisplay = NULL;
+    try
+    {
+        newDisplay = RI_NEW(RIEGLDisplay, (dpy));	//throws bad_alloc
+        egl->addDisplay(newDisplay);	//throws bad_alloc
+        display = newDisplay;
+        RI_ASSERT(display);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(newDisplay);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE);
+    }
+
+    if(major) *major = 1;
+    if(minor) *minor = 2;
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglTerminate(EGLDisplay dpy)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_SUCCESS, EGL_TRUE);
+    egl->removeDisplay(display);
+    RI_DELETE(display);
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+const char* EGLAPIENTRY eglQueryString(EGLDisplay dpy, EGLint name)
+{
+    EGL_GET_DISPLAY(dpy, NULL);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, NULL);
+
+    static const char apis[] = "OpenVG";
+    static const char extensions[] = "";
+    static const char vendor[] = "Khronos Group";
+    static const char version[] = "1.3";
+
+    const char* ret = NULL;
+    switch(name)
+    {
+    case EGL_CLIENT_APIS:
+        ret = apis;
+        break;
+
+    case EGL_EXTENSIONS:
+        ret = extensions;
+        break;
+
+    case EGL_VENDOR:
+        ret = vendor;
+        break;
+
+    case EGL_VERSION:
+        ret = version;
+        break;
+
+    default:
+        EGL_RETURN(EGL_BAD_PARAMETER, NULL);
+    }
+    EGL_RETURN(EGL_SUCCESS, ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglGetConfigs(EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!num_config, EGL_BAD_PARAMETER, EGL_FALSE);
+    if(!configs)
+    {
+        *num_config = display->getNumConfigs();
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+    }
+    *num_config = RI_INT_MIN(config_size, display->getNumConfigs());
+    for(int i=0;i<*num_config;i++)
+        configs[i] = display->getConfig(i).m_config;
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static bool smaller(EGLint c, EGLint filter)
+{
+    return (filter != EGL_DONT_CARE) && (c < filter);
+}
+
+EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!num_config, EGL_BAD_PARAMETER, EGL_FALSE);
+
+    if(!configs)
+    {
+        *num_config = display->getNumConfigs();
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+    }
+    *num_config = 0;
+    if(!config_size)
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+
+    int bufferSize = 0;
+    int redSize = 0;
+    int greenSize = 0;
+    int blueSize = 0;
+    int luminanceSize = 0;
+    int alphaSize = 0;
+    int alphaMaskSize = 0;
+    int colorBufferType = EGL_RGB_BUFFER;
+    int configID = EGL_DONT_CARE;
+    int sampleBuffers = 0;
+    int samples = 0;
+    if(attrib_list)
+    {
+        for(int i=0;attrib_list[i] != EGL_NONE;i+=2)
+        {
+            switch(attrib_list[i])
+            {
+            case EGL_BUFFER_SIZE:				//depth of the color buffer
+                bufferSize = attrib_list[i+1];
+                break;
+            case EGL_RED_SIZE:					//bits of Red in the color buffer
+                redSize = attrib_list[i+1];
+                break;
+            case EGL_GREEN_SIZE:				//bits of Green in the color buffer
+                greenSize = attrib_list[i+1];
+                break;
+            case EGL_BLUE_SIZE:					//bits of Blue in the color buffer
+                blueSize = attrib_list[i+1];
+                break;
+            case EGL_LUMINANCE_SIZE:			//bits of Luminance in the color buffer
+                luminanceSize = attrib_list[i+1];
+                break;
+            case EGL_ALPHA_SIZE:				//bits of Alpha in the color buffer
+                alphaSize = attrib_list[i+1];
+                break;
+            case EGL_ALPHA_MASK_SIZE:			//bits of Alpha in the alpha mask buffer
+                alphaMaskSize = attrib_list[i+1];
+                if(attrib_list[i+1] > 8)
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+            case EGL_COLOR_BUFFER_TYPE:			//enum color buffer type (EGL_RGB_BUFFER, EGL_LUMINANCE_BUFFER)
+                EGL_IF_ERROR(attrib_list[i+1] != EGL_RGB_BUFFER && attrib_list[i+1] != EGL_LUMINANCE_BUFFER && attrib_list[i+1] != EGL_DONT_CARE, EGL_BAD_ATTRIBUTE, EGL_FALSE);
+                colorBufferType = attrib_list[i+1];
+                break;
+            case EGL_CONFIG_ID:					//unique EGLConfig identifier
+                configID = attrib_list[i+1];
+                break;
+
+            case EGL_SAMPLE_BUFFERS:			//integer number of multisample buffers
+                sampleBuffers = attrib_list[i+1];
+                break;
+            case EGL_SAMPLES:					//integer number of samples per pixel
+                samples = attrib_list[i+1];
+                break;
+
+            case EGL_BIND_TO_TEXTURE_RGB:		//boolean True if bindable to RGB textures. (always EGL_FALSE)
+            case EGL_BIND_TO_TEXTURE_RGBA:		//boolean True if bindable to RGBA textures. (always EGL_FALSE)
+            case EGL_DEPTH_SIZE:				//integer bits of Z in the depth buffer (always 0)
+            case EGL_LEVEL:						//integer frame buffer level (always 0)
+            case EGL_NATIVE_RENDERABLE:			//boolean EGL TRUE if native rendering APIs can render to surface (always EGL_FALSE)
+            case EGL_STENCIL_SIZE:				//integer bits of Stencil in the stencil buffer (always 0)
+                if(attrib_list[i+1])
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+
+            case EGL_CONFIG_CAVEAT:				//enum any caveats for the configuration (always EGL_NONE)
+            case EGL_NATIVE_VISUAL_TYPE:		//integer native visual type of the associated visual (always EGL_NONE)
+                if(attrib_list[i+1] != EGL_NONE)
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+
+            case EGL_MAX_SWAP_INTERVAL:			//integer maximum swap interval (always 1)
+            case EGL_MIN_SWAP_INTERVAL:			//integer minimum swap interval (always 1)
+                if(attrib_list[i+1] != 1)
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+
+            case EGL_RENDERABLE_TYPE:			//bitmask which client rendering APIs are supported. (always EGL_OPENVG_BIT)
+                if(!(attrib_list[i+1] & EGL_OPENVG_BIT))
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+
+            case EGL_SURFACE_TYPE:				//bitmask which types of EGL surfaces are supported. (always EGL_WINDOW_BIT | EGL_PIXMAP_BIT | EGL_PBUFFER_BIT | EGL_VG_COLORSPACE_LINEAR_BIT | EGL_VG_ALPHA_FORMAT_PRE_BIT)
+                break;	//all types are always supported
+
+            case EGL_TRANSPARENT_TYPE:			//enum type of transparency supported (always EGL_NONE)
+            case EGL_NATIVE_VISUAL_ID:			//integer handle of corresponding native visual (always 0)
+            case EGL_MAX_PBUFFER_WIDTH:			//integer maximum width of pbuffer (always INT_MAX)
+            case EGL_MAX_PBUFFER_HEIGHT:		//integer maximum height of pbuffer (always INT_MAX)
+            case EGL_MAX_PBUFFER_PIXELS:		//integer maximum size of pbuffer (always INT_MAX)
+            case EGL_TRANSPARENT_RED_VALUE:		//integer transparent red value (undefined)
+            case EGL_TRANSPARENT_GREEN_VALUE:	//integer transparent green value (undefined)
+            case EGL_TRANSPARENT_BLUE_VALUE:	//integer transparent blue value (undefined)
+                break;	//ignored
+
+            default:
+                EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE);	//unknown attribute
+            }
+        }
+    }
+
+    if(configID && configID != EGL_DONT_CARE)
+    {	//if CONFIG_ID is defined, ignore the rest of the attribs
+        for(int i=0;i<EGL_NUMCONFIGS;i++)
+        {
+            if(display->getConfig(i).m_configID == configID)
+            {
+                *num_config = 1;
+                *configs = display->getConfig(i).m_config;
+            }
+        }
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+    }
+
+    //go through all configs, add passed configs to return list
+    //TODO take alpha mask size into account
+    EGLConfig found[EGL_NUMCONFIGS];
+    int keys[EGL_NUMCONFIGS];
+    int numFound = 0;
+    for(int i=0;i<display->getNumConfigs();i++)
+    {
+        const RIEGLConfig& c = display->getConfig(i);
+
+        int configMaskBits = c.m_maskBits;
+        int colorBits = c.m_desc.redBits + c.m_desc.greenBits + c.m_desc.blueBits;
+        int luminanceBits = c.m_desc.luminanceBits;
+        int configBufferSize;
+        if(colorBits)
+        {
+            RI_ASSERT(!luminanceBits);
+            colorBits += c.m_desc.alphaBits;
+            configBufferSize = colorBits;
+        }
+        else if(luminanceBits)
+        {
+            luminanceBits += c.m_desc.alphaBits;
+            configBufferSize = luminanceBits;
+        }
+        else
+        {	//alpha only surface
+            colorBits = c.m_desc.alphaBits;
+            luminanceBits = c.m_desc.alphaBits;
+            configBufferSize = colorBits;
+        }
+
+        if (smaller(configBufferSize, bufferSize))
+            continue;
+
+        int configSampleBuffers = c.m_samples == 1 ? 0 : 1;
+        if (smaller(configSampleBuffers, sampleBuffers))
+            continue;
+        if (smaller(c.m_samples, samples))
+            continue;
+
+        if (smaller(c.m_desc.redBits, redSize)
+            || smaller(c.m_desc.greenBits, greenSize)
+            || smaller(c.m_desc.blueBits, blueSize)
+            || smaller(c.m_desc.alphaBits, alphaSize) )
+            continue;
+
+        if (smaller(c.m_desc.luminanceBits, luminanceSize))
+            continue;
+
+        if (smaller(configMaskBits, alphaMaskSize))
+            continue;
+
+        if ((colorBufferType == EGL_RGB_BUFFER && !colorBits) ||
+            (colorBufferType == EGL_LUMINANCE_BUFFER && !luminanceBits))
+            continue;
+
+        // \todo Add the alphaMaskSize into the sort order also!
+        int sortKey = c.m_configID;	//sort from smaller to larger
+        int sortBits = 0;
+        if(redSize != 0 && redSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.redBits;
+        if(greenSize != 0 && greenSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.greenBits;
+        if(blueSize != 0 && blueSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.blueBits;
+        if(alphaSize != 0 && alphaSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.alphaBits;
+        if(luminanceSize != 0 && luminanceSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.luminanceBits;
+        RI_ASSERT(c.m_configID <= EGL_NUMCONFIGS);	//if there are more configs, increase the shift value
+        RI_ASSERT(sortBits <= 32);
+        sortKey += (32-sortBits) << 4;	//sort from larger to smaller
+
+        found[numFound] = c.m_config;
+        keys[numFound++] = sortKey;
+    }
+    if(!numFound)
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+
+    //sort return list into increasing order
+    for(int e=0;e<numFound-1;e++)
+    {
+        for(int f=e+1;f<numFound;f++)
+        {
+            if(keys[e] > keys[f])
+            {
+                EGLConfig tmp = found[e];
+                found[e] = found[f];
+                found[f] = tmp;
+                RI_INT_SWAP(keys[e], keys[f]);
+            }
+        }
+    }
+
+    //write configs into return array
+    numFound = RI_INT_MIN(numFound, config_size);
+    for(int i=0;i<numFound;i++)
+    {
+        configs[i] = found[i];
+    }
+    *num_config = numFound;
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_FALSE);
+    const RIEGLConfig& c = display->getConfig(config);
+    switch(attribute)
+    {
+    case EGL_BUFFER_SIZE:
+        *value = RI_INT_MAX(c.m_desc.redBits + c.m_desc.greenBits + c.m_desc.blueBits + c.m_desc.alphaBits, c.m_desc.luminanceBits + c.m_desc.alphaBits);
+        break;
+
+    case EGL_RED_SIZE:
+        *value = c.m_desc.redBits;
+        break;
+
+    case EGL_GREEN_SIZE:
+        *value = c.m_desc.greenBits;
+        break;
+
+    case EGL_BLUE_SIZE:
+        *value = c.m_desc.blueBits;
+        break;
+
+    case EGL_LUMINANCE_SIZE:
+        *value = c.m_desc.luminanceBits;
+        break;
+
+    case EGL_ALPHA_SIZE:
+        *value = c.m_desc.alphaBits;
+        break;
+
+    case EGL_ALPHA_MASK_SIZE:
+        *value = c.m_maskBits;
+        break;
+
+    case EGL_BIND_TO_TEXTURE_RGB:
+    case EGL_BIND_TO_TEXTURE_RGBA:
+        *value = EGL_FALSE;
+        break;
+
+    case EGL_COLOR_BUFFER_TYPE:
+        if(c.m_desc.redBits)
+            *value = EGL_RGB_BUFFER;
+        else
+            *value = EGL_LUMINANCE_BUFFER;
+        break;
+
+    case EGL_CONFIG_CAVEAT:
+        *value = EGL_NONE;
+        break;
+
+    case EGL_CONFIG_ID:
+        *value = c.m_configID;
+        break;
+
+    case EGL_DEPTH_SIZE:
+        *value = 0;
+        break;
+
+    case EGL_LEVEL:
+        *value = 0;
+        break;
+
+    case EGL_MAX_PBUFFER_WIDTH:
+    case EGL_MAX_PBUFFER_HEIGHT:
+        *value = 16384;			//NOTE arbitrary maximum
+        break;
+
+    case EGL_MAX_PBUFFER_PIXELS:
+        *value = 16384*16384;	//NOTE arbitrary maximum
+        break;
+
+    case EGL_MAX_SWAP_INTERVAL:
+    case EGL_MIN_SWAP_INTERVAL:
+        *value = 1;
+        break;
+
+    case EGL_NATIVE_RENDERABLE:
+        *value = EGL_FALSE;
+        break;
+
+    case EGL_NATIVE_VISUAL_ID:
+        *value = 0;
+        break;
+
+    case EGL_NATIVE_VISUAL_TYPE:
+        *value = EGL_NONE;
+        break;
+
+    case EGL_RENDERABLE_TYPE:
+        *value = EGL_OPENVG_BIT;
+        break;
+
+    case EGL_SAMPLE_BUFFERS:
+        *value = c.m_samples > 1 ? 1 : 0;
+        break;
+
+    case EGL_SAMPLES:
+        *value = c.m_samples > 1 ? c.m_samples : 0;
+        break;
+
+    case EGL_STENCIL_SIZE:
+        *value = 0;
+        break;
+
+    case EGL_SURFACE_TYPE:
+        *value = EGL_WINDOW_BIT | EGL_PIXMAP_BIT | EGL_PBUFFER_BIT | EGL_VG_COLORSPACE_LINEAR_BIT | EGL_VG_ALPHA_FORMAT_PRE_BIT;
+        break;
+
+    case EGL_TRANSPARENT_TYPE:
+        *value = EGL_NONE;
+        break;
+
+    case EGL_TRANSPARENT_RED_VALUE:
+    case EGL_TRANSPARENT_GREEN_VALUE:
+    case EGL_TRANSPARENT_BLUE_VALUE:
+        *value = 0;
+        break;
+
+    case EGL_CONFORMANT:
+        *value = EGL_OPENVG_BIT;  //TODO return proper value
+        break;
+
+    default:
+        EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE);
+    }
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list)
+{
+    EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE);
+
+    int renderBuffer = EGL_BACK_BUFFER;
+    int colorSpace = EGL_VG_COLORSPACE_sRGB;
+    int alphaFormat = EGL_VG_ALPHA_FORMAT_NONPRE;
+    if(attrib_list)
+    {
+        for(int i=0;attrib_list[i] != EGL_NONE;i+=2)
+        {
+            switch(attrib_list[i])
+            {
+            case EGL_RENDER_BUFFER:
+                renderBuffer = attrib_list[i+1];
+                break;
+
+            case EGL_VG_COLORSPACE:
+                colorSpace = attrib_list[i+1];
+                break;
+
+            case EGL_VG_ALPHA_FORMAT:
+                alphaFormat = attrib_list[i+1];
+                break;
+
+            default:
+                EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
+            }
+        }
+    }
+    //we ignore the renderBuffer parameter since we can only render to double buffered surfaces
+
+    //TODO If the attributes of win do not correspond to config, then an EGL BAD MATCH error is generated.
+    //TODO If there is already an EGLConfig associated with win (as a result of a previous eglCreateWindowSurface call), then an EGL BAD ALLOC error is generated
+
+    void* wc = NULL;
+    OpenVGRI::Drawable* d = NULL;
+    RIEGLSurface* s = NULL;
+    try
+    {
+        wc = OSCreateWindowContext((EGLNativeWindowType)win);
+        RI_ASSERT(wc);
+        //TODO what should happen if window width or height is zero?
+        int windowWidth = 0, windowHeight = 0;
+        OSGetWindowSize((OSWindowContext*)wc, windowWidth, windowHeight);
+        bool isWindow = OSIsWindow((const OSWindowContext*)wc);
+        if(windowWidth <= 0 || windowHeight <= 0 || !isWindow)
+        {
+            OSDestroyWindowContext((OSWindowContext*)wc);
+            EGL_IF_ERROR(!isWindow, EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
+            EGL_IF_ERROR(windowWidth <= 0 || windowHeight <= 0, EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
+        }
+        Color::Descriptor colorDescriptor = display->getConfig(config).configToDescriptor((colorSpace == EGL_VG_COLORSPACE_LINEAR) ? false : true, (alphaFormat == EGL_VG_ALPHA_FORMAT_PRE) ? true : false);
+        d = RI_NEW(OpenVGRI::Drawable, (colorDescriptor, windowWidth, windowHeight, display->getConfig(config).m_samples, display->getConfig(config).m_maskBits));	//throws bad_alloc
+        RI_ASSERT(d);
+        s = RI_NEW(RIEGLSurface,(wc, config, d, false, renderBuffer));	//throws bad_alloc
+        RI_ASSERT(s);
+        s->addReference();
+        display->addSurface(s);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        OSDestroyWindowContext((OSWindowContext*)wc);
+        RI_DELETE(d);
+        RI_DELETE(s);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+    }
+    EGL_RETURN(EGL_SUCCESS, (EGLSurface)s);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list)
+{
+    EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE);
+
+    int width = 0, height = 0;
+    bool largestPbuffer = false;
+    int colorSpace = EGL_VG_COLORSPACE_sRGB;
+    int alphaFormat = EGL_VG_ALPHA_FORMAT_NONPRE;
+    if(attrib_list)
+    {
+        for(int i=0;attrib_list[i] != EGL_NONE;i+=2)
+        {
+            switch(attrib_list[i])
+            {
+            case EGL_WIDTH:
+                width = attrib_list[i+1];
+                break;
+
+            case EGL_HEIGHT:
+                height = attrib_list[i+1];
+                break;
+
+            case EGL_LARGEST_PBUFFER:
+                largestPbuffer = attrib_list[i+1] ? true : false;
+                break;
+
+            case EGL_VG_COLORSPACE:
+                colorSpace = attrib_list[i+1];
+                break;
+
+            case EGL_VG_ALPHA_FORMAT:
+                alphaFormat = attrib_list[i+1];
+                break;
+
+            case EGL_TEXTURE_FORMAT:	//config doesn't support OpenGL ES
+            case EGL_TEXTURE_TARGET:	//config doesn't support OpenGL ES
+            case EGL_MIPMAP_TEXTURE:	//config doesn't support OpenGL ES
+            default:
+                EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
+            break;
+            }
+        }
+    }
+    EGL_IF_ERROR(width <= 0 || height <= 0, EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
+
+    OpenVGRI::Drawable* d = NULL;
+    RIEGLSurface* s = NULL;
+    try
+    {
+        d = RI_NEW(OpenVGRI::Drawable, (display->getConfig(config).configToDescriptor((colorSpace == EGL_VG_COLORSPACE_LINEAR) ? false : true, (alphaFormat == EGL_VG_ALPHA_FORMAT_PRE) ? true : false), width, height, display->getConfig(config).m_samples, display->getConfig(config).m_maskBits));	//throws bad_alloc
+        RI_ASSERT(d);
+        s = RI_NEW(RIEGLSurface,(NULL, config, d, largestPbuffer, EGL_BACK_BUFFER));	//throws bad_alloc
+        RI_ASSERT(s);
+        s->addReference();
+        display->addSurface(s);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(d);
+        RI_DELETE(s);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+    }
+    EGL_RETURN(EGL_SUCCESS, (EGLSurface)s);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list)
+{
+    EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE);
+    EGL_IF_ERROR(buftype != EGL_OPENVG_IMAGE, EGL_BAD_PARAMETER, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!buffer, EGL_BAD_PARAMETER, EGL_NO_SURFACE);	//TODO should also check if buffer really is a valid VGImage object (needs VG context for that)
+    Image* image = (Image*)buffer;
+    EGL_IF_ERROR(image->isInUse(), EGL_BAD_ACCESS, EGL_NO_SURFACE);	//buffer is in use by OpenVG
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE);
+    EGL_IF_ERROR(attrib_list && attrib_list[0] != EGL_NONE, EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);	//there are no valid attribs for OpenVG
+    const Color::Descriptor& bc = ((Image*)buffer)->getDescriptor();
+    const Color::Descriptor& cc = display->getConfig(config).m_desc;
+    EGL_IF_ERROR(bc.redBits != cc.redBits || bc.greenBits != cc.greenBits || bc.blueBits != cc.blueBits ||
+                 bc.alphaBits != cc.alphaBits || bc.luminanceBits != cc.luminanceBits, EGL_BAD_MATCH, EGL_NO_SURFACE);
+
+    //TODO If buffer is already bound to another pbuffer, an EGL BAD ACCESS error is generated.
+
+    OpenVGRI::Drawable* d = NULL;
+    RIEGLSurface* s = NULL;
+    try
+    {
+        d = RI_NEW(OpenVGRI::Drawable, (image, display->getConfig(config).m_maskBits));
+        RI_ASSERT(d);
+        s = RI_NEW(RIEGLSurface,(NULL, config, d, false, EGL_BACK_BUFFER));	//throws bad_alloc
+        RI_ASSERT(s);
+        s->addReference();
+        display->addSurface(s);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(d);
+        RI_DELETE(s);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+    }
+    EGL_RETURN(EGL_SUCCESS, (EGLSurface)s);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list)
+{
+    // Seems that this function has not been implemented correctly in the RI:
+    // cannot assume that EGLNativePixmapType has format, data, etc.
+#if 0
+    EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!pixmap || !isValidImageFormat(pixmap->format) || !pixmap->data || pixmap->width <= 0 || pixmap->height <= 0, EGL_BAD_NATIVE_PIXMAP, EGL_NO_SURFACE);
+    RI_UNREF(attrib_list);
+    EGL_IF_ERROR(display->getConfig(config).m_samples != 1, EGL_BAD_MATCH, EGL_NO_SURFACE);
+
+    //TODO If there is already an EGLSurface associated with pixmap (as a result of a previous eglCreatePixmapSurface call), then a EGL BAD ALLOC error is generated.
+
+    Drawable* d = NULL;
+    RIEGLSurface* s = NULL;
+    try
+    {
+        d = RI_NEW(Drawable, (Color::formatToDescriptor((VGImageFormat)pixmap->format), pixmap->width, pixmap->height, pixmap->stride, (RIuint8*)pixmap->data, display->getConfig(config).m_maskBits));	//throws bad_alloc
+        RI_ASSERT(d);
+        s = RI_NEW(RIEGLSurface,(NULL, config, d, false, EGL_BACK_BUFFER));	//throws bad_alloc
+        RI_ASSERT(s);
+        s->addReference();
+        display->addSurface(s);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(d);
+        RI_DELETE(s);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+    }
+    EGL_RETURN(EGL_SUCCESS, (EGLSurface)s);
+#else
+    (void)dpy;
+    (void)config;
+    (void)pixmap;
+    (void)attrib_list;
+    return 0;
+#endif
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglDestroySurface(EGLDisplay dpy, EGLSurface surface)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+
+    display->removeSurface((RIEGLSurface*)surface);
+    if(!((RIEGLSurface*)surface)->removeReference())
+        RI_DELETE((RIEGLSurface*)surface);
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+    RI_UNREF(attribute);
+    RI_UNREF(value);
+    //do nothing
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglQuerySurface(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+    //TODO give an error if value is NULL?
+
+    RIEGLSurface* s = (RIEGLSurface*)surface;
+    switch(attribute)
+    {
+    case EGL_VG_ALPHA_FORMAT:
+        *value = (s->getDrawable()->getDescriptor().isPremultiplied()) ? EGL_VG_ALPHA_FORMAT_PRE : EGL_VG_ALPHA_FORMAT_NONPRE;
+        break;
+
+    case EGL_VG_COLORSPACE:
+        *value = (s->getDrawable()->getDescriptor().isNonlinear()) ? EGL_VG_COLORSPACE_sRGB : EGL_VG_COLORSPACE_LINEAR;
+        break;
+
+    case EGL_CONFIG_ID:
+        *value = display->getConfig(s->getConfig()).m_configID;
+        break;
+
+    case EGL_HEIGHT:
+        *value = s->getDrawable()->getHeight();
+        break;
+
+    case EGL_HORIZONTAL_RESOLUTION:
+        *value = EGL_UNKNOWN;			//TODO Horizontal dot pitch
+        break;
+
+    case EGL_LARGEST_PBUFFER:
+        if(!s->getOSWindowContext())
+            *value = s->isLargestPbuffer() ? EGL_TRUE : EGL_FALSE;
+        break;
+
+    case EGL_MIPMAP_TEXTURE:
+        if(!s->getOSWindowContext())
+            *value = EGL_FALSE;
+        break;
+
+    case EGL_MIPMAP_LEVEL:
+        if(!s->getOSWindowContext())
+            *value = 0;
+        break;
+
+    case EGL_PIXEL_ASPECT_RATIO:
+        *value = EGL_UNKNOWN;			//TODO Display aspect ratio
+        break;
+
+    case EGL_RENDER_BUFFER:
+        *value = s->getRenderBuffer();
+        break;
+
+    case EGL_SWAP_BEHAVIOR:
+        *value = EGL_BUFFER_PRESERVED;
+        break;
+
+    case EGL_TEXTURE_FORMAT:
+        if(!s->getOSWindowContext())
+            *value = EGL_NO_TEXTURE;
+        break;
+
+    case EGL_TEXTURE_TARGET:
+        if(!s->getOSWindowContext())
+            *value = EGL_NO_TEXTURE;
+        break;
+
+    case EGL_VERTICAL_RESOLUTION:
+        *value = EGL_UNKNOWN;			//TODO Vertical dot pitch
+        break;
+
+    case EGL_WIDTH:
+        *value = s->getDrawable()->getWidth();
+        break;
+
+    default:
+        EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE);
+    }
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list)
+{
+    EGL_GET_DISPLAY(dpy, EGL_NO_CONTEXT);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_CONTEXT);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_CONTEXT);
+    RI_UNREF(attrib_list);
+
+    RIEGLThread* thread = egl->getThread();
+    if(!thread)
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
+
+    //creation of OpenGL ES contexts is not allowed in this implementation
+    if(thread->getBoundAPI() != EGL_OPENVG_API)
+        EGL_RETURN(EGL_BAD_MATCH, EGL_NO_CONTEXT);
+
+    OpenVGRI::VGContext* vgctx = NULL;
+    RIEGLContext* c = NULL;
+    try
+    {
+        vgctx = RI_NEW(OpenVGRI::VGContext, (share_context ? ((RIEGLContext*)share_context)->getVGContext() : NULL));	//throws bad_alloc
+        c = RI_NEW(RIEGLContext, (vgctx, config));	//throws bad_alloc
+        c->addReference();
+        display->addContext(c);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(vgctx);
+        RI_DELETE(c);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
+    }
+
+    EGL_RETURN(EGL_SUCCESS, (EGLContext)c);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE);
+
+    RIEGLContext* context = (RIEGLContext*)ctx;
+    display->removeContext(context);
+    if(!context->removeReference() )
+        RI_DELETE(context);
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(ctx != EGL_NO_CONTEXT && !display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE);
+    EGL_IF_ERROR(draw != EGL_NO_SURFACE && !display->surfaceExists(draw), EGL_BAD_SURFACE, EGL_FALSE);
+    EGL_IF_ERROR(read != EGL_NO_SURFACE && !display->surfaceExists(read), EGL_BAD_SURFACE, EGL_FALSE);
+    EGL_IF_ERROR(draw != read, EGL_BAD_MATCH, EGL_FALSE);	//TODO what's the proper error code?
+    EGL_IF_ERROR((draw != EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT) || (draw == EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT), EGL_BAD_MATCH, EGL_FALSE);
+
+    RIEGLSurface* s = NULL;
+    RIEGLContext* c = NULL;
+    if(draw != EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT)
+    {
+        EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+
+        s = (RIEGLSurface*)draw;
+        c = (RIEGLContext*)ctx;
+
+        //If either draw or read are pbuffers created with eglCreatePbufferFromClientBuffer, and the underlying bound client API buffers
+        //are in use by the client API that created them, an EGL BAD ACCESS error is generated.
+        EGL_IF_ERROR(s->getDrawable()->isInUse(), EGL_BAD_ACCESS, EGL_FALSE);
+
+
+        //TODO properly check compatibility of surface and context:
+        //-both have RGB or LUMINANCE configs
+        //-buffer bit depths match
+        //-configs support OpenVG
+        //-both have the same display
+        EGL_IF_ERROR(s->getConfig() != c->getConfig(), EGL_BAD_MATCH, EGL_FALSE);
+        //TODO check if context or surfaces are already bound to another thread
+
+        //If a native window underlying either draw or read is no longer valid, an EGL BAD NATIVE WINDOW error is generated.
+        EGL_IF_ERROR(s->getOSWindowContext() && !OSIsWindow((const OSWindowContext*)s->getOSWindowContext()), EGL_BAD_NATIVE_WINDOW, EGL_FALSE);
+
+        //TODO If the previous context of the calling display has unflushed commands, and the previous surface is no longer valid, an EGL BAD CURRENT SURFACE error is generated. (can this happen?)
+        //TODO If the ancillary buffers for draw and read cannot be allocated, an EGL BAD ALLOC error is generated. (mask buffer?)
+    }
+
+    //check if the thread is current
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread)
+    {	//thread is current, release the old bindinds and remove the thread from the current thread list
+        RIEGLContext* pc = thread->getCurrentContext();
+        RIEGLSurface* ps = thread->getCurrentSurface();
+        if(pc)
+        {
+            vgFlush();
+            pc->getVGContext()->setDefaultDrawable(NULL);
+            if(!pc->removeReference())
+                RI_DELETE(pc);
+        }
+        if(ps)
+        {
+            if(!ps->removeReference())
+                RI_DELETE(ps);
+        }
+
+        egl->removeCurrentThread(thread);
+    }
+
+    if( c && s )
+    {
+        //bind context and surface to the current display
+        RIEGLThread* newThread = egl->getThread();
+        if(!newThread)
+            EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE);
+        newThread->makeCurrent(c, s);
+        c->getVGContext()->setDefaultDrawable(s->getDrawable());
+
+        try
+        {
+            egl->addCurrentThread(newThread);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+            EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE);
+        }
+
+        c->addReference();
+        s->addReference();
+    }
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLContext EGLAPIENTRY eglGetCurrentContext()
+{
+    EGL_GET_EGL(EGL_NO_CONTEXT);
+    EGLContext ret = EGL_NO_CONTEXT;
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread && thread->getBoundAPI() == EGL_OPENVG_API)
+    {
+        ret = thread->getCurrentContext();
+        RI_ASSERT(ret);
+    }
+    EGL_RETURN(EGL_SUCCESS, ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglGetCurrentSurface(EGLint readdraw)
+{
+    EGL_GET_EGL(EGL_NO_SURFACE);
+    EGL_IF_ERROR(readdraw != EGL_READ && readdraw != EGL_DRAW, EGL_BAD_PARAMETER, EGL_NO_SURFACE);
+    EGLContext ret = EGL_NO_SURFACE;
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread && thread->getBoundAPI() == EGL_OPENVG_API)
+    {
+        ret = thread->getCurrentSurface();
+        RI_ASSERT(ret);
+    }
+    EGL_RETURN(EGL_SUCCESS, ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns the current display
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLDisplay EGLAPIENTRY eglGetCurrentDisplay(void)
+{
+    EGL_GET_EGL(EGL_NO_DISPLAY);
+
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(!thread || thread->getBoundAPI() != EGL_OPENVG_API)
+        EGL_RETURN(EGL_SUCCESS, EGL_NO_DISPLAY);
+
+    RIEGLContext* ctx = thread->getCurrentContext();
+    RI_ASSERT(ctx);
+    EGLDisplay ret = egl->findDisplay(ctx);
+    EGL_RETURN(EGL_SUCCESS, ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglQueryContext(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint* value)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE);
+    EGL_IF_ERROR(attribute != EGL_CONFIG_ID && attribute != EGL_CONTEXT_CLIENT_TYPE, EGL_BAD_ATTRIBUTE, EGL_FALSE);
+    if(attribute == EGL_CONFIG_ID)
+        *value = display->getConfig(((RIEGLContext*)ctx)->getConfig()).m_configID;
+    if(attribute == EGL_CONTEXT_CLIENT_TYPE)
+        *value = EGL_OPENVG_API;
+    // \todo [kalle 05/Jul/05] Handling of EGL_RENDER_BUFFER attribute is missing.
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglBindAPI(EGLenum api)
+{
+    EGL_GET_EGL(EGL_FALSE);
+    EGL_IF_ERROR(api != EGL_OPENVG_API && api != EGL_OPENGL_ES_API, EGL_BAD_PARAMETER, EGL_FALSE);
+    RIEGLThread* thread = egl->getThread();
+    if(thread)
+        thread->bindAPI(api);
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLenum EGLAPIENTRY eglQueryAPI(void)
+{
+    EGL_GET_EGL(EGL_NONE);
+    RIEGLThread* thread = egl->getThread();
+    if(thread)
+        EGL_RETURN(EGL_SUCCESS, thread->getBoundAPI());
+    EGL_RETURN(EGL_SUCCESS, EGL_NONE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglWaitClient()
+{
+    EGL_GET_EGL(EGL_FALSE);
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread && thread->getBoundAPI() == EGL_OPENVG_API)
+        vgFinish();
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Waits for OpenGL ES
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglWaitGL(void)
+{
+    return EGL_TRUE;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note		We don't support native rendering
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglWaitNative(EGLint engine)
+{
+    RI_UNREF(engine);
+    return EGL_TRUE;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface surface)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+
+    RIEGLSurface* s = (RIEGLSurface*)surface;
+
+    RIEGLThread* currentThread = egl->getCurrentThread();
+    EGL_IF_ERROR(!currentThread || currentThread->getCurrentSurface() != s, EGL_BAD_SURFACE, EGL_FALSE);
+    EGL_IF_ERROR(!OSIsWindow((const OSWindowContext*)s->getOSWindowContext()), EGL_BAD_NATIVE_WINDOW, EGL_FALSE);
+
+    vgFlush();
+
+    if(!s->getOSWindowContext())
+    {	//do nothing for other than window surfaces (NOTE: single-buffered window surfaces should return immediately as well)
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+    }
+
+    int windowWidth = 0, windowHeight = 0;
+    OSGetWindowSize((OSWindowContext*)s->getOSWindowContext(), windowWidth, windowHeight);
+
+    if(windowWidth != s->getDrawable()->getWidth() || windowHeight != s->getDrawable()->getHeight())
+    {	//resize the back buffer
+        RIEGLContext* c = currentThread->getCurrentContext();
+        RI_ASSERT(c);
+        try
+        {
+            s->getDrawable()->resize(c->getVGContext(), windowWidth, windowHeight);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+            c->getVGContext()->setDefaultDrawable(NULL);
+            EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE);
+        }
+    }
+
+    OSBlitToWindow((OSWindowContext*)s->getOSWindowContext(), s->getDrawable());
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target)
+{
+    // This RI implementation does not make sense.
+#if 0
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+    EGL_IF_ERROR(!target || !isValidImageFormat(target->format) || !target->data || target->width <= 0 || target->height <= 0, EGL_BAD_NATIVE_PIXMAP, EGL_FALSE);
+    RIEGLThread* currentThread = egl->getCurrentThread();
+    RIEGLContext* c = currentThread->getCurrentContext();
+    RI_ASSERT(c);
+    try
+    {
+        Image output(Color::formatToDescriptor((VGImageFormat)target->format), target->width, target->height, target->stride, (RIuint8*)target->data);
+        output.addReference();
+        output.blit(c->getVGContext(), ((RIEGLSurface*)surface)->getDrawable()->getColorBuffer()->getImage(), 0, 0, 0, 0, target->width, target->height);	//throws bad_alloc
+        output.removeReference();
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+#else
+    (void)dpy;
+    (void)surface;
+    (void)target;
+    return EGL_FALSE;
+#endif
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note		We support only swap interval one
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglSwapInterval(EGLDisplay dpy, EGLint interval)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    RI_UNREF(interval);
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+typedef void RI_Proc();
+
+__eglMustCastToProperFunctionPointerType EGLAPIENTRY eglGetProcAddress(const char *procname)
+{
+    if(!procname)
+        return NULL;
+    return NULL;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglReleaseThread(void)
+{
+    EGL_GET_EGL(EGL_FALSE);
+
+    //check if the thread is current
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread)
+    {	//thread is current, release the old bindings and remove the thread from the current thread list
+        RIEGLContext* pc = thread->getCurrentContext();
+        RIEGLSurface* ps = thread->getCurrentSurface();
+        if(pc)
+        {
+            vgFlush();
+            pc->getVGContext()->setDefaultDrawable(NULL);
+            if(!pc->removeReference())
+                RI_DELETE(pc);
+        }
+        if(ps)
+        {
+            if(!ps->removeReference())
+                RI_DELETE(ps);
+        }
+
+        egl->removeCurrentThread(thread);
+    }
+
+    //destroy EGL's thread struct
+    egl->destroyThread();
+
+    //destroy the EGL instance
+    releaseEGL();
+
+    OSReleaseMutex();
+    OSDeinitMutex();
+
+    return EGL_SUCCESS;
+}
+
+#undef EGL_NUMCONFIGS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riPath.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2779 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief   Implementation of Path functions.
+ * \note    
+ *//*-------------------------------------------------------------------*/
+
+#include "riPath.h"
+
+//==============================================================================================
+
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+RIfloat inputFloat(VGfloat f);  //defined in riApi.cpp
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Form a reliable normalized average of the two unit input vectors.
+*           The average always lies to the given direction from the first
+*           vector.
+* \param    u0, u1 Unit input vectors.
+* \param    cw True if the average should be clockwise from u0, false if
+*              counterclockwise.
+* \return   Average of the two input vectors.
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static const Vector2 unitAverage(const Vector2& u0, const Vector2& u1, bool cw)
+{
+    Vector2 u = 0.5f * (u0 + u1);
+    Vector2 n0 = perpendicularCCW(u0);
+
+    if( dot(u, u) > 0.25f )
+    {   //the average is long enough and thus reliable
+        if( dot(n0, u1) < 0.0f )
+            u = -u; //choose the larger angle
+    }
+    else
+    {   // the average is too short, use the average of the normals to the vectors instead
+        Vector2 n1 = perpendicularCW(u1);
+        u = 0.5f * (n0 + n1);
+    }
+    if( cw )
+        u = -u;
+
+    return normalize(u);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Form a reliable normalized average of the two unit input vectors.
+*           The average lies on the side where the angle between the input
+*           vectors is less than 180 degrees.
+* \param    u0, u1 Unit input vectors.
+* \return   Average of the two input vectors.
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static const Vector2 unitAverage(const Vector2& u0, const Vector2& u1)
+{
+    Vector2 u = 0.5f * (u0 + u1);
+
+    if( dot(u, u) < 0.25f )
+    {   // the average is unreliable, use the average of the normals to the vectors instead
+        Vector2 n0 = perpendicularCCW(u0);
+        Vector2 n1 = perpendicularCW(u1);
+        u = 0.5f * (n0 + n1);
+        if( dot(n1, u0) < 0.0f )
+            u = -u;
+    }
+
+    return normalize(u);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Interpolate the given unit tangent vectors to the given
+*           direction on a unit circle.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static const Vector2 circularLerp(const Vector2& t0, const Vector2& t1, RIfloat ratio, bool cw)
+{
+    Vector2 u0 = t0, u1 = t1;
+    RIfloat l0 = 0.0f, l1 = 1.0f;
+    for(int i=0;i<18;i++)
+    {
+        Vector2 n = unitAverage(u0, u1, cw);
+        RIfloat l = 0.5f * (l0 + l1);
+        if( ratio < l )
+        {
+            u1 = n;
+            l1 = l;
+        }
+        else
+        {
+            u0 = n;
+            l0 = l;
+        }
+    }
+    return u0;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Interpolate the given unit tangent vectors on a unit circle.
+*           Smaller angle between the vectors is used.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static const Vector2 circularLerp(const Vector2& t0, const Vector2& t1, RIfloat ratio)
+{
+    Vector2 u0 = t0, u1 = t1;
+    RIfloat l0 = 0.0f, l1 = 1.0f;
+    for(int i=0;i<18;i++)
+    {
+        Vector2 n = unitAverage(u0, u1);
+        RIfloat l = 0.5f * (l0 + l1);
+        if( ratio < l )
+        {
+            u1 = n;
+            l1 = l;
+        }
+        else
+        {
+            u0 = n;
+            l0 = l;
+        }
+    }
+    return u0;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Path constructor.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+Path::Path(VGint format, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int segmentCapacityHint, int coordCapacityHint, VGbitfield caps) :
+    m_format(format),
+    m_datatype(datatype),
+    m_scale(scale),
+    m_bias(bias),
+    m_capabilities(caps),
+    m_referenceCount(0),
+    m_segments(),
+    m_data(),
+    m_vertices(),
+    m_segmentToVertex(),
+    m_userMinx(0.0f),
+    m_userMiny(0.0f),
+    m_userMaxx(0.0f),
+    m_userMaxy(0.0f)
+{
+    RI_ASSERT(format == VG_PATH_FORMAT_STANDARD);
+    RI_ASSERT(datatype >= VG_PATH_DATATYPE_S_8 && datatype <= VG_PATH_DATATYPE_F);
+    if(segmentCapacityHint > 0)
+        m_segments.reserve(RI_INT_MIN(segmentCapacityHint, 65536));
+    if(coordCapacityHint > 0)
+        m_data.reserve(RI_INT_MIN(coordCapacityHint, 65536) * getBytesPerCoordinate(datatype));
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Path destructor.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+Path::~Path()
+{
+    RI_ASSERT(m_referenceCount == 0);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Reads a coordinate and applies scale and bias.
+* \param    
+* \return   
+*//*-------------------------------------------------------------------*/
+
+RIfloat Path::getCoordinate(int i) const
+{
+    RI_ASSERT(i >= 0 && i < m_data.size() / getBytesPerCoordinate(m_datatype));
+    RI_ASSERT(m_scale != 0.0f);
+
+    const RIuint8* ptr = &m_data[0];
+    switch(m_datatype)
+    {
+    case VG_PATH_DATATYPE_S_8:
+        return (RIfloat)(((const RIint8*)ptr)[i]) * m_scale + m_bias;
+
+    case VG_PATH_DATATYPE_S_16:
+        return (RIfloat)(((const RIint16*)ptr)[i]) * m_scale + m_bias;
+
+    case VG_PATH_DATATYPE_S_32:
+        return (RIfloat)(((const RIint32*)ptr)[i]) * m_scale + m_bias;
+
+    default:
+        RI_ASSERT(m_datatype == VG_PATH_DATATYPE_F);
+        return (RIfloat)(((const RIfloat32*)ptr)[i]) * m_scale + m_bias;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Writes a coordinate, subtracting bias and dividing out scale.
+* \param    
+* \return   
+* \note     If the coordinates do not fit into path datatype range, they
+*           will overflow silently.
+*//*-------------------------------------------------------------------*/
+
+void Path::setCoordinate(Array<RIuint8>& data, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int i, RIfloat c)
+{
+    RI_ASSERT(i >= 0 && i < data.size()/getBytesPerCoordinate(datatype));
+    RI_ASSERT(!RI_ISNAN(scale));    
+    RI_ASSERT(!RI_ISNAN(bias));
+    RI_ASSERT(scale != 0.0f);
+
+    c = inputFloat(c); // Revalidate: Can happen when a coordinate has been transformed.
+    c -= bias;
+    c /= scale;
+
+    RI_ASSERT(!RI_ISNAN(c));
+
+    RIuint8* ptr = &data[0];
+    switch(datatype)
+    {
+    case VG_PATH_DATATYPE_S_8:
+        ((RIint8*)ptr)[i] = (RIint8)floor(c + 0.5f);    //add 0.5 for correct rounding
+        break;
+
+    case VG_PATH_DATATYPE_S_16:
+        ((RIint16*)ptr)[i] = (RIint16)floor(c + 0.5f);  //add 0.5 for correct rounding
+        break;
+
+    case VG_PATH_DATATYPE_S_32:
+        ((RIint32*)ptr)[i] = (RIint32)floor(c + 0.5f);  //add 0.5 for correct rounding
+        break;
+
+    default:
+        RI_ASSERT(datatype == VG_PATH_DATATYPE_F);
+        ((RIfloat32*)ptr)[i] = (RIfloat32)c;
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Given a datatype, returns the number of bytes per coordinate.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+int Path::getBytesPerCoordinate(VGPathDatatype datatype)
+{
+    if(datatype == VG_PATH_DATATYPE_S_8)
+        return 1;
+    if(datatype == VG_PATH_DATATYPE_S_16)
+        return 2;
+    RI_ASSERT(datatype == VG_PATH_DATATYPE_S_32 || datatype == VG_PATH_DATATYPE_F);
+    return 4;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Given a path segment type, returns the number of coordinates
+*           it uses.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+int Path::segmentToNumCoordinates(VGPathSegment segment)
+{
+    RI_ASSERT(((int)segment >> 1) >= 0 && ((int)segment >> 1) <= 12);
+    static const int coords[13] = {0,2,2,1,1,4,6,2,4,5,5,5,5};
+    return coords[(int)segment >> 1];
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Computes the number of coordinates a segment sequence uses.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+int Path::countNumCoordinates(const RIuint8* segments, int numSegments)
+{
+    RI_ASSERT(segments);
+    RI_ASSERT(numSegments >= 0);
+
+    int coordinates = 0;
+    for(int i=0;i<numSegments;i++)
+        coordinates += segmentToNumCoordinates(getPathSegment(segments[i]));
+    return coordinates;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Clears path segments and data, and resets capabilities.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::clear(VGbitfield capabilities)
+{
+    m_segments.clear();
+    m_data.clear();
+    m_capabilities = capabilities;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Appends user segments and data.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::appendData(const RIuint8* segments, int numSegments, const RIuint8* data)
+{
+    RI_ASSERT(numSegments > 0);
+    RI_ASSERT(segments && data);
+    RI_ASSERT(m_referenceCount > 0);
+
+    //allocate new arrays
+    int oldSegmentsSize = m_segments.size();
+    int newSegmentsSize = oldSegmentsSize + numSegments;
+    Array<RIuint8> newSegments;
+    newSegments.resize(newSegmentsSize);    //throws bad_alloc
+
+    int newCoords = countNumCoordinates(segments, numSegments);
+    int bytesPerCoordinate = getBytesPerCoordinate(m_datatype);
+    int newDataSize = m_data.size() + newCoords * bytesPerCoordinate;
+    Array<RIuint8> newData;
+    newData.resize(newDataSize);    //throws bad_alloc
+    //if we get here, the memory allocations have succeeded
+
+    //copy old segments and append new ones
+    if(m_segments.size())
+        ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+    ri_memcpy(&newSegments[0] + m_segments.size(), segments, numSegments);
+
+    //copy old data and append new ones
+    if(newData.size())
+    {
+        if(m_data.size())
+            ri_memcpy(&newData[0], &m_data[0], m_data.size());
+        if(m_datatype == VG_PATH_DATATYPE_F)
+        {
+            RIfloat32* d = (RIfloat32*)(&newData[0] + m_data.size());
+            const RIfloat32* s = (const RIfloat32*)data;
+            for(int i=0;i<newCoords;i++)
+                *d++ = (RIfloat32)inputFloat(*s++);
+        }
+        else
+        {
+            ri_memcpy(&newData[0] + m_data.size(), data, newCoords * bytesPerCoordinate);
+        }
+    }
+
+    RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype));
+
+    //replace old arrays
+    m_segments.swap(newSegments);
+    m_data.swap(newData);
+
+    int c = 0;
+    for(int i=0;i<m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+        c += coords;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Appends a path.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::append(const Path* srcPath)
+{
+    RI_ASSERT(srcPath);
+    RI_ASSERT(m_referenceCount > 0 && srcPath->m_referenceCount > 0);
+
+    if(srcPath->m_segments.size())
+    {
+        //allocate new arrays
+        int newSegmentsSize = m_segments.size() + srcPath->m_segments.size();
+        Array<RIuint8> newSegments;
+        newSegments.resize(newSegmentsSize);    //throws bad_alloc
+
+        int newDataSize = m_data.size() + srcPath->getNumCoordinates() * getBytesPerCoordinate(m_datatype);
+        Array<RIuint8> newData;
+        newData.resize(newDataSize);    //throws bad_alloc
+        //if we get here, the memory allocations have succeeded
+
+        //copy old segments and append new ones
+        if(m_segments.size())
+            ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+        if(srcPath->m_segments.size())
+            ri_memcpy(&newSegments[0] + m_segments.size(), &srcPath->m_segments[0], srcPath->m_segments.size());
+
+        //copy old data and append new ones
+        if(m_data.size())
+            ri_memcpy(&newData[0], &m_data[0], m_data.size());
+        for(int i=0;i<srcPath->getNumCoordinates();i++)
+            setCoordinate(newData, m_datatype, m_scale, m_bias, i + getNumCoordinates(), srcPath->getCoordinate(i));
+
+        RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype));
+
+        //replace old arrays
+        m_segments.swap(newSegments);
+        m_data.swap(newData);
+    }
+}
+
+int Path::coordsSizeInBytes( int startIndex, int numSegments )
+    {
+    RI_ASSERT(numSegments > 0);
+    RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size());
+    RI_ASSERT(m_referenceCount > 0);
+
+    int numCoords = countNumCoordinates(&m_segments[startIndex], numSegments);
+    if(!numCoords)
+        return 0;
+    int bytesPerCoordinate = getBytesPerCoordinate(m_datatype);
+    return (numCoords * bytesPerCoordinate);
+    }
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Modifies existing coordinate data.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::modifyCoords(int startIndex, int numSegments, const RIuint8* data)
+{
+    RI_ASSERT(numSegments > 0);
+    RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size());
+    RI_ASSERT(data);
+    RI_ASSERT(m_referenceCount > 0);
+
+    int startCoord = countNumCoordinates(&m_segments[0], startIndex);
+    int numCoords = countNumCoordinates(&m_segments[startIndex], numSegments);
+    if(!numCoords)
+        return;
+    int bytesPerCoordinate = getBytesPerCoordinate(m_datatype);
+    RIuint8* dst = &m_data[startCoord * bytesPerCoordinate];
+    if(m_datatype == VG_PATH_DATATYPE_F)
+    {
+        RIfloat32* d = (RIfloat32*)dst;
+        const RIfloat32* s = (const RIfloat32*)data;
+        for(int i=0;i<numCoords;i++)
+            *d++ = (RIfloat32)inputFloat(*s++);
+    }
+    else
+    {
+        ri_memcpy(dst, data, numCoords*bytesPerCoordinate);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Appends a transformed copy of the source path.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::transform(const Path* srcPath, const Matrix3x3& matrix)
+{
+    RI_ASSERT(srcPath);
+    RI_ASSERT(m_referenceCount > 0 && srcPath->m_referenceCount > 0);
+    RI_ASSERT(matrix.isAffine());
+
+    if(!srcPath->m_segments.size())
+        return;
+
+    //count the number of resulting coordinates
+    int numSrcCoords = 0;
+    int numDstCoords = 0;
+    for(int i=0;i<srcPath->m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(srcPath->m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+        numSrcCoords += coords;
+        if(segment == VG_HLINE_TO || segment == VG_VLINE_TO)
+            coords = 2; //convert hline and vline to lines
+        numDstCoords += coords;
+    }
+
+    //allocate new arrays
+    Array<RIuint8> newSegments;
+    newSegments.resize(m_segments.size() + srcPath->m_segments.size()); //throws bad_alloc
+    Array<RIuint8> newData;
+    newData.resize(m_data.size() + numDstCoords * getBytesPerCoordinate(m_datatype));   //throws bad_alloc
+    //if we get here, the memory allocations have succeeded
+
+    //copy old segments
+    if(m_segments.size())
+        ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+
+    //copy old data
+    if(m_data.size())
+        ri_memcpy(&newData[0], &m_data[0], m_data.size());
+
+    int srcCoord = 0;
+    int dstCoord = getNumCoordinates();
+    Vector2 s(0,0);     //the beginning of the current subpath
+    Vector2 o(0,0);     //the last point of the previous segment
+    for(int i=0;i<srcPath->m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(srcPath->m_segments[i]);
+        VGPathAbsRel absRel = getPathAbsRel(srcPath->m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+
+        switch(segment)
+        {
+        case VG_CLOSE_PATH:
+        {
+            RI_ASSERT(coords == 0);
+            o = s;
+            break;
+        }
+
+        case VG_MOVE_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 tc;
+
+            if (absRel == VG_ABSOLUTE)
+                tc = affineTransform(matrix, c);
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+            
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            s = c;
+            o = c;
+            break;
+        }
+
+        case VG_LINE_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 tc;
+
+            if (absRel == VG_ABSOLUTE)
+                tc = affineTransform(matrix, c);
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            o = c;
+            break;
+        }
+
+        case VG_HLINE_TO:
+        {
+            RI_ASSERT(coords == 1);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), 0);
+            Vector2 tc;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                c.y = o.y;
+                tc = affineTransform(matrix, c);
+            }
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            o = c;
+            segment = VG_LINE_TO;
+            break;
+        }
+
+        case VG_VLINE_TO:
+        {
+            RI_ASSERT(coords == 1);
+            Vector2 c(0, srcPath->getCoordinate(srcCoord+0));
+            Vector2 tc;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                c.x = o.x;
+                tc = affineTransform(matrix, c);
+            }
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            o = c;
+            segment = VG_LINE_TO;
+            break;
+        }
+
+        case VG_QUAD_TO:
+        {
+            RI_ASSERT(coords == 4);
+            Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            Vector2 tc0, tc1;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                tc0 = affineTransform(matrix, c0);
+                tc1 = affineTransform(matrix, c1);
+            }
+            else
+            {
+                tc0 = affineTangentTransform(matrix, c0);
+                tc1 = affineTangentTransform(matrix, c1);
+                c1 += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.y);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y);
+            o = c1;
+            break;
+        }
+
+        case VG_CUBIC_TO:
+        {
+            RI_ASSERT(coords == 6);
+            Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            Vector2 c2(srcPath->getCoordinate(srcCoord+4), srcPath->getCoordinate(srcCoord+5));
+            Vector2 tc0, tc1, tc2;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                tc0 = affineTransform(matrix, c0);
+                tc1 = affineTransform(matrix, c1);
+                tc2 = affineTransform(matrix, c2);
+            }
+            else
+            {
+                tc0 = affineTangentTransform(matrix, c0);
+                tc1 = affineTangentTransform(matrix, c1);
+                tc2 = affineTangentTransform(matrix, c2);
+                c2 += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.y);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.y);
+            o = c2;
+            break;
+        }
+
+        case VG_SQUAD_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 tc1;
+
+            if (absRel == VG_ABSOLUTE)
+                tc1 = affineTransform(matrix, c1);
+            else
+            {
+                tc1 = affineTangentTransform(matrix, c1);
+                c1 += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y);
+            o = c1;
+            break;
+        }
+
+        case VG_SCUBIC_TO:
+        {
+            RI_ASSERT(coords == 4);
+            Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c2(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            Vector2 tc1, tc2;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                tc1 = affineTransform(matrix, c1);
+                tc2 = affineTransform(matrix, c2);
+            }
+            else
+            {
+                tc1 = affineTangentTransform(matrix, c1);
+                tc2 = affineTangentTransform(matrix, c2);
+                c2 += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.y);
+            o = c2;
+            break;
+        }
+
+        default:
+        {
+            RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO ||
+                      segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO);
+            RI_ASSERT(coords == 5);
+            RIfloat rh = srcPath->getCoordinate(srcCoord+0);
+            RIfloat rv = srcPath->getCoordinate(srcCoord+1);
+            RIfloat rot = srcPath->getCoordinate(srcCoord+2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+3), srcPath->getCoordinate(srcCoord+4));
+
+            rot = RI_DEG_TO_RAD(rot);
+            Matrix3x3 u((RIfloat)cos(rot)*rh, -(RIfloat)sin(rot)*rv,  0,
+                        (RIfloat)sin(rot)*rh,  (RIfloat)cos(rot)*rv,  0,
+                        0,                   0,                   1);
+            u = matrix * u;
+            u[2].set(0,0,1);        //force affinity
+            //u maps from the unit circle to transformed ellipse
+
+            //compute new rh, rv and rot
+            Vector2 p(u[0][0], u[1][0]);
+            Vector2 q(u[1][1], -u[0][1]);
+            bool swapped = false;
+            if(dot(p,p) < dot(q,q))
+            {
+                RI_SWAP(p.x,q.x);
+                RI_SWAP(p.y,q.y);
+                swapped = true;
+            }
+            Vector2 h = (p+q) * 0.5f;
+            Vector2 hp = (p-q) * 0.5f;
+            RIfloat hlen = h.length();
+            RIfloat hplen = hp.length();
+            rh = hlen + hplen;
+            rv = hlen - hplen;
+
+            if (RI_ISNAN(rh)) rh = 0.0f;
+            if (RI_ISNAN(rv)) rv = 0.0f;
+
+            h = hplen * h + hlen * hp;
+            hlen = dot(h,h);
+            if(hlen == 0.0f)
+                rot = 0.0f;
+            else
+            {
+                h.normalize();
+                rot = (RIfloat)acos(h.x);
+                if(h.y < 0.0f)
+                    rot = 2.0f*RI_PI - rot;
+                if (RI_ISNAN(rot))
+                    rot = 0.0f;
+            }
+            if(swapped)
+                rot += RI_PI*0.5f;
+
+            Vector2 tc;
+            if (absRel == VG_ABSOLUTE)
+                tc = affineTransform(matrix, c);
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, rh);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, rv);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, RI_RAD_TO_DEG(rot));
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            o = c;
+
+            //flip winding if the determinant is negative
+            if (matrix.det() < 0)
+            {
+                switch (segment)
+                {
+                case VG_SCCWARC_TO: segment = VG_SCWARC_TO;     break;
+                case VG_SCWARC_TO:  segment = VG_SCCWARC_TO;    break;
+                case VG_LCCWARC_TO: segment = VG_LCWARC_TO;     break;
+                case VG_LCWARC_TO:  segment = VG_LCCWARC_TO;    break;
+                default:                                        break;
+                }
+            }
+            break;
+        }
+        }
+
+        newSegments[m_segments.size() + i] = (RIuint8)(segment | absRel);
+        srcCoord += coords;
+    }
+    RI_ASSERT(srcCoord == numSrcCoords);
+    RI_ASSERT(dstCoord == getNumCoordinates() + numDstCoords);
+
+    RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype));
+
+    //replace old arrays
+    m_segments.swap(newSegments);
+    m_data.swap(newData);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Normalizes a path for interpolation.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::normalizeForInterpolation(const Path* srcPath)
+{
+    RI_ASSERT(srcPath);
+    RI_ASSERT(srcPath != this);
+    RI_ASSERT(srcPath->m_referenceCount > 0);
+
+    //count the number of resulting coordinates
+    int numSrcCoords = 0;
+    int numDstCoords = 0;
+    for(int i=0;i<srcPath->m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(srcPath->m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+        numSrcCoords += coords;
+        switch(segment)
+        {
+        case VG_CLOSE_PATH:
+        case VG_MOVE_TO:
+        case VG_LINE_TO:
+            break;
+
+        case VG_HLINE_TO:
+        case VG_VLINE_TO:
+            coords = 2;
+            break;
+
+        case VG_QUAD_TO:
+        case VG_CUBIC_TO:
+        case VG_SQUAD_TO:
+        case VG_SCUBIC_TO:
+            coords = 6;
+            break;
+
+        default:
+            RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO ||
+                      segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO);
+            break;
+        }
+        numDstCoords += coords;
+    }
+
+    m_segments.resize(srcPath->m_segments.size());  //throws bad_alloc
+    m_data.resize(numDstCoords * getBytesPerCoordinate(VG_PATH_DATATYPE_F));    //throws bad_alloc
+
+    int srcCoord = 0;
+    int dstCoord = 0;
+    Vector2 s(0,0);     //the beginning of the current subpath
+    Vector2 o(0,0);     //the last point of the previous segment
+
+    // the last internal control point of the previous segment, if the
+    //segment was a (regular or smooth) quadratic or cubic
+    //Bezier, or else the last point of the previous segment
+    Vector2 p(0,0);     
+    for(int i=0;i<srcPath->m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(srcPath->m_segments[i]);
+        VGPathAbsRel absRel = getPathAbsRel(srcPath->m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+
+        switch(segment)
+        {
+        case VG_CLOSE_PATH:
+        {
+            RI_ASSERT(coords == 0);
+            p = s;
+            o = s;
+            break;
+        }
+
+        case VG_MOVE_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            if(absRel == VG_RELATIVE)
+                c += o;
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            s = c;
+            p = c;
+            o = c;
+            break;
+        }
+
+        case VG_LINE_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            if(absRel == VG_RELATIVE)
+                c += o;
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            p = c;
+            o = c;
+            break;
+        }
+
+        case VG_HLINE_TO:
+        {
+            RI_ASSERT(coords == 1);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), o.y);
+            if(absRel == VG_RELATIVE)
+                c.x += o.x;
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            p = c;
+            o = c;
+            segment = VG_LINE_TO;
+            break;
+        }
+
+        case VG_VLINE_TO:
+        {
+            RI_ASSERT(coords == 1);
+            Vector2 c(o.x, srcPath->getCoordinate(srcCoord+0));
+            if(absRel == VG_RELATIVE)
+                c.y += o.y;
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            p = c;
+            o = c;
+            segment = VG_LINE_TO;
+            break;
+        }
+
+        case VG_QUAD_TO:
+        {
+            RI_ASSERT(coords == 4);
+            Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            if(absRel == VG_RELATIVE)
+            {
+                c0 += o;
+                c1 += o;
+            }
+            Vector2 d0 = (1.0f/3.0f) * (o + 2.0f * c0);
+            Vector2 d1 = (1.0f/3.0f) * (c1 + 2.0f * c0);
+            setCoordinate(dstCoord++, d0.x);
+            setCoordinate(dstCoord++, d0.y);
+            setCoordinate(dstCoord++, d1.x);
+            setCoordinate(dstCoord++, d1.y);
+            setCoordinate(dstCoord++, c1.x);
+            setCoordinate(dstCoord++, c1.y);
+            p = c0;
+            o = c1;
+            segment = VG_CUBIC_TO;
+            break;
+        }
+
+        case VG_CUBIC_TO:
+        {
+            RI_ASSERT(coords == 6);
+            Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            Vector2 c2(srcPath->getCoordinate(srcCoord+4), srcPath->getCoordinate(srcCoord+5));
+            if(absRel == VG_RELATIVE)
+            {
+                c0 += o;
+                c1 += o;
+                c2 += o;
+            }
+            setCoordinate(dstCoord++, c0.x);
+            setCoordinate(dstCoord++, c0.y);
+            setCoordinate(dstCoord++, c1.x);
+            setCoordinate(dstCoord++, c1.y);
+            setCoordinate(dstCoord++, c2.x);
+            setCoordinate(dstCoord++, c2.y);
+            p = c1;
+            o = c2;
+            break;
+        }
+
+        case VG_SQUAD_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c0 = 2.0f * o - p;
+            Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            if(absRel == VG_RELATIVE)
+                c1 += o;
+            Vector2 d0 = (1.0f/3.0f) * (o + 2.0f * c0);
+            Vector2 d1 = (1.0f/3.0f) * (c1 + 2.0f * c0);
+            setCoordinate(dstCoord++, d0.x);
+            setCoordinate(dstCoord++, d0.y);
+            setCoordinate(dstCoord++, d1.x);
+            setCoordinate(dstCoord++, d1.y);
+            setCoordinate(dstCoord++, c1.x);
+            setCoordinate(dstCoord++, c1.y);
+            p = c0;
+            o = c1;
+            segment = VG_CUBIC_TO;
+            break;
+        }
+
+        case VG_SCUBIC_TO:
+        {
+            RI_ASSERT(coords == 4);
+            Vector2 c0 = 2.0f * o - p;
+            Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c2(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            if(absRel == VG_RELATIVE)
+            {
+                c1 += o;
+                c2 += o;
+            }
+            setCoordinate(dstCoord++, c0.x);
+            setCoordinate(dstCoord++, c0.y);
+            setCoordinate(dstCoord++, c1.x);
+            setCoordinate(dstCoord++, c1.y);
+            setCoordinate(dstCoord++, c2.x);
+            setCoordinate(dstCoord++, c2.y);
+            p = c1;
+            o = c2;
+            segment = VG_CUBIC_TO;
+            break;
+        }
+
+        default:
+        {
+            RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO ||
+                      segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO);
+            RI_ASSERT(coords == 5);
+            RIfloat rh = srcPath->getCoordinate(srcCoord+0);
+            RIfloat rv = srcPath->getCoordinate(srcCoord+1);
+            RIfloat rot = srcPath->getCoordinate(srcCoord+2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+3), srcPath->getCoordinate(srcCoord+4));
+            if(absRel == VG_RELATIVE)
+                c += o;
+            setCoordinate(dstCoord++, rh);
+            setCoordinate(dstCoord++, rv);
+            setCoordinate(dstCoord++, rot);
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            p = c;
+            o = c;
+            break;
+        }
+        }
+
+        m_segments[i] = (RIuint8)(segment | VG_ABSOLUTE);
+        srcCoord += coords;
+    }
+    RI_ASSERT(srcCoord == numSrcCoords);
+    RI_ASSERT(dstCoord == numDstCoords);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Appends a linearly interpolated copy of the two source paths.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+bool Path::interpolate(const Path* startPath, const Path* endPath, RIfloat amount)
+{
+    RI_ASSERT(startPath && endPath);
+    RI_ASSERT(m_referenceCount > 0 && startPath->m_referenceCount > 0 && endPath->m_referenceCount > 0);
+
+    if(!startPath->m_segments.size() || startPath->m_segments.size() != endPath->m_segments.size())
+        return false;   //start and end paths are incompatible or zero length
+
+    Path start(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F, 1.0f, 0.0f, 0, 0, 0);
+    start.normalizeForInterpolation(startPath); //throws bad_alloc
+
+    Path end(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F, 1.0f, 0.0f, 0, 0, 0);
+    end.normalizeForInterpolation(endPath); //throws bad_alloc
+
+    //check that start and end paths are compatible
+    if(start.m_data.size() != end.m_data.size() || start.m_segments.size() != end.m_segments.size())
+        return false;   //start and end paths are incompatible
+
+    //allocate new arrays
+    Array<RIuint8> newSegments;
+    newSegments.resize(m_segments.size() + start.m_segments.size());    //throws bad_alloc
+    Array<RIuint8> newData;
+    newData.resize(m_data.size() + start.m_data.size() * getBytesPerCoordinate(m_datatype) / getBytesPerCoordinate(start.m_datatype));  //throws bad_alloc
+    //if we get here, the memory allocations have succeeded
+
+    //copy old segments
+    if(m_segments.size())
+        ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+
+    //copy old data
+    if(m_data.size())
+        ri_memcpy(&newData[0], &m_data[0], m_data.size());
+
+    //copy segments
+    for(int i=0;i<start.m_segments.size();i++)
+    {
+        VGPathSegment s = getPathSegment(start.m_segments[i]);
+        VGPathSegment e = getPathSegment(end.m_segments[i]);
+
+        if(s == VG_SCCWARC_TO || s == VG_SCWARC_TO || s == VG_LCCWARC_TO || s == VG_LCWARC_TO)
+        {
+            if(e != VG_SCCWARC_TO && e != VG_SCWARC_TO && e != VG_LCCWARC_TO && e != VG_LCWARC_TO)
+                return false;   //start and end paths are incompatible
+            if(amount < 0.5f)
+                newSegments[m_segments.size() + i] = start.m_segments[i];
+            else
+                newSegments[m_segments.size() + i] = end.m_segments[i];
+        }
+        else
+        {
+            if(s != e)
+                return false;   //start and end paths are incompatible
+            newSegments[m_segments.size() + i] = start.m_segments[i];
+        }
+    }
+
+    //interpolate data
+    int oldNumCoords = getNumCoordinates();
+    for(int i=0;i<start.getNumCoordinates();i++)
+        setCoordinate(newData, m_datatype, m_scale, m_bias, oldNumCoords + i, start.getCoordinate(i) * (1.0f - amount) + end.getCoordinate(i) * amount);
+
+    RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype));
+
+    //replace old arrays
+    m_segments.swap(newSegments);
+    m_data.swap(newData);
+
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path for filling and appends resulting edges
+*           to a rasterizer.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::fill(const Matrix3x3& pathToSurface, Rasterizer& rasterizer)
+{
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(pathToSurface.isAffine());
+
+    tessellate(pathToSurface, 0.0f);    //throws bad_alloc
+
+    try
+    {
+        Vector2 p0(0,0), p1(0,0);
+        for(int i=0;i<m_vertices.size();i++)
+        {
+            p1 = affineTransform(pathToSurface, m_vertices[i].userPosition);
+
+            if(!(m_vertices[i].flags & START_SEGMENT))
+            {   //in the middle of a segment
+                rasterizer.addEdge(p0, p1); //throws bad_alloc
+            }
+
+            p0 = p1;
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        rasterizer.clear(); //remove the unfinished path
+        throw;
+    }
+}
+
+/**
+ *  \brief  Intersection between lines (p0->p1) and (p2->p3)
+ *  \todo   This must be done in the rasterizer to get correct results.
+ */
+static void intersectLines(const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3, Vector2& pt)
+{
+    RIfloat n = (p1.x-p0.x)*(p0.y-p2.y)-(p1.y-p0.y)*(p0.x-p2.x);
+    RIfloat d = (p3.y-p2.y)*(p1.x-p0.x)-(p3.x-p2.x)*(p1.y-p0.y);
+    if (d == 0) 
+    {
+        pt = p0;
+        return;
+    }
+    RIfloat t = n/d;
+    Vector2 dir = p1-p0;
+
+    pt = p0+t*dir;
+}
+
+static bool isCCW(const Vector2& a, const Vector2& b)
+{
+    RIfloat c = a.x*b.y - a.y*b.x;
+    return c >= 0;
+}
+
+/**
+ * \brief   Add a CCW stitch-triangle so that accw -> acw is the base of the triangle.
+ * \param   accw    Counter-clockwise stroke end (for example).
+ * \param   acw     Clockwise stroke end.
+ * \param   p       Tip of the triangle to form.
+ */
+static void addStitchTriangle(Rasterizer& rasterizer, const Vector2& accw, const Vector2& acw, const Vector2& p)
+{
+    if (isCCW(p - accw, acw - accw))
+    {
+        // p "below"
+        rasterizer.addEdge(accw, p);
+        rasterizer.addEdge(p, acw);
+        rasterizer.addEdge(acw, accw);
+    }
+    else
+    {
+        rasterizer.addEdge(accw, acw);
+        rasterizer.addEdge(acw, p);
+        rasterizer.addEdge(p, accw);
+    }
+}
+
+/**
+ * \brief   Add a (ccw-closed) segment to path. See the naming of parameters for input order:
+ *          pp = previous, nn = next
+ */
+static void addStrokeSegment(Rasterizer& rasterizer, const Vector2& ppccw, const Vector2& ppcw, const Vector2& nnccw, const Vector2& nncw)
+{
+    RIfloat d = dot(nnccw-ppccw, nncw-ppcw);
+    if(d < 0)
+    {
+        Vector2 ip;
+        intersectLines(ppccw, ppcw, nnccw, nncw, ip);
+
+        // Create two triangles from the self-intersecting part
+        if (isCCW(ppccw - nnccw, ip - nnccw))
+        {
+            rasterizer.addEdge(nnccw, ppccw);
+            rasterizer.addEdge(ppccw, ip);
+            rasterizer.addEdge(ip, nnccw);
+
+            rasterizer.addEdge(nncw, ppcw);
+            rasterizer.addEdge(ppcw, ip);
+            rasterizer.addEdge(ip, nncw);
+        }
+        else
+        {
+            rasterizer.addEdge(nnccw, ip);
+            rasterizer.addEdge(ip, ppccw);
+            rasterizer.addEdge(ppccw, nnccw);
+
+            rasterizer.addEdge(nncw, ip);
+            rasterizer.addEdge(ip, ppcw);
+            rasterizer.addEdge(ppcw, nncw);
+        }
+        // Final stitch (not necessary if done in the rasterizer)
+        addStitchTriangle(rasterizer, ppccw, ppcw, ip);
+        addStitchTriangle(rasterizer, nnccw, nncw, ip);
+    }
+    else
+    {
+        rasterizer.addEdge(ppccw, ppcw);	//throws bad_alloc
+        rasterizer.addEdge(ppcw, nncw);	//throws bad_alloc
+        rasterizer.addEdge(nncw, nnccw);		//throws bad_alloc
+        rasterizer.addEdge(nnccw, ppccw);	//throws bad_alloc
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Smoothly interpolates between two StrokeVertices. Positions
+*           are interpolated linearly, while tangents are interpolated
+*           on a unit circle. Stroking is implemented so that overlapping
+*           geometry doesnt cancel itself when filled with nonzero rule.
+*           The resulting polygons are closed.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::interpolateStroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth) const
+{
+    Vector2 ppccw, endccw;
+    Vector2 ppcw, endcw;
+    
+    if (m_mirror)
+    {
+        ppccw = affineTransform(pathToSurface, v0.cw);
+        ppcw = affineTransform(pathToSurface, v0.ccw);
+        endccw = affineTransform(pathToSurface, v1.cw);
+        endcw = affineTransform(pathToSurface, v1.ccw);
+    }
+    else
+    {
+        ppccw = affineTransform(pathToSurface, v0.ccw);
+        ppcw = affineTransform(pathToSurface, v0.cw);
+        endccw = affineTransform(pathToSurface, v1.ccw);
+        endcw = affineTransform(pathToSurface, v1.cw);
+    }
+
+	const RIfloat tessellationAngle = 5.0f;
+
+	RIfloat angle = RI_RAD_TO_DEG((RIfloat)acos(RI_CLAMP(dot(v0.t, v1.t), -1.0f, 1.0f))) / tessellationAngle;
+	int samples = RI_INT_MAX((int)ceil(angle), 1);
+	Vector2 prev = v0.p;
+	Vector2 prevt = v0.t;
+	Vector2 position = v0.p;
+	for(int j=0;j<samples-1;j++)
+	{
+		RIfloat t = (RIfloat)(j+1) / (RIfloat)samples;
+		position = v0.p * (1.0f - t) + v1.p * t;
+		Vector2 tangent = circularLerp(v0.t, v1.t, t);
+		Vector2 n = normalize(perpendicularCCW(tangent)) * strokeWidth * 0.5f;
+
+		Vector2 nnccw = affineTransform(pathToSurface, position + n);
+		Vector2 nncw = affineTransform(pathToSurface, position - n);
+
+        addStrokeSegment(rasterizer, ppccw, ppcw, nnccw, nncw);
+
+		ppccw = nnccw;
+		ppcw = nncw;
+		prev = position;
+		prevt = tangent;
+	}
+
+	//connect the last segment to the end coordinates
+	//Vector2 n = affineTangentTransform(pathToSurface, perpendicularCCW(v1.t));
+    Vector2 nncw = endcw;
+    Vector2 nnccw = endccw;
+
+    addStrokeSegment(rasterizer, ppccw, ppcw, nnccw, nncw);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Generate edges for stroke caps. Resulting polygons are closed.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::doCap(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v, RIfloat strokeWidth, VGCapStyle capStyle) const
+{
+    const bool mirror = m_mirror;
+    Vector2 ccwt, cwt, p;
+    if (mirror)
+    {
+        ccwt = affineTransform(pathToSurface, v.cw);
+        cwt = affineTransform(pathToSurface, v.ccw);
+        p = affineTransform(pathToSurface, v.p);
+    }
+    else
+    {
+        ccwt = affineTransform(pathToSurface, v.ccw);
+        cwt = affineTransform(pathToSurface, v.cw);
+        p = affineTransform(pathToSurface, v.p);
+    }
+
+    //rasterizer.clear();
+    switch(capStyle)
+    {
+    case VG_CAP_BUTT:
+        break;
+
+    case VG_CAP_ROUND:
+    {
+        const RIfloat tessellationAngle = 5.0f;
+
+        RIfloat angle = 180.0f / tessellationAngle;
+
+        int samples = (int)ceil(angle);
+        RIfloat step = 1.0f / samples;
+        RIfloat t = step;
+        Vector2 u0, u1;
+        if (!mirror)
+        {
+            u0 = normalize(v.cw - v.p);
+            u1 = normalize(v.ccw - v.p);
+        } else
+        {
+            u0 = normalize(v.ccw - v.p);
+            u1 = normalize(v.cw - v.p);
+        }
+        Vector2 prev = cwt;
+        rasterizer.addEdge(p, cwt);    //throws bad_alloc
+        for(int j=1;j<samples;j++)
+        {
+            Vector2 next = v.p + circularLerp(u0, u1, t, mirror) * strokeWidth * 0.5f;
+            next = affineTransform(pathToSurface, next);
+
+            rasterizer.addEdge(prev, next); //throws bad_alloc
+            prev = next;
+            t += step;
+        }
+        rasterizer.addEdge(prev, ccwt);  //throws bad_alloc
+        rasterizer.addEdge(ccwt, p);     //throws bad_alloc
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(capStyle == VG_CAP_SQUARE);
+        Vector2 t = v.t;
+        t.normalize();
+        Vector2 ccws, cws;
+        if (!mirror)
+        {
+            ccws = affineTransform(pathToSurface, v.ccw + t * strokeWidth * 0.5f);
+            cws = affineTransform(pathToSurface, v.cw + t * strokeWidth * 0.5f);
+        }
+        else
+        {
+            ccws = affineTransform(pathToSurface, v.cw + t * strokeWidth * 0.5f);
+            cws = affineTransform(pathToSurface, v.ccw + t * strokeWidth * 0.5f);
+        }
+        rasterizer.addEdge(p, cwt);    //throws bad_alloc
+        rasterizer.addEdge(cwt, cws); //throws bad_alloc
+        rasterizer.addEdge(cws, ccws);  //throws bad_alloc
+        rasterizer.addEdge(ccws, ccwt);   //throws bad_alloc
+        rasterizer.addEdge(ccwt, p);     //throws bad_alloc
+        break;
+    }
+    }
+    //rasterizer.fill();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Generate edges for stroke joins. Resulting polygons are closed.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::doJoin(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth, VGJoinStyle joinStyle, RIfloat miterLimit) const
+{
+    const bool mirror = m_mirror;
+    Vector2 ccw0t, ccw1t;
+    Vector2 cw0t, cw1t;
+    Vector2 m0t, m1t;
+    Vector2 tt0, tt1;
+
+    if(mirror)
+    {
+        ccw0t = affineTransform(pathToSurface, v0.cw);
+        cw0t = affineTransform(pathToSurface, v0.ccw);
+        m0t = affineTransform(pathToSurface, v0.p);
+        tt0 = affineTangentTransform(pathToSurface, v0.t);
+        ccw1t = affineTransform(pathToSurface, v1.cw);
+        cw1t = affineTransform(pathToSurface, v1.ccw);
+        m1t = affineTransform(pathToSurface, v1.p);
+        tt1 = affineTangentTransform(pathToSurface, v1.t);
+    } else
+    {
+        ccw0t = affineTransform(pathToSurface, v0.ccw);
+        cw0t = affineTransform(pathToSurface, v0.cw);
+        m0t = affineTransform(pathToSurface, v0.p);
+        tt0 = affineTangentTransform(pathToSurface, v0.t);
+        ccw1t = affineTransform(pathToSurface, v1.ccw);
+        cw1t = affineTransform(pathToSurface, v1.cw);
+        m1t = affineTransform(pathToSurface, v1.p);
+        tt1 = affineTangentTransform(pathToSurface, v1.t);
+    }
+
+    Vector2 tccw = v1.ccw - v0.ccw;
+    Vector2 s, e, m, st, et;
+    bool cw = true;
+
+    // \todo Uses addStrokeSegment, which is wasteful in several cases
+    // (but should be pretty robust)
+    // Round or miter to cw-side?
+    
+    if (dot(tt1, ccw0t - m0t) >= 0)
+        cw = false;
+        
+    // Add the bevel (which is part of all the other joins also)
+    // This would be a "consistent" way to handle joins (in addition
+    // to creating rounding to _both_ side of the join). However,
+    // the conformance test currently invalidates this case.
+    // \note Causes some extra geometry.
+    if (cw)
+        addStrokeSegment(rasterizer, ccw0t, m0t, ccw1t, m1t);
+    else
+        addStrokeSegment(rasterizer, m0t, cw0t, m1t, cw1t);
+
+    switch (joinStyle)
+    {
+    case VG_JOIN_BEVEL:
+        break;
+    case VG_JOIN_MITER:
+    {
+        RIfloat theta = (RIfloat)acos(RI_CLAMP(dot(v0.t, -v1.t), -1.0f, 1.0f));
+        RIfloat miterLengthPerStrokeWidth = 1.0f / (RIfloat)sin(theta*0.5f);
+        if (miterLengthPerStrokeWidth < miterLimit)
+        {   
+            // Miter
+            if (cw)
+            {
+                m = !mirror ? v0.ccw : v0.cw;
+                s = ccw1t;
+                e = ccw0t;
+            } else
+            {
+                m = !mirror ? v0.cw : v0.ccw;
+                s = cw0t;
+                e = cw1t;
+            }
+
+            RIfloat l = (RIfloat)cos(theta*0.5f) * miterLengthPerStrokeWidth * (strokeWidth * 0.5f);
+            l = RI_MIN(l, RI_FLOAT_MAX);    //force finite
+            Vector2 c = m + v0.t * l;
+            c = affineTransform(pathToSurface, c);
+
+            rasterizer.addEdge(s, c);
+            rasterizer.addEdge(c, e);
+            rasterizer.addEdge(e, s);
+        }
+        break;
+    }
+    default:
+    {
+        RI_ASSERT(joinStyle == VG_JOIN_ROUND);
+
+        Vector2 sp, ep;
+
+        const RIfloat tessellationAngle = 5.0f;
+            
+        if (cw)
+        {
+            s = ccw1t;
+            st = -v1.t;
+            e = ccw0t;
+            et = -v0.t;
+            sp = v1.p;
+            ep = v0.p;
+        } else
+        {
+            s = cw0t;
+            st = v0.t;
+            e = cw1t;
+            et = v1.t;
+            sp = v0.p;
+            ep = v1.p;
+        }
+
+        Vector2 prev = s;
+        RIfloat angle = RI_RAD_TO_DEG((RIfloat)acos(RI_CLAMP(dot(st, et), -1.0f, 1.0f))) / tessellationAngle;
+        int samples = (int)ceil(angle);
+        if( samples )
+        {
+            RIfloat step = 1.0f / samples;
+            RIfloat t = step;
+            for(int j=1;j<samples;j++)
+            {
+                Vector2 position = sp * (1.0f - t) + ep * t;
+                Vector2 tangent = circularLerp(st, et, t, mirror);
+
+                Vector2 next = position + normalize(perpendicular(tangent, !mirror)) * strokeWidth * 0.5f;
+                next = affineTransform(pathToSurface, next);
+
+                rasterizer.addEdge(prev, next); //throws bad_alloc
+                prev = next;
+                t += step;
+            }
+        }
+        rasterizer.addEdge(prev, e);    //throws bad_alloc
+        rasterizer.addEdge(e, s);
+        break;
+    }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellate a path, apply stroking, dashing, caps and joins, and
+*           append resulting edges to a rasterizer.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::stroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const Array<RIfloat>& dashPattern, RIfloat dashPhase, bool dashPhaseReset, RIfloat strokeWidth, VGCapStyle capStyle, VGJoinStyle joinStyle, RIfloat miterLimit)
+{
+    RI_ASSERT(pathToSurface.isAffine());
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(strokeWidth >= 0.0f);
+    RI_ASSERT(miterLimit >= 1.0f);
+
+    tessellate(pathToSurface, strokeWidth); //throws bad_alloc
+
+    m_mirror = pathToSurface[0][0]*pathToSurface[1][1] < 0 ? true : false;
+
+    if(!m_vertices.size())
+        return;
+
+    bool dashing = true;
+    int dashPatternSize = dashPattern.size();
+    if( dashPattern.size() & 1 )
+        dashPatternSize--;  //odd number of dash pattern entries, discard the last one
+    RIfloat dashPatternLength = 0.0f;
+    for(int i=0;i<dashPatternSize;i++)
+        dashPatternLength += RI_MAX(dashPattern[i], 0.0f);
+    if(!dashPatternSize || dashPatternLength == 0.0f )
+        dashing = false;
+    dashPatternLength = RI_MIN(dashPatternLength, RI_FLOAT_MAX);
+
+    //walk along the path
+    //stop at the next event which is either:
+    //-path vertex
+    //-dash stop
+    //for robustness, decisions based on geometry are done only once.
+    //inDash keeps track whether the last point was in dash or not
+
+    //loop vertex events
+    try
+    {
+        RIfloat nextDash = 0.0f;
+        int d = 0;
+        bool inDash = true;
+        StrokeVertex v0, v1, vs;
+        for(int i=0;i<m_vertices.size();i++)
+        {
+            //read the next vertex
+            Vertex& v = m_vertices[i];
+            v1.p = v.userPosition;
+            v1.t = v.userTangent;
+            RI_ASSERT(!isZero(v1.t));   //don't allow zero tangents
+
+            v1.ccw = v1.p + normalize(perpendicularCCW(v1.t)) * strokeWidth * 0.5f;
+            v1.cw = v1.p + normalize(perpendicularCW(v1.t)) * strokeWidth * 0.5f;
+
+            v1.pathLength = v.pathLength;
+            v1.flags = v.flags;
+            v1.inDash = dashing ? inDash : true;    //NOTE: for other than START_SEGMENT vertices inDash will be updated after dashing
+
+            //process the vertex event
+            if(v.flags & START_SEGMENT)
+            {
+                if(v.flags & START_SUBPATH)
+                {
+                    if( dashing )
+                    {   //initialize dashing by finding which dash or gap the first point of the path lies in
+                        if(dashPhaseReset || i == 0)
+                        {
+                            d = 0;
+                            inDash = true;
+                            nextDash = v1.pathLength - RI_MOD(dashPhase, dashPatternLength);
+                            for(;;)
+                            {
+                                RIfloat prevDash = nextDash;
+                                nextDash = prevDash + RI_MAX(dashPattern[d], 0.0f);
+                                if(nextDash >= v1.pathLength)
+                                    break;
+
+                                if( d & 1 )
+                                    inDash = true;
+                                else
+                                    inDash = false;
+                                d = (d+1) % dashPatternSize;
+                            }
+                            v1.inDash = inDash;
+                            //the first point of the path lies between prevDash and nextDash
+                            //d in the index of the next dash stop
+                            //inDash is true if the first point is in a dash
+                        }
+                    }
+                    vs = v1;    //save the subpath start point
+                }
+                else
+                {
+                    if( v.flags & IMPLICIT_CLOSE_SUBPATH )
+                    {   //do caps for the start and end of the current subpath
+                        if( v0.inDash )
+                            doCap(pathToSurface, rasterizer, v0, strokeWidth, capStyle);    //end cap   //throws bad_alloc
+                        if( vs.inDash )
+                        {
+                            StrokeVertex vi = vs;
+                            vi.t = -vi.t;
+                            RI_SWAP(vi.ccw.x, vi.cw.x);
+                            RI_SWAP(vi.ccw.y, vi.cw.y);
+                            doCap(pathToSurface, rasterizer, vi, strokeWidth, capStyle);    //start cap //throws bad_alloc
+                        }
+                    }
+                    else
+                    {   //join two segments
+                        RI_ASSERT(v0.inDash == v1.inDash);
+                        if( v0.inDash )
+                            doJoin(pathToSurface, rasterizer, v0, v1, strokeWidth, joinStyle, miterLimit);  //throws bad_alloc
+                    }
+                }
+            }
+            else
+            {   //in the middle of a segment
+                if( !(v.flags & IMPLICIT_CLOSE_SUBPATH) )
+                {   //normal segment, do stroking
+                    if( dashing )
+                    {
+                        StrokeVertex prevDashVertex = v0;   //dashing of the segment starts from the previous vertex
+
+                        if(nextDash + 10000.0f * dashPatternLength < v1.pathLength)
+                            throw std::bad_alloc();     //too many dashes, throw bad_alloc
+
+                        //loop dash events until the next vertex event
+                        //zero length dashes are handled as a special case since if they hit the vertex,
+                        //we want to include their starting point to this segment already in order to generate a join
+                        int numDashStops = 0;
+                        while(nextDash < v1.pathLength || (nextDash <= v1.pathLength && dashPattern[(d+1) % dashPatternSize] == 0.0f))
+                        {
+                            RIfloat edgeLength = v1.pathLength - v0.pathLength;
+                            RIfloat ratio = 0.0f;
+                            if(edgeLength > 0.0f)
+                                ratio = (nextDash - v0.pathLength) / edgeLength;
+                            StrokeVertex nextDashVertex;
+                            nextDashVertex.p = v0.p * (1.0f - ratio) + v1.p * ratio;
+                            nextDashVertex.t = circularLerp(v0.t, v1.t, ratio);
+                            nextDashVertex.ccw = nextDashVertex.p + normalize(perpendicularCCW(nextDashVertex.t)) * strokeWidth * 0.5f;
+                            nextDashVertex.cw = nextDashVertex.p + normalize(perpendicularCW(nextDashVertex.t)) * strokeWidth * 0.5f;
+
+                            if( inDash )
+                            {   //stroke from prevDashVertex -> nextDashVertex
+                                if( numDashStops )
+                                {   //prevDashVertex is not the start vertex of the segment, cap it (start vertex has already been joined or capped)
+                                    StrokeVertex vi = prevDashVertex;
+                                    vi.t = -vi.t;
+                                    RI_SWAP(vi.ccw.x, vi.cw.x);
+                                    RI_SWAP(vi.ccw.y, vi.cw.y);
+                                    doCap(pathToSurface, rasterizer, vi, strokeWidth, capStyle);    //throws bad_alloc
+                                }
+                                interpolateStroke(pathToSurface, rasterizer, prevDashVertex, nextDashVertex, strokeWidth);  //throws bad_alloc
+                                doCap(pathToSurface, rasterizer, nextDashVertex, strokeWidth, capStyle);    //end cap   //throws bad_alloc
+                            }
+                            prevDashVertex = nextDashVertex;
+
+                            if( d & 1 )
+                            {   //dash starts
+                                RI_ASSERT(!inDash);
+                                inDash = true;
+                            }
+                            else
+                            {   //dash ends
+                                RI_ASSERT(inDash);
+                                inDash = false;
+                            }
+                            d = (d+1) % dashPatternSize;
+                            nextDash += RI_MAX(dashPattern[d], 0.0f);
+                            numDashStops++;
+                        }
+                        
+                        if( inDash )
+                        {   //stroke prevDashVertex -> v1
+                            if( numDashStops )
+                            {   //prevDashVertex is not the start vertex of the segment, cap it (start vertex has already been joined or capped)
+                                StrokeVertex vi = prevDashVertex;
+                                vi.t = -vi.t;
+                                RI_SWAP(vi.ccw.x, vi.cw.x);
+                                RI_SWAP(vi.ccw.y, vi.cw.y);
+                                doCap(pathToSurface, rasterizer, vi, strokeWidth, capStyle);    //throws bad_alloc
+                            }
+                            interpolateStroke(pathToSurface, rasterizer, prevDashVertex, v1, strokeWidth);  //throws bad_alloc
+                            //no cap, leave path open
+                        }
+
+                        v1.inDash = inDash; //update inDash status of the segment end point
+                    }
+                    else    //no dashing, just interpolate segment end points
+                        interpolateStroke(pathToSurface, rasterizer, v0, v1, strokeWidth);  //throws bad_alloc
+                }
+            }
+
+            if((v.flags & END_SEGMENT) && (v.flags & CLOSE_SUBPATH))
+            {   //join start and end of the current subpath
+                if( v1.inDash && vs.inDash )
+                    doJoin(pathToSurface, rasterizer, v1, vs, strokeWidth, joinStyle, miterLimit);  //throws bad_alloc
+                else
+                {   //both start and end are not in dash, cap them
+                    if( v1.inDash )
+                        doCap(pathToSurface, rasterizer, v1, strokeWidth, capStyle);    //end cap   //throws bad_alloc
+                    if( vs.inDash )
+                    {
+                        StrokeVertex vi = vs;
+                        vi.t = -vi.t;
+                        RI_SWAP(vi.ccw.x, vi.cw.x);
+                        RI_SWAP(vi.ccw.y, vi.cw.y);
+                        doCap(pathToSurface, rasterizer, vi, strokeWidth, capStyle);    //start cap //throws bad_alloc
+                    }
+                }
+            }
+
+            v0 = v1;
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        rasterizer.clear(); //remove the unfinished path
+        throw;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path, and returns a position and a tangent on the path
+*           given a distance along the path.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::getPointAlong(int startIndex, int numSegments, RIfloat distance, Vector2& p, Vector2& t)
+{
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size() && numSegments > 0);
+
+    Matrix3x3 identity;
+    identity.identity();
+    tessellate(identity, 0.0f); //throws bad_alloc
+
+    RI_ASSERT(startIndex >= 0 && startIndex < m_segmentToVertex.size());
+    RI_ASSERT(startIndex + numSegments >= 0 && startIndex + numSegments <= m_segmentToVertex.size());
+
+    // ignore move segments at the start of the path
+    while (numSegments && (m_segments[startIndex] & ~VG_RELATIVE) == VG_MOVE_TO)
+    {
+        startIndex++;
+        numSegments--;
+    }
+
+    // ignore move segments at the end of the path
+    while (numSegments && (m_segments[startIndex + numSegments - 1] & ~VG_RELATIVE) == VG_MOVE_TO)
+        numSegments--;
+
+    // empty path?
+    if (!m_vertices.size() || !numSegments)
+    {
+        p.set(0,0);
+        t.set(1,0);
+        return;
+    }
+
+    int startVertex = m_segmentToVertex[startIndex].start;
+    int endVertex = m_segmentToVertex[startIndex + numSegments - 1].end;
+
+    if(startVertex == -1)
+        startVertex = 0;
+
+    // zero length?
+    if (startVertex >= endVertex)
+    {
+        p = m_vertices[startVertex].userPosition;
+        t.set(1,0);
+        return;
+    }
+
+    RI_ASSERT(startVertex >= 0 && startVertex < m_vertices.size());
+    RI_ASSERT(endVertex >= 0 && endVertex < m_vertices.size());
+
+    distance += m_vertices[startVertex].pathLength; //map distance to the range of the whole path
+
+    if(distance <= m_vertices[startVertex].pathLength)
+    {   //return the first point of the path
+        p = m_vertices[startVertex].userPosition;
+        t = m_vertices[startVertex].userTangent;
+        return;
+    }
+
+    if(distance >= m_vertices[endVertex].pathLength)
+    {   //return the last point of the path
+        p = m_vertices[endVertex].userPosition;
+        t = m_vertices[endVertex].userTangent;
+        return;
+    }
+
+    //search for the segment containing the distance
+    for(int s=startIndex;s<startIndex+numSegments;s++)
+    {
+        int start = m_segmentToVertex[s].start;
+        int end = m_segmentToVertex[s].end;
+        if(start < 0)
+            start = 0;
+        if(end < 0)
+            end = 0;
+        RI_ASSERT(start >= 0 && start < m_vertices.size());
+        RI_ASSERT(end >= 0 && end < m_vertices.size());
+
+        if(distance >= m_vertices[start].pathLength && distance < m_vertices[end].pathLength)
+        {   //segment contains the queried distance
+            for(int i=start;i<end;i++)
+            {
+                const Vertex& v0 = m_vertices[i];
+                const Vertex& v1 = m_vertices[i+1];
+                if(distance >= v0.pathLength && distance < v1.pathLength)
+                {   //segment found, interpolate linearly between its end points
+                    RIfloat edgeLength = v1.pathLength - v0.pathLength;
+                    RI_ASSERT(edgeLength > 0.0f);
+                    RIfloat r = (distance - v0.pathLength) / edgeLength;
+                    p = (1.0f - r) * v0.userPosition + r * v1.userPosition;
+                    t = (1.0f - r) * v0.userTangent + r * v1.userTangent;
+                    return;
+                }
+            }
+        }
+    }
+
+    RI_ASSERT(0);   //point not found (should never get here)
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path, and computes its length.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+RIfloat Path::getPathLength(int startIndex, int numSegments)
+{
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size() && numSegments > 0);
+
+    Matrix3x3 identity;
+    identity.identity();
+    tessellate(identity, 0.0f); //throws bad_alloc
+
+    RI_ASSERT(startIndex >= 0 && startIndex < m_segmentToVertex.size());
+    RI_ASSERT(startIndex + numSegments >= 0 && startIndex + numSegments <= m_segmentToVertex.size());
+
+    int startVertex = m_segmentToVertex[startIndex].start;
+    int endVertex = m_segmentToVertex[startIndex + numSegments - 1].end;
+
+    if(!m_vertices.size())
+        return 0.0f;
+
+    RIfloat startPathLength = 0.0f;
+    if(startVertex >= 0)
+    {
+        RI_ASSERT(startVertex >= 0 && startVertex < m_vertices.size());
+        startPathLength = m_vertices[startVertex].pathLength;
+    }
+    RIfloat endPathLength = 0.0f;
+    if(endVertex >= 0)
+    {
+        RI_ASSERT(endVertex >= 0 && endVertex < m_vertices.size());
+        endPathLength = m_vertices[endVertex].pathLength;
+    }
+
+    return endPathLength - startPathLength;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path, and computes its bounding box in user space.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::getPathBounds(RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy)
+{
+    RI_ASSERT(m_referenceCount > 0);
+
+    Matrix3x3 identity;
+    identity.identity();
+    tessellate(identity, 0.0f); //throws bad_alloc
+
+    if(m_vertices.size())
+    {
+        minx = m_userMinx;
+        miny = m_userMiny;
+        maxx = m_userMaxx;
+        maxy = m_userMaxy;
+    }
+    else
+    {
+        minx = miny = 0;
+        maxx = maxy = -1;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path, and computes its bounding box in surface space.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::getPathTransformedBounds(const Matrix3x3& pathToSurface, RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy)
+{
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(pathToSurface.isAffine());
+
+    Matrix3x3 identity;
+    identity.identity();
+    tessellate(identity, 0.0f); //throws bad_alloc
+
+    if(m_vertices.size())
+    {
+        Vector3 p0(m_userMinx, m_userMiny, 1.0f);
+        Vector3 p1(m_userMinx, m_userMaxy, 1.0f);
+        Vector3 p2(m_userMaxx, m_userMaxy, 1.0f);
+        Vector3 p3(m_userMaxx, m_userMiny, 1.0f);
+        p0 = pathToSurface * p0;
+        p1 = pathToSurface * p1;
+        p2 = pathToSurface * p2;
+        p3 = pathToSurface * p3;
+
+        minx = RI_MIN(RI_MIN(RI_MIN(p0.x, p1.x), p2.x), p3.x);
+        miny = RI_MIN(RI_MIN(RI_MIN(p0.y, p1.y), p2.y), p3.y);
+        maxx = RI_MAX(RI_MAX(RI_MAX(p0.x, p1.x), p2.x), p3.x);
+        maxy = RI_MAX(RI_MAX(RI_MAX(p0.y, p1.y), p2.y), p3.y);
+    }
+    else
+    {
+        minx = miny = 0;
+        maxx = maxy = -1;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Adds a vertex to a tessellated path.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::addVertex(const Vector2& p, const Vector2& t, RIfloat pathLength, unsigned int flags)
+{
+    RI_ASSERT(!isZero(t));
+
+    Vertex v;
+    v.pathLength = pathLength;
+    v.userPosition = p;
+    v.userTangent = t;
+    v.flags = flags;
+    m_vertices.push_back(v);    //throws bad_alloc
+    m_numTessVertices++;
+
+    m_userMinx = RI_MIN(m_userMinx, v.userPosition.x);
+    m_userMiny = RI_MIN(m_userMiny, v.userPosition.y);
+    m_userMaxx = RI_MAX(m_userMaxx, v.userPosition.x);
+    m_userMaxy = RI_MAX(m_userMaxy, v.userPosition.y);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Adds an edge to a tessellated path.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::addEdge(const Vector2& p0, const Vector2& p1, const Vector2& t0, const Vector2& t1, unsigned int startFlags, unsigned int endFlags)
+{
+    Vertex v;
+    RIfloat pathLength = 0.0f;
+
+    RI_ASSERT(!isZero(t0) && !isZero(t1));
+
+    //segment midpoints are shared between edges
+    if(!m_numTessVertices)
+    {
+        if(m_vertices.size() > 0)
+            pathLength = m_vertices[m_vertices.size()-1].pathLength;
+
+        addVertex(p0, t0, pathLength, startFlags);  //throws bad_alloc
+    }
+
+    //other than implicit close paths (caused by a MOVE_TO) add to path length
+    if( !(endFlags & IMPLICIT_CLOSE_SUBPATH) )
+    {
+        //NOTE: with extremely large coordinates the floating point path length is infinite
+        RIfloat l = (p1 - p0).length();
+        pathLength = m_vertices[m_vertices.size()-1].pathLength + l;
+        pathLength = RI_MIN(pathLength, RI_FLOAT_MAX);
+    }
+
+    addVertex(p1, t1, pathLength, endFlags);    //throws bad_alloc
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a close-path segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::addEndPath(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry, unsigned int flags)
+{
+    RI_UNREF(pathToSurface);
+    m_numTessVertices = 0;
+    if(!subpathHasGeometry)
+    {   //single vertex
+        Vector2 t(1.0f,0.0f);
+        addEdge(p0, p1, t, t, START_SEGMENT | START_SUBPATH, END_SEGMENT | END_SUBPATH);    //throws bad_alloc
+        m_numTessVertices = 0;
+        addEdge(p0, p1, -t, -t, IMPLICIT_CLOSE_SUBPATH | START_SEGMENT, IMPLICIT_CLOSE_SUBPATH | END_SEGMENT);  //throws bad_alloc
+        return;
+    }
+    //the subpath contains segment commands that have generated geometry
+
+    //add a close path segment to the start point of the subpath
+    RI_ASSERT(m_vertices.size() > 0);
+    m_vertices[m_vertices.size()-1].flags |= END_SUBPATH;
+
+    Vector2 t = normalize(p1 - p0);
+    if(isZero(t))
+        t = m_vertices[m_vertices.size()-1].userTangent;    //if the segment is zero-length, use the tangent of the last segment end point so that proper join will be generated
+    RI_ASSERT(!isZero(t));
+
+    addEdge(p0, p1, t, t, flags | START_SEGMENT, flags | END_SEGMENT);  //throws bad_alloc
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a line-to segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+bool Path::addLineTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry)
+{
+    RI_UNREF(pathToSurface);
+    if(p0 == p1)
+        return false;   //discard zero-length segments
+
+    //compute end point tangents
+    Vector2 t = normalize(p1 - p0);
+    RI_ASSERT(!isZero(t));
+
+    m_numTessVertices = 0;
+    unsigned int startFlags = START_SEGMENT;
+    if(!subpathHasGeometry)
+        startFlags |= START_SUBPATH;
+    addEdge(p0, p1, t, t, startFlags, END_SEGMENT); //throws bad_alloc
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a quad-to segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+bool Path::addQuadTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, bool subpathHasGeometry, float strokeWidth)
+{
+    RI_UNREF(pathToSurface);
+    RI_UNREF(strokeWidth);
+    if(p0 == p1 && p0 == p2)
+    {
+        RI_ASSERT(p1 == p2);
+        return false;   //discard zero-length segments
+    }
+
+    //compute end point tangents
+
+    Vector2 incomingTangent = normalize(p1 - p0);
+    Vector2 outgoingTangent = normalize(p2 - p1);
+    if(p0 == p1)
+        incomingTangent = normalize(p2 - p0);
+    if(p1 == p2)
+        outgoingTangent = normalize(p2 - p0);
+    RI_ASSERT(!isZero(incomingTangent) && !isZero(outgoingTangent));
+
+    m_numTessVertices = 0;
+    unsigned int startFlags = START_SEGMENT;
+    if(!subpathHasGeometry)
+        startFlags |= START_SUBPATH;
+
+    const int segments = RI_NUM_TESSELLATED_SEGMENTS_QUAD;
+    Vector2 pp = p0;
+    Vector2 tp = incomingTangent;
+    unsigned int prevFlags = startFlags;
+    for(int i=1;i<segments;i++)
+    {
+        RIfloat t = (RIfloat)i / (RIfloat)segments;
+        RIfloat u = 1.0f-t;
+        Vector2 pn = u*u * p0 + 2.0f*t*u * p1 + t*t * p2;
+        Vector2 tn = (-1.0f+t) * p0 + (1.0f-2.0f*t) * p1 + t * p2;
+        tn = normalize(tn);
+        if(isZero(tn))
+            tn = tp;
+
+        addEdge(pp, pn, tp, tn, prevFlags, 0);  //throws bad_alloc
+
+        pp = pn;
+        tp = tn;
+        prevFlags = 0;
+    }
+    addEdge(pp, p2, tp, outgoingTangent, prevFlags, END_SEGMENT);   //throws bad_alloc
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a cubic-to segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+bool Path::addCubicTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3, bool subpathHasGeometry, float strokeWidth)
+{
+    RI_UNREF(pathToSurface);
+    RI_UNREF(strokeWidth);
+
+    if(p0 == p1 && p0 == p2 && p0 == p3)
+    {
+        RI_ASSERT(p1 == p2 && p1 == p3 && p2 == p3);
+        return false;   //discard zero-length segments
+    }
+
+    //compute end point tangents
+    Vector2 incomingTangent = normalize(p1 - p0);
+    Vector2 outgoingTangent = normalize(p3 - p2);
+    if(p0 == p1)
+    {
+        incomingTangent = normalize(p2 - p0);
+        if(p1 == p2)
+            incomingTangent = normalize(p3 - p0);
+    }
+    if(p2 == p3)
+    {
+        outgoingTangent = normalize(p3 - p1);
+        if(p1 == p2)
+            outgoingTangent = normalize(p3 - p0);
+    }
+    RI_ASSERT(!isZero(incomingTangent) && !isZero(outgoingTangent));
+
+    m_numTessVertices = 0;
+    unsigned int startFlags = START_SEGMENT;
+    if(!subpathHasGeometry)
+        startFlags |= START_SUBPATH;
+
+    const int segments = RI_NUM_TESSELLATED_SEGMENTS_CUBIC;
+    Vector2 pp = p0;
+    Vector2 tp = incomingTangent;
+    unsigned int prevFlags = startFlags;
+    for(int i=1;i<segments;i++)
+    {
+        RIfloat t = (RIfloat)i / (RIfloat)segments;
+        Vector2 pn = (1.0f - 3.0f*t + 3.0f*t*t - t*t*t) * p0 + (3.0f*t - 6.0f*t*t + 3.0f*t*t*t) * p1 + (3.0f*t*t - 3.0f*t*t*t) * p2 + t*t*t * p3;
+        Vector2 tn = (-3.0f + 6.0f*t - 3.0f*t*t) * p0 + (3.0f - 12.0f*t + 9.0f*t*t) * p1 + (6.0f*t - 9.0f*t*t) * p2 + 3.0f*t*t * p3;
+
+        tn = normalize(tn);
+        if(isZero(tn))
+            tn = tp;
+
+        addEdge(pp, pn, tp, tn, prevFlags, 0);  //throws bad_alloc
+
+        pp = pn;
+        tp = tn;
+        prevFlags = 0;
+    }
+    addEdge(pp, p3, tp, outgoingTangent, prevFlags, END_SEGMENT);   //throws bad_alloc
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Finds an ellipse center and transformation from the unit circle to
+*           that ellipse.
+* \param    rh Length of the horizontal axis
+*           rv Length of the vertical axis
+*           rot Rotation angle
+*           p0,p1 User space end points of the arc
+*           c0,c1 (Return value) Unit circle space center points of the two ellipses
+*           u0,u1 (Return value) Unit circle space end points of the arc
+*           unitCircleToEllipse (Return value) A matrix mapping from unit circle space to user space
+* \return   true if ellipse exists, false if doesn't
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static bool findEllipses(RIfloat rh, RIfloat rv, RIfloat rot, const Vector2& p0, const Vector2& p1, VGPathSegment segment, Vector2& c0, Vector2& c1, Vector2& u0, Vector2& u1, Matrix3x3& unitCircleToEllipse, bool& cw)
+{
+    rh = RI_ABS(rh);
+    rv = RI_ABS(rv);
+    if(rh == 0.0f || rv == 0.0f || p0 == p1)
+        return false;   //degenerate ellipse
+
+    rot = RI_DEG_TO_RAD(rot);
+    unitCircleToEllipse.set((RIfloat)cos(rot)*rh, -(RIfloat)sin(rot)*rv,  0,
+                            (RIfloat)sin(rot)*rh,  (RIfloat)cos(rot)*rv,  0,
+                            0,                   0,                   1);
+    Matrix3x3 ellipseToUnitCircle = invert(unitCircleToEllipse);
+    //force affinity
+    ellipseToUnitCircle[2][0] = 0.0f;
+    ellipseToUnitCircle[2][1] = 0.0f;
+    ellipseToUnitCircle[2][2] = 1.0f;
+
+    // Transform p0 and p1 into unit space
+    u0 = affineTransform(ellipseToUnitCircle, p0);
+    u1 = affineTransform(ellipseToUnitCircle, p1);
+
+    Vector2 m = 0.5f * (u0 + u1);
+    Vector2 d = u0 - u1;
+
+    RIfloat lsq = (RIfloat)dot(d,d);
+    if(lsq <= 0.0f)
+        return false;   //the points are coincident
+
+    RIfloat disc = (1.0f / lsq) - 0.25f;
+    if(disc < 0.0f)
+    {   //the points are too far apart for a solution to exist, scale the axes so that there is a solution
+        RIfloat l = (RIfloat)sqrt(lsq);
+        rh *= 0.5f * l;
+        rv *= 0.5f * l;
+
+        //redo the computation with scaled axes
+        unitCircleToEllipse.set((RIfloat)cos(rot)*rh, -(RIfloat)sin(rot)*rv,  0,
+                                (RIfloat)sin(rot)*rh,  (RIfloat)cos(rot)*rv,  0,
+                                0,                   0,                   1);
+        ellipseToUnitCircle = invert(unitCircleToEllipse);
+        //force affinity
+        ellipseToUnitCircle[2][0] = 0.0f;
+        ellipseToUnitCircle[2][1] = 0.0f;
+        ellipseToUnitCircle[2][2] = 1.0f;
+
+        // Transform p0 and p1 into unit space
+        u0 = affineTransform(ellipseToUnitCircle, p0);
+        u1 = affineTransform(ellipseToUnitCircle, p1);
+
+        // Solve for intersecting unit circles
+        d = u0 - u1;
+        m = 0.5f * (u0 + u1);
+
+        lsq = dot(d,d);
+        if(lsq <= 0.0f)
+            return false;   //the points are coincident
+
+        disc = RI_MAX(0.0f, 1.0f / lsq - 0.25f);
+    }
+
+    if(u0 == u1)
+        return false;
+
+    Vector2 sd = d * (RIfloat)sqrt(disc);
+    Vector2 sp = perpendicularCW(sd);
+    c0 = m + sp;
+    c1 = m - sp;
+
+    //choose the center point and direction
+    Vector2 cp = c0;
+    if(segment == VG_SCWARC_TO || segment == VG_LCCWARC_TO)
+        cp = c1;
+    cw = false;
+    if(segment == VG_SCWARC_TO || segment == VG_LCWARC_TO)
+        cw = true;
+
+    //move the unit circle origin to the chosen center point
+    u0 -= cp;
+    u1 -= cp;
+
+    if(u0 == u1 || isZero(u0) || isZero(u1))
+        return false;
+
+    //transform back to the original coordinate space
+    cp = affineTransform(unitCircleToEllipse, cp);
+    unitCircleToEllipse[0][2] = cp.x;
+    unitCircleToEllipse[1][2] = cp.y;
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates an arc-to segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+bool Path::addArcTo(const Matrix3x3& pathToSurface, const Vector2& p0, RIfloat rh, RIfloat rv, RIfloat rot, const Vector2& p1, const Vector2& p1r, VGPathSegment segment, bool subpathHasGeometry, float strokeWidth)
+{
+    RI_UNREF(pathToSurface);
+    RI_UNREF(strokeWidth);
+
+    if(p0 == p1)
+        return false;   //discard zero-length segments
+    
+    // Check NaNs
+    // \todo Make a general vec2 function?
+    if (RI_ISNAN(p0.x) || RI_ISNAN(p0.y))
+        return false;
+
+    if (RI_ISNAN(p1.x) || RI_ISNAN(p1.y))
+        return false;
+
+    Vector2 c0, c1, u0, u1;
+    Matrix3x3 unitCircleToEllipse;
+    bool cw;
+
+    m_numTessVertices = 0;
+    unsigned int startFlags = START_SEGMENT;
+    if(!subpathHasGeometry)
+        startFlags |= START_SUBPATH;
+
+    if(!findEllipses(rh, rv, rot, Vector2(), p1r, segment, c0, c1, u0, u1, unitCircleToEllipse, cw))
+    {   //ellipses don't exist, add line instead
+        Vector2 t = normalize(p1r);
+        RI_ASSERT(!isZero(t));
+        addEdge(p0, p1, t, t, startFlags, END_SEGMENT); //throws bad_alloc
+        return true;
+    }
+
+    //compute end point tangents
+    Vector2 incomingTangent = perpendicular(u0, cw);
+    incomingTangent = affineTangentTransform(unitCircleToEllipse, incomingTangent);
+    incomingTangent = normalize(incomingTangent);
+    Vector2 outgoingTangent = perpendicular(u1, cw);
+    outgoingTangent = affineTangentTransform(unitCircleToEllipse, outgoingTangent);
+    outgoingTangent = normalize(outgoingTangent);
+    RI_ASSERT(!isZero(incomingTangent) && !isZero(outgoingTangent));
+
+    const int segments = RI_NUM_TESSELLATED_SEGMENTS_ARC;
+    Vector2 pp = p0;
+    Vector2 tp = incomingTangent;
+    unsigned int prevFlags = startFlags;
+    for(int i=1;i<segments;i++)
+    {
+        RIfloat t = (RIfloat)i / (RIfloat)segments;
+        Vector2 pn = circularLerp(u0, u1, t, cw);
+        Vector2 tn = perpendicular(pn, cw);
+        tn = affineTangentTransform(unitCircleToEllipse, tn);
+        pn = affineTransform(unitCircleToEllipse, pn) + p0;
+        tn = normalize(tn);
+        if(isZero(tn))
+            tn = tp;
+
+        addEdge(pp, pn, tp, tn, prevFlags, 0);  //throws bad_alloc
+
+        pp = pn;
+        tp = tn;
+        prevFlags = 0;
+    }
+    addEdge(pp, p1, tp, outgoingTangent, prevFlags, END_SEGMENT);   //throws bad_alloc
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path.
+* \param    
+* \return   
+* \note     tessellation output format: A list of vertices describing the
+*           path tessellated into line segments and relevant aspects of the
+*           input data. Each path segment has a start vertex, a number of
+*           internal vertices (possibly zero), and an end vertex. The start
+*           and end of segments and subpaths have been flagged, as well as
+*           implicit and explicit close subpath segments.
+*//*-------------------------------------------------------------------*/
+
+void Path::tessellate(const Matrix3x3& pathToSurface, float strokeWidth)
+{
+    m_vertices.clear();
+
+    m_userMinx = RI_FLOAT_MAX;
+    m_userMiny = RI_FLOAT_MAX;
+    m_userMaxx = -RI_FLOAT_MAX;
+    m_userMaxy = -RI_FLOAT_MAX;
+    
+    try
+    {
+        m_segmentToVertex.resize(m_segments.size());
+
+        int coordIndex = 0;
+        Vector2 s(0,0);     //the beginning of the current subpath
+        Vector2 o(0,0);     //the last point of the previous segment
+        Vector2 p(0,0);     //the last internal control point of the previous segment, if the segment was a (regular or smooth) quadratic or cubic Bezier, or else the last point of the previous segment
+
+        //tessellate the path segments
+        coordIndex = 0;
+        s.set(0,0);
+        o.set(0,0);
+        p.set(0,0);
+        bool subpathHasGeometry = false;
+        VGPathSegment prevSegment = VG_MOVE_TO;
+        for(int i=0;i<m_segments.size();i++)
+        {
+            VGPathSegment segment = getPathSegment(m_segments[i]);
+            VGPathAbsRel absRel = getPathAbsRel(m_segments[i]);
+            int coords = segmentToNumCoordinates(segment);
+            m_segmentToVertex[i].start = m_vertices.size();
+
+            switch(segment)
+            {
+            case VG_CLOSE_PATH:
+            {
+                RI_ASSERT(coords == 0);
+                addEndPath(pathToSurface, o, s, subpathHasGeometry, CLOSE_SUBPATH);
+                p = s;
+                o = s;
+                subpathHasGeometry = false;
+                break;
+            }
+
+            case VG_MOVE_TO:
+            {
+                RI_ASSERT(coords == 2);
+                Vector2 c(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                if(absRel == VG_RELATIVE)
+                    c += o;
+                if(prevSegment != VG_MOVE_TO && prevSegment != VG_CLOSE_PATH)
+                    addEndPath(pathToSurface, o, s, subpathHasGeometry, IMPLICIT_CLOSE_SUBPATH);
+                s = c;
+                p = c;
+                o = c;
+                subpathHasGeometry = false;
+                break;
+            }
+
+            case VG_LINE_TO:
+            {
+                RI_ASSERT(coords == 2);
+                Vector2 c(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                if(absRel == VG_RELATIVE)
+                    c += o;
+                if(addLineTo(pathToSurface, o, c, subpathHasGeometry))
+                    subpathHasGeometry = true;
+                p = c;
+                o = c;
+                break;
+            }
+
+            case VG_HLINE_TO:
+            {
+                RI_ASSERT(coords == 1);
+                Vector2 c(getCoordinate(coordIndex+0), o.y);
+                if(absRel == VG_RELATIVE)
+                    c.x += o.x;
+                if(addLineTo(pathToSurface, o, c, subpathHasGeometry))
+                    subpathHasGeometry = true;
+                p = c;
+                o = c;
+                break;
+            }
+
+            case VG_VLINE_TO:
+            {
+                RI_ASSERT(coords == 1);
+                Vector2 c(o.x, getCoordinate(coordIndex+0));
+                if(absRel == VG_RELATIVE)
+                    c.y += o.y;
+                if(addLineTo(pathToSurface, o, c, subpathHasGeometry))
+                    subpathHasGeometry = true;
+                p = c;
+                o = c;
+                break;
+            }
+
+            case VG_QUAD_TO:
+            {
+                RI_ASSERT(coords == 4);
+                Vector2 c0(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                Vector2 c1(getCoordinate(coordIndex+2), getCoordinate(coordIndex+3));
+                if(absRel == VG_RELATIVE)
+                {
+                    c0 += o;
+                    c1 += o;
+                }
+                if(addQuadTo(pathToSurface, o, c0, c1, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c0;
+                o = c1;
+                break;
+            }
+
+            case VG_SQUAD_TO:
+            {
+                RI_ASSERT(coords == 2);
+                Vector2 c0 = 2.0f * o - p;
+                Vector2 c1(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                if(absRel == VG_RELATIVE)
+                    c1 += o;
+                if(addQuadTo(pathToSurface, o, c0, c1, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c0;
+                o = c1;
+                break;
+            }
+
+            case VG_CUBIC_TO:
+            {
+                RI_ASSERT(coords == 6);
+                Vector2 c0(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                Vector2 c1(getCoordinate(coordIndex+2), getCoordinate(coordIndex+3));
+                Vector2 c2(getCoordinate(coordIndex+4), getCoordinate(coordIndex+5));
+                if(absRel == VG_RELATIVE)
+                {
+                    c0 += o;
+                    c1 += o;
+                    c2 += o;
+                }
+                if(addCubicTo(pathToSurface, o, c0, c1, c2, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c1;
+                o = c2;
+                break;
+            }
+
+            case VG_SCUBIC_TO:
+            {
+                RI_ASSERT(coords == 4);
+                Vector2 c0 = 2.0f * o - p;
+                Vector2 c1(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                Vector2 c2(getCoordinate(coordIndex+2), getCoordinate(coordIndex+3));
+                if(absRel == VG_RELATIVE)
+                {
+                    c1 += o;
+                    c2 += o;
+                }
+                if(addCubicTo(pathToSurface, o, c0, c1, c2, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c1;
+                o = c2;
+                break;
+            }
+
+            default:
+            {
+                RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO ||
+                          segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO);
+                RI_ASSERT(coords == 5);
+                RIfloat rh = getCoordinate(coordIndex+0);
+                RIfloat rv = getCoordinate(coordIndex+1);
+                RIfloat rot = getCoordinate(coordIndex+2);
+                Vector2 c(getCoordinate(coordIndex+3), getCoordinate(coordIndex+4));
+
+                Vector2 cr = c;
+                if(absRel == VG_ABSOLUTE)
+                    cr -= o;
+                else
+                    c += o;
+
+                if(addArcTo(pathToSurface, o, rh, rv, rot, c, cr, segment, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c;
+                o = c;
+                break;
+            }
+            }
+
+            if(m_vertices.size() > m_segmentToVertex[i].start)
+            {   //segment produced vertices
+                m_segmentToVertex[i].end = m_vertices.size() - 1;
+            }
+            else
+            {   //segment didn't produce vertices (zero-length segment). Ignore it.
+                m_segmentToVertex[i].start = m_segmentToVertex[i].end = m_vertices.size()-1;
+            }
+            prevSegment = segment;
+            coordIndex += coords;
+        }
+
+        //add an implicit MOVE_TO to the end to close the last subpath.
+        //if the subpath contained only zero-length segments, this produces the necessary geometry to get it stroked
+        // and included in path bounds. The geometry won't be included in the pointAlongPath query.
+        if(prevSegment != VG_MOVE_TO && prevSegment != VG_CLOSE_PATH)
+            addEndPath(pathToSurface, o, s, subpathHasGeometry, IMPLICIT_CLOSE_SUBPATH);
+
+        //check that the flags are correct
+#ifdef RI_DEBUG
+        int prev = -1;
+        bool subpathStarted = false;
+        bool segmentStarted = false;
+        for(int i=0;i<m_vertices.size();i++)
+        {
+            Vertex& v = m_vertices[i];
+
+            if(v.flags & START_SUBPATH)
+            {
+                RI_ASSERT(!subpathStarted);
+                RI_ASSERT(v.flags & START_SEGMENT);
+                RI_ASSERT(!(v.flags & END_SUBPATH));
+                RI_ASSERT(!(v.flags & END_SEGMENT));
+                RI_ASSERT(!(v.flags & CLOSE_SUBPATH));
+                RI_ASSERT(!(v.flags & IMPLICIT_CLOSE_SUBPATH));
+                subpathStarted = true;
+            }
+            
+            if(v.flags & START_SEGMENT)
+            {
+                RI_ASSERT(subpathStarted || (v.flags & CLOSE_SUBPATH) || (v.flags & IMPLICIT_CLOSE_SUBPATH));
+                RI_ASSERT(!segmentStarted);
+                RI_ASSERT(!(v.flags & END_SUBPATH));
+                RI_ASSERT(!(v.flags & END_SEGMENT));
+                segmentStarted = true;
+            }
+            
+            if( v.flags & CLOSE_SUBPATH )
+            {
+                RI_ASSERT(segmentStarted);
+                RI_ASSERT(!subpathStarted);
+                RI_ASSERT((v.flags & START_SEGMENT) || (v.flags & END_SEGMENT));
+                RI_ASSERT(!(v.flags & IMPLICIT_CLOSE_SUBPATH));
+                RI_ASSERT(!(v.flags & START_SUBPATH));
+                RI_ASSERT(!(v.flags & END_SUBPATH));
+            }
+            if( v.flags & IMPLICIT_CLOSE_SUBPATH )
+            {
+                RI_ASSERT(segmentStarted);
+                RI_ASSERT(!subpathStarted);
+                RI_ASSERT((v.flags & START_SEGMENT) || (v.flags & END_SEGMENT));
+                RI_ASSERT(!(v.flags & CLOSE_SUBPATH));
+                RI_ASSERT(!(v.flags & START_SUBPATH));
+                RI_ASSERT(!(v.flags & END_SUBPATH));
+            }
+            
+            if( prev >= 0 )
+            {
+                RI_ASSERT(segmentStarted);
+                RI_ASSERT(subpathStarted || ((m_vertices[prev].flags & CLOSE_SUBPATH) && (m_vertices[i].flags & CLOSE_SUBPATH)) ||
+                          ((m_vertices[prev].flags & IMPLICIT_CLOSE_SUBPATH) && (m_vertices[i].flags & IMPLICIT_CLOSE_SUBPATH)));
+            }
+
+            prev = i;
+            if(v.flags & END_SEGMENT)
+            {
+                RI_ASSERT(subpathStarted || (v.flags & CLOSE_SUBPATH) || (v.flags & IMPLICIT_CLOSE_SUBPATH));
+                RI_ASSERT(segmentStarted);
+                RI_ASSERT(!(v.flags & START_SUBPATH));
+                RI_ASSERT(!(v.flags & START_SEGMENT));
+                segmentStarted = false;
+                prev = -1;
+            }
+            
+            if(v.flags & END_SUBPATH)
+            {
+                RI_ASSERT(subpathStarted);
+                RI_ASSERT(v.flags & END_SEGMENT);
+                RI_ASSERT(!(v.flags & START_SUBPATH));
+                RI_ASSERT(!(v.flags & START_SEGMENT));
+                RI_ASSERT(!(v.flags & CLOSE_SUBPATH));
+                RI_ASSERT(!(v.flags & IMPLICIT_CLOSE_SUBPATH));
+                subpathStarted = false;
+            }
+        }
+#endif  //RI_DEBUG
+    }
+    catch(std::bad_alloc)
+    {
+        m_vertices.clear();
+        throw;
+    }
+}
+
+//==============================================================================================
+
+}       //namespace OpenVGRI
+
+//==============================================================================================
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riPath.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,192 @@
+#ifndef __RIPATH_H
+#define __RIPATH_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Path class.
+ * \note	
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _OPENVG_H
+#include "openvg.h"
+#endif
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#ifndef __RIRASTERIZER_H
+#include "riRasterizer.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Storage and operations for VGPath.
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+class Path
+{
+public:
+	Path(VGint format, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int segmentCapacityHint, int coordCapacityHint, VGbitfield caps);	//throws bad_alloc
+	~Path();
+
+	VGint				getFormat() const						{ return m_format; }
+	VGPathDatatype		getDatatype() const						{ return m_datatype; }
+	RIfloat				getScale() const						{ return m_scale; }
+	RIfloat				getBias() const							{ return m_bias; }
+	VGbitfield			getCapabilities() const					{ return m_capabilities; }
+	void				setCapabilities(VGbitfield caps)		{ m_capabilities = caps; }
+	int					getNumSegments() const					{ return m_segments.size(); }
+	int					getNumCoordinates() const				{ return m_data.size() / getBytesPerCoordinate(m_datatype); }
+	void				addReference()							{ m_referenceCount++; }
+	int					removeReference()						{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+	void				clear(VGbitfield capabilities);
+	void				appendData(const RIuint8* segments, int numSegments, const RIuint8* data);	//throws bad_alloc
+	void				append(const Path* srcPath);	//throws bad_alloc
+	void				modifyCoords(int startIndex, int numSegments, const RIuint8* data);
+	void				transform(const Path* srcPath, const Matrix3x3& matrix);	//throws bad_alloc
+	//returns true if interpolation succeeds, false if start and end paths are not compatible
+	bool				interpolate(const Path* startPath, const Path* endPath, RIfloat amount);	//throws bad_alloc
+	void				fill(const Matrix3x3& pathToSurface, Rasterizer& rasterizer);	//throws bad_alloc
+	void				stroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const Array<RIfloat>& dashPattern, RIfloat dashPhase, bool dashPhaseReset, RIfloat strokeWidth, VGCapStyle capStyle, VGJoinStyle joinStyle, RIfloat miterLimit);	//throws bad_alloc
+
+	void				getPointAlong(int startIndex, int numSegments, RIfloat distance, Vector2& p, Vector2& t);	//throws bad_alloc
+	RIfloat				getPathLength(int startIndex, int numSegments);	//throws bad_alloc
+	void				getPathBounds(RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy);	//throws bad_alloc
+	void				getPathTransformedBounds(const Matrix3x3& pathToSurface, RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy);	//throws bad_alloc
+    int                 coordsSizeInBytes( int startIndex, int numSegments );
+
+private:
+	enum VertexFlags
+	{
+		START_SUBPATH			= (1<<0),
+		END_SUBPATH				= (1<<1),
+		START_SEGMENT			= (1<<2),
+		END_SEGMENT				= (1<<3),
+		CLOSE_SUBPATH			= (1<<4),
+		IMPLICIT_CLOSE_SUBPATH	= (1<<5)
+	};
+	struct Vertex
+	{
+		Vertex() : userPosition(), userTangent(), pathLength(0.0f), flags(0) {}
+		Vector2			userPosition;
+		Vector2			userTangent;
+		RIfloat			pathLength;
+		unsigned int	flags;
+	};
+	struct StrokeVertex
+	{
+		StrokeVertex() : p(), t(), ccw(), cw(), pathLength(0.0f), flags(0), inDash(false) {}
+		Vector2			p;
+		Vector2			t;
+		Vector2			ccw;
+		Vector2			cw;
+		RIfloat			pathLength;
+		unsigned int	flags;
+		bool			inDash;
+	};
+
+	Path(const Path&);						//!< Not allowed.
+	const Path& operator=(const Path&);		//!< Not allowed.
+
+	static VGPathSegment getPathSegment(RIuint8 data)				{ return (VGPathSegment)(data & 0x1e); }
+	static VGPathAbsRel	getPathAbsRel(RIuint8 data)					{ return (VGPathAbsRel)(data & 0x1); }
+	static int			segmentToNumCoordinates(VGPathSegment segment);
+	static int			countNumCoordinates(const RIuint8* segments, int numSegments);
+	static int			getBytesPerCoordinate(VGPathDatatype datatype);
+
+	static void			setCoordinate(Array<RIuint8>& data, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int i, RIfloat c);
+
+	RIfloat				getCoordinate(int i) const;
+	void				setCoordinate(int i, RIfloat c)				{ setCoordinate(m_data, m_datatype, m_scale, m_bias, i, c); }
+
+	void				addVertex(const Vector2& p, const Vector2& t, RIfloat pathLength, unsigned int flags);	//throws bad_alloc
+	void				addEdge(const Vector2& p0, const Vector2& p1, const Vector2& t0, const Vector2& t1, unsigned int startFlags, unsigned int endFlags);	//throws bad_alloc
+
+	void				addEndPath(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry, unsigned int flags);	//throws bad_alloc
+	bool				addLineTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry);	//throws bad_alloc
+	bool				addQuadTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, bool subpathHasGeometry, float strokeWidth);	//throws bad_alloc
+	bool				addCubicTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3, bool subpathHasGeometry, float strokeWidth);	//throws bad_alloc
+	bool				addArcTo(const Matrix3x3& pathToSurface, const Vector2& p0, RIfloat rh, RIfloat rv, RIfloat rot, const Vector2& p1, const Vector2& p1r, VGPathSegment segment, bool subpathHasGeometry, float strokeWidth);	//throws bad_alloc
+
+	void				tessellate(const Matrix3x3& pathToSurface, float strokeWidth);	//throws bad_alloc
+
+	void				normalizeForInterpolation(const Path* srcPath);	//throws bad_alloc
+
+	void				interpolateStroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth) const;	//throws bad_alloc
+	void				doCap(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v, RIfloat strokeWidth, VGCapStyle capStyle) const;	//throws bad_alloc
+	void				doJoin(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth, VGJoinStyle joinStyle, RIfloat miterLimit) const;	//throws bad_alloc
+
+	//input data
+	VGint				m_format;
+	VGPathDatatype		m_datatype;
+	RIfloat				m_scale;
+	RIfloat				m_bias;
+	VGbitfield			m_capabilities;
+	int					m_referenceCount;
+	Array<RIuint8>		m_segments;
+	Array<RIuint8>		m_data;
+
+	//data produced by tessellation
+	struct VertexIndex
+	{
+		int		start;
+		int		end;
+	};
+	Array<Vertex>		m_vertices;
+    int                 m_numTessVertices;
+	Array<VertexIndex>	m_segmentToVertex;
+	RIfloat				m_userMinx;
+	RIfloat				m_userMiny;
+	RIfloat				m_userMaxx;
+	RIfloat				m_userMaxy;
+
+    bool                m_mirror;
+};
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+//==============================================================================================
+
+#endif /* __RIPATH_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riPixelPipe.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1440 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief   Implementation of Paint and pixel pipe functionality.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+#ifndef __RIRASTERIZER_H
+#   include "riRasterizer.h"
+#endif
+#ifndef __SFDYNAMICPIXELPIPE_H
+#   include "sfDynamicPixelPipe.h"
+#endif
+#ifndef __SFCOMPILER_H
+#   include "sfCompiler.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Paint constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Paint::Paint() :
+    m_paintType(VG_PAINT_TYPE_COLOR),
+    m_paintColor(0,0,0,1,Color::sRGBA_PRE),
+    m_inputPaintColor(0,0,0,1,Color::sRGBA),
+    m_colorRampSpreadMode(VG_COLOR_RAMP_SPREAD_PAD),
+    m_colorRampStops(),
+    m_inputColorRampStops(),
+    m_colorRampPremultiplied(VG_TRUE),
+    m_inputLinearGradientPoint0(0,0),
+    m_inputLinearGradientPoint1(1,0),
+    m_inputRadialGradientCenter(0,0),
+    m_inputRadialGradientFocalPoint(0,0),
+    m_inputRadialGradientRadius(1.0f),
+    m_linearGradientPoint0(0,0),
+    m_linearGradientPoint1(1,0),
+    m_radialGradientCenter(0,0),
+    m_radialGradientFocalPoint(0,0),
+    m_radialGradientRadius(1.0f),
+    m_patternTilingMode(VG_TILE_FILL),
+    m_pattern(NULL),
+    m_referenceCount(0),
+    m_lutFormat((VGImageFormat)-1),
+    m_gradientStopsChanged(true)
+{
+    Paint::GradientStop gs;
+    gs.offset = 0.0f;
+    gs.color.set(0,0,0,1,Color::sRGBA);
+    m_colorRampStops.push_back(gs); //throws bad_alloc
+    gs.offset = 1.0f;
+    gs.color.set(1,1,1,1,Color::sRGBA);
+    m_colorRampStops.push_back(gs); //throws bad_alloc
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Paint destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Paint::~Paint()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    if(m_pattern)
+    {
+        m_pattern->removeInUse();
+        if(!m_pattern->removeReference())
+            RI_DELETE(m_pattern);
+    }
+}
+
+static Color readStopColor(const Array<Paint::GradientStop>& colorRampStops, int i, VGboolean colorRampPremultiplied)
+{
+    RI_ASSERT(i >= 0 && i < colorRampStops.size());
+    Color c = colorRampStops[i].color;
+    RI_ASSERT(c.getInternalFormat() == Color::sRGBA);
+    if(colorRampPremultiplied)
+        c.premultiply();
+    return c;
+}
+
+void Paint::setGradientStops(Array<GradientStop>& inputStops, Array<GradientStop>& stops)
+{
+    m_colorRampStops.swap(stops);
+    m_inputColorRampStops.swap(inputStops);
+    m_gradientStopsChanged = true;
+}
+
+void Paint::setLinearGradient(const Vector2& p0, const Vector2& p1)
+{
+    m_linearGradientPoint0 = p0;
+    m_linearGradientPoint1 = p1;
+}
+
+void Paint::setRadialGradient(const Vector2& c, const Vector2& f, VGfloat r)
+{
+    m_radialGradientCenter = c;
+    m_radialGradientFocalPoint = f;
+    m_radialGradientRadius = r;
+}
+
+bool Paint::linearDegenerate() const
+{
+    return m_linearGradientPoint0 == m_linearGradientPoint1 ? true : false;
+}
+
+bool Paint::radialDegenerate() const
+{
+    return m_radialGradientRadius == 0.0f ? true : false;
+}
+
+/**
+ * \brief   Returns either the VG_PAINT_COLOR, or evaluated gradient value when the
+ *          gradient is degenerate.
+ */
+Color Paint::getSolidColor() const
+{
+    if (m_paintType == VG_PAINT_TYPE_PATTERN)
+    {
+        RI_ASSERT(m_pattern == NULL);
+        return m_paintColor;
+    }
+
+    if (m_paintType == VG_PAINT_TYPE_COLOR)
+        return m_paintColor;
+
+    RI_ASSERT(linearDegenerate() || radialDegenerate());
+
+    // Determine the color at the end of the gradient
+    RIfloat gs, ge;
+    if (m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_PAD)
+    {
+        gs = 1.0f - 1/256.0f;
+        ge = 1.0f;
+    } else if (m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT)
+    {
+        gs = 0.0f;
+        ge = 1/256.0f;
+    } else
+    {
+        gs = 1.0f - 1/256.0f;
+        ge = 1.0f;
+    }
+    Color c = integrateColorRamp(gs, ge);
+    return c * 256.0f;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Returns the average color within an offset range in the color ramp.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Paint::integrateColorRamp(RIfloat gmin, RIfloat gmax) const
+{
+    RI_ASSERT(gmin <= gmax);
+    RI_ASSERT(gmin >= 0.0f && gmin <= 1.0f);
+    RI_ASSERT(gmax >= 0.0f && gmax <= 1.0f);
+    RI_ASSERT(m_colorRampStops.size() >= 2);   //there are at least two stops
+
+    Color currC(0,0,0,0,m_colorRampPremultiplied ? Color::sRGBA_PRE : Color::sRGBA);
+
+    if(gmin == 1.0f || gmax == 0.0f)
+        return currC;
+
+    int i = 0;
+
+    for(; i < m_colorRampStops.size()-1; i++)
+    {
+        if(gmin >= m_colorRampStops[i].offset && gmin < m_colorRampStops[i+1].offset)
+        {
+            RIfloat s = m_colorRampStops[i].offset;
+            RIfloat e = m_colorRampStops[i+1].offset;
+            RI_ASSERT(s < e);
+            RIfloat g = (gmin - s) / (e - s);
+
+            Color sc = readStopColor(m_colorRampStops, i, m_colorRampPremultiplied);
+            Color ec = readStopColor(m_colorRampStops, i+1, m_colorRampPremultiplied);
+            Color rc = (1.0f-g) * sc + g * ec;
+
+            //subtract the average color from the start of the stop to gmin
+            Color dc = 0.5f*(gmin - s)*(sc + rc);
+            currC -= dc; 
+            break;
+        }
+    }
+
+    for(;i < m_colorRampStops.size()-1; i++)
+    {
+        RIfloat s = m_colorRampStops[i].offset;
+        RIfloat e = m_colorRampStops[i+1].offset;
+        RI_ASSERT(s <= e);
+
+        Color sc = readStopColor(m_colorRampStops, i, m_colorRampPremultiplied);
+        Color ec = readStopColor(m_colorRampStops, i+1, m_colorRampPremultiplied);
+
+        //average of the stop
+        Color dc = 0.5f*(e-s)*(sc + ec);
+        currC += dc; 
+
+        if(gmax >= m_colorRampStops[i].offset && gmax < m_colorRampStops[i+1].offset)
+        {
+            RIfloat g = (gmax - s) / (e - s);
+            Color rc = (1.0f-g) * sc + g * ec;
+
+            //subtract the average color from gmax to the end of the stop
+            dc = 0.5f*(e - gmax)*(rc + ec);
+            currC -= dc;
+            break;
+        }
+    }
+
+    return currC;
+}
+
+/**
+ * \brief   Generates gradient color-ramp lookup values.
+ *
+ * \param   targetFormat    Destination or image format to associate LUT with.
+ * \patam   drawImage       true if paint is evaluated along drawImage.
+ *
+ * \note    Must be called prior to rendering, and after the destination
+ *          format is known. The destination format is either destination 
+ *          surface format, or the image format in case of image rendering
+ *          operation.
+ */
+void Paint::generateLUT(PixelPipe& pipe, VGImageFormat preferredFormat)
+{
+    const RIfloat gstep = 1.0f / (GRADIENT_LUT_COUNT);
+    const RIfloat rcp = (RIfloat)(GRADIENT_LUT_COUNT);
+    RIfloat gsx;
+    gsx = 0.0f;
+    
+    if (!pipe.colorTransformChanged() && !m_gradientStopsChanged && (preferredFormat == m_lutFormat))
+        return; // Already in correct format
+
+    const bool inputPremultiplied = m_colorRampPremultiplied == VG_TRUE ? true : false;
+
+    // Colortransform premultiplies color.
+    const Color::Descriptor srcDesc = Color::formatToDescriptorConst(
+        inputPremultiplied || pipe.hasColorTransform() ? VG_sRGBA_8888_PRE : VG_sRGBA_8888);
+
+    const Color::Descriptor dstDesc = Color::formatToDescriptorConst(preferredFormat);
+
+    // Create a pre-calculated LUT.
+    for (int i = 0; i < GRADIENT_LUT_COUNT; i++)
+    {
+        // \todo Open up the integrator and/or use also integers.
+        Color c = integrateColorRamp(gsx, gsx + gstep);
+        c *= rcp;
+
+        // \todo Changing the mode must be tracked somehow!
+        if (pipe.getImageMode() != VG_DRAW_IMAGE_MULTIPLY)
+            pipe.colorTransform(c);
+
+        IntegerColor ic = IntegerColor(c);
+        ic.convertToFrom(dstDesc, srcDesc, false);
+        m_gradientLUT[i] = ic;
+
+        gsx += gstep;
+    }
+
+    m_gradientStopsChanged = false;
+    m_lutFormat = Color::descriptorToVGImageFormat(dstDesc);
+    pipe.setColorTransformChanged(false);
+
+    RI_ASSERT(m_lutFormat == preferredFormat);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    PixelPipe constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+PixelPipe::PixelPipe() :
+    m_drawable(NULL),
+    m_image(NULL),
+    m_paint(NULL),
+    m_defaultPaint(),
+    m_blendMode(VG_BLEND_SRC_OVER),
+    m_imageMode(VG_DRAW_IMAGE_NORMAL),
+    m_imageQuality(VG_IMAGE_QUALITY_FASTER),
+    m_tileFillColor(0,0,0,0,Color::sRGBA),
+    m_colorTransform(false),
+    m_colorTransformValues(),
+    m_iColorTransformValues(),
+    m_surfaceToPaintMatrix(),
+    m_surfaceToImageMatrix(),
+    m_paintToSurfaceMatrix(),
+    m_maskOperation(VG_SET_MASK),
+    m_renderToMask(false),
+    m_colorTransformChanged(true)
+{
+    for(int i=0;i<8;i++)
+    {
+        m_colorTransformValues[i] = (i < 4) ? 1.0f : 0.0f;
+        m_iColorTransformValues[i] = (i < 4) ? (COLOR_TRANSFORM_ONE) : 0;
+    }
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief    PixelPipe destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+PixelPipe::~PixelPipe()
+{
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the rendering surface.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setDrawable(Drawable* drawable)
+{
+    RI_ASSERT(drawable);
+    m_drawable = drawable;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the blend mode.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setBlendMode(VGBlendMode blendMode)
+{
+    RI_ASSERT(blendMode >= VG_BLEND_SRC && blendMode <= VG_BLEND_ADDITIVE);
+    m_blendMode = blendMode;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the mask image. NULL disables masking.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setMask(bool masking)
+{
+    m_masking = masking;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the image to be drawn. NULL disables image drawing.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setImage(Image* image, VGImageMode imageMode)
+{
+    RI_ASSERT(imageMode == VG_DRAW_IMAGE_NORMAL || imageMode == VG_DRAW_IMAGE_MULTIPLY || imageMode == VG_DRAW_IMAGE_STENCIL);
+    m_image = image;
+    m_imageMode = imageMode;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the surface-to-paint matrix.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setSurfaceToPaintMatrix(const Matrix3x3& surfaceToPaintMatrix)
+{
+    m_surfaceToPaintMatrix = surfaceToPaintMatrix;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the surface-to-image matrix.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setSurfaceToImageMatrix(const Matrix3x3& surfaceToImageMatrix)
+{
+    m_surfaceToImageMatrix = surfaceToImageMatrix;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets image quality.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setImageQuality(VGImageQuality imageQuality)
+{
+    RI_ASSERT(imageQuality == VG_IMAGE_QUALITY_NONANTIALIASED || imageQuality == VG_IMAGE_QUALITY_FASTER || imageQuality == VG_IMAGE_QUALITY_BETTER);
+    m_imageQuality = imageQuality;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets fill color for VG_TILE_FILL tiling mode (pattern only).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setTileFillColor(const Color& c)
+{
+    m_tileFillColor = c;
+    m_tileFillColor.clamp();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets paint.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setPaint(Paint* paint)
+{
+    // \temp Only call this right before filling a polygon.
+    m_paint = paint;
+
+    if(!m_paint)
+        m_paint = &m_defaultPaint;
+
+    if(m_paint->m_pattern)
+        m_tileFillColor.convert(m_paint->m_pattern->getDescriptor().internalFormat);
+
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Color transform.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setColorTransform(bool enable, RIfloat values[8])
+{
+    m_colorTransform = enable;
+    for(int i=0;i<4;i++)
+    {
+        m_colorTransformValues[i] = RI_CLAMP(values[i], -127.0f, 127.0f);
+        m_colorTransformValues[i+4] = RI_CLAMP(values[i+4], -1.0f, 1.0f);
+        m_iColorTransformValues[i] = RI_ROUND_TO_INT(m_colorTransformValues[i]*(RIfloat)COLOR_TRANSFORM_ONE);
+        m_iColorTransformValues[i+4] = RI_ROUND_TO_INT(m_colorTransformValues[i+4]*255.0f);
+    }
+    m_colorTransformChanged = true;
+}
+
+const Image* PixelPipe::getRenderTargetImage() const
+{
+    if (m_renderToMask)
+        return m_drawable->getMaskBuffer()->getImage();
+
+    return m_drawable->getColorBuffer()->getImage();
+}
+
+/**
+ * \brief   Determine an appropriate VGImageFormat to use for lookup tables.
+ * \todo    Should return descriptor instead?
+ */
+VGImageFormat PixelPipe::getPreferredLUTFormat() const
+{
+    const Image* target = getRenderTargetImage();
+    const Color::Descriptor& targetDesc = target->getDescriptor();
+
+    if (m_renderToMask)
+    {
+        RI_ASSERT(!m_image);
+        if (targetDesc.isNonlinear())
+            return VG_sRGBA_8888_PRE;
+        else
+            return VG_lRGBA_8888_PRE;
+    }
+
+    if (m_image && m_imageMode == VG_DRAW_IMAGE_MULTIPLY)
+        return VG_sRGBA_8888_PRE; // ?
+
+    // Prefer premultiplied formats
+    // \note Can also generate non-premultiplied if no sampling/other operation and destination
+    // is in linear format.
+    // \note Do not use VGImageFormat, because using (s/l)LA88 is possible with
+    // luminance destination formats.
+    if (targetDesc.isNonlinear())
+        return VG_sRGBA_8888_PRE;
+    else
+        return VG_lRGBA_8888_PRE;
+}
+
+void PixelPipe::prepareSolidFill()
+{
+    if (!(m_drawable && m_paint))
+        return;
+        
+    Color c = m_paint->getSolidColor();
+    //Color c = m_paint->m_paintColor;
+    
+    if (!m_image || m_imageMode != VG_DRAW_IMAGE_MULTIPLY)
+        colorTransform(c); // Output will be premultiplied
+    // Generate internal color
+    Color::Descriptor blendDesc = getRenderTargetImage()->getDescriptor();
+
+    // MULTIPLY uses the color as-is.
+    if (m_imageMode != VG_DRAW_IMAGE_MULTIPLY) c.convert(blendDesc.internalFormat);
+
+    IntegerColor ic = IntegerColor(c);
+    blendDesc.internalFormat = (Color::InternalFormat)(blendDesc.internalFormat | (Color::PREMULTIPLIED));
+
+    if (m_imageMode != VG_DRAW_IMAGE_MULTIPLY) c.convert(blendDesc.internalFormat);
+    
+    IntegerColor blendColor = IntegerColor(c);
+
+    if (m_imageMode == VG_DRAW_IMAGE_STENCIL)
+        blendColor.asFixedPoint(c); // Enhance the precision a bit
+    
+    // \todo No need to pack the color if solid fill is not possible
+    if (!m_renderToMask)
+        ic.truncateColor(getRenderTargetImage()->getDescriptor());
+    else
+        ic.truncateMask(getRenderTargetImage()->getDescriptor());
+
+    RIuint32 p = ic.getPackedColor(getRenderTargetImage()->getDescriptor());
+
+    m_spanUniforms.solidColor = blendColor; // This must be premultiplied
+    m_spanUniforms.packedSolidColor = p; // This must be exactly the dst color
+}
+
+void PixelPipe::prepareCoverageFill()
+{
+    IntegerColor ic = IntegerColor(255, 255, 255, 255);
+    RIuint32 p = ic.getPackedColor(m_drawable->getMaskBuffer()->getDescriptor());
+
+    m_spanUniforms.solidColor = ic;
+    m_spanUniforms.packedSolidColor = p;
+}
+
+void PixelPipe::prepareLinearGradient()
+{
+    const Matrix3x3& s2p = m_surfaceToPaintMatrix;
+
+    Vector2 zero(0,0);
+    Vector2 p0 = m_paint->m_linearGradientPoint0;
+    Vector2 p1 = m_paint->m_linearGradientPoint1;
+    Vector2 delta = p1 - p0;
+
+    zero = affineTransform(s2p, zero);
+
+    RIfloat d = (delta.x * delta.x) + (delta.y * delta.y);
+    RIfloat gdx = (s2p[0][0] * delta.x + s2p[1][0] * delta.y) / d;
+    RIfloat gdy = (s2p[0][1] * delta.x + s2p[1][1] * delta.y) / d;
+    RIfloat cx = (zero.x-p0.x) * (delta.x);
+    RIfloat cy = (zero.y-p0.y) * (delta.y);
+    RIfloat c = (cx + cy) / d;
+
+    m_spanUniforms.dgdx = RI_FLOAT_TO_FX(gdx, PixelPipe::GRADIENT_BITS);
+    m_spanUniforms.dgdy = RI_FLOAT_TO_FX(gdy, PixelPipe::GRADIENT_BITS);
+    m_spanUniforms.lgc = RI_FLOAT_TO_FX(c + 0.5*(gdx + gdy), PixelPipe::GRADIENT_BITS);
+
+    m_spanUniforms.gradientLookup = m_paint->getGradientLUT();
+}
+
+void PixelPipe::prepareRadialGradient()
+{
+    const Matrix3x3& s2p = m_surfaceToPaintMatrix;
+
+    Vector2 c = m_paint->m_radialGradientCenter;
+    Vector2 f = m_paint->m_radialGradientFocalPoint;
+    RGScalar r = m_paint->m_radialGradientRadius;
+
+    Vector2 zero(0,0);
+    Vector2 pzero = affineTransform(s2p, zero);
+
+    Vector2 fp = f - c;
+
+    RGScalar q = fp.length();
+
+    if (q > r)
+    {
+        const RIfloat scale = 0.99f;
+        fp.normalize();
+        fp *= r * scale;
+        f = fp + c;
+    } 
+
+    RGScalar r1sqr = RI_SQR(r);
+    RGScalar d = r1sqr - dot(fp, fp);
+
+    m_spanUniforms.rdxdx = s2p[0][0];
+    m_spanUniforms.rdxdy = s2p[0][1];
+    m_spanUniforms.rdydx = s2p[1][0];
+    m_spanUniforms.rdydy = s2p[1][1];
+
+    m_spanUniforms.rsqrp = r1sqr / RI_SQR(d);
+    m_spanUniforms.rfxp = fp.x / d;
+    m_spanUniforms.rfyp = fp.y / d;
+    m_spanUniforms.rx0 = pzero.x - f.x + 0.5f*(m_spanUniforms.rdxdx + m_spanUniforms.rdxdy);
+    m_spanUniforms.ry0 = pzero.y - f.y + 0.5f*(m_spanUniforms.rdydy + m_spanUniforms.rdydx);
+
+    m_spanUniforms.gradientLookup = m_paint->getGradientLUT();
+}
+
+void PixelPipe::preparePattern()
+{
+    // Patterns only support affine transforms
+    const Matrix3x3& s2p = m_surfaceToPaintMatrix;
+    const RIfloat patternWidth = (RIfloat)m_paint->m_pattern->getWidth();
+    const RIfloat patternHeight = (RIfloat)m_paint->m_pattern->getHeight();
+    const Vector2 zero(0, 0);
+    Vector2 pzero = affineTransform(s2p, zero); 
+
+    m_spanUniforms.paint_x0 = RI_ROUND_TO_INT((pzero.x/patternWidth)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_y0 = RI_ROUND_TO_INT((pzero.y/patternHeight)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_dxdx = RI_ROUND_TO_INT((s2p[0][0]/patternWidth)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_dxdy = RI_ROUND_TO_INT((s2p[0][1]/patternHeight)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_dydx = RI_ROUND_TO_INT((s2p[1][0]/patternWidth)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_dydy = RI_ROUND_TO_INT((s2p[1][1]/patternHeight)*(1<<GRADIENT_BITS));
+
+    m_spanUniforms.paint_x0 += (m_spanUniforms.paint_dxdx + m_spanUniforms.paint_dxdy) / 2;
+    m_spanUniforms.paint_y0 += (m_spanUniforms.paint_dydy + m_spanUniforms.paint_dydx) / 2;
+
+    m_spanUniforms.patternPtr = m_paint->m_pattern->getData(); 
+    m_spanUniforms.patternStride = m_paint->m_pattern->getStride();
+    m_spanUniforms.paint_width = m_paint->m_pattern->getWidth();
+    m_spanUniforms.paint_height = m_paint->m_pattern->getHeight();
+
+    m_signatureState.patternDesc = m_paint->m_pattern->getDescriptor();
+
+    m_spanUniforms.tileFillColor = IntegerColor(m_tileFillColor);
+    // The tile fill-color must be shifted down to same bit-depth (see integer samplers)
+    m_spanUniforms.tileFillColor.truncateColor(m_signatureState.patternDesc);
+
+}
+
+RI_INLINE static RIfloat floatEqu(RIfloat a, RIfloat b, RIfloat e)
+{
+    // \note This should be sufficient for our use-cases;
+    return (RI_ABS(a - b) < e);
+}
+
+RI_INLINE static RIfloat distToInt(RIfloat f)
+{
+    const RIfloat intF = RI_ROUND_TO_INT(f);
+    return RI_ABS(intF - f);
+}
+
+/**
+ * \brief   Check if transform is 90 degree rotation, or flip and nothing else.
+ */
+RI_INLINE static bool orthoNormalCoAxialTransform(const Matrix3x3& t, bool aa)
+{
+    const RIfloat epsilonCoord = 1/255.0f; // 1/127.0f;
+    const RIfloat epsilonGradient = epsilonCoord * epsilonCoord; // \todo Too strict?
+    const RIfloat absPatterns[2][4] = {
+        {1.0f, 0.0f, 0.0f, 1.0f},
+        {0.0f, 1.0f, 1.0f, 0.0f} };
+
+    if (!t.isAffine())
+        return false;
+
+    // \todo This rule only applies if filtering is in use?
+    if (aa)
+        if (!floatEqu(distToInt(t[0][2]), 0.0f, epsilonCoord) || !floatEqu(distToInt(t[1][2]), 0.0f, epsilonCoord))
+            return false;
+
+    Matrix3x3 u = t;
+    
+    for (int j = 0; j < 2; j++)
+        for (int i = 0; i < 2; i++)
+            u[j][i] = RI_ABS(u[j][i]);
+
+    bool found;
+
+    for (int m = 0; m < 2; m++)
+    {
+        found = true;
+        for (int j = 0; j < 2; j++)
+        {
+            for (int i = 0; i < 2; i++)
+            {
+                //if (u[j][i] != absPatterns[m][i+j*2])
+                if (!floatEqu(u[j][i], absPatterns[m][i+j*2], epsilonGradient))
+                {
+                    found = false;
+                    break;
+                }
+            }
+            if (!found) break;
+        }
+        if (found) break;
+    }
+
+    return found;
+}
+
+void PixelPipe::prepareImage(bool aa)
+{
+    if (!m_image)
+    {
+        m_signatureState.imageGradientType = GRADIENT_TYPE_INTEGER;
+        return;
+    }
+
+    RI_ASSERT(m_image);
+    m_spanUniforms.imagePtr = m_image->getData();
+    m_spanUniforms.imageStride = m_image->getStride();
+    
+    if (m_image->getParent() != NULL)
+    {
+        // Adjust the pointer.
+        int x, y;
+        m_image->getStorageOffset(x, y);
+        m_spanUniforms.imagePtr = Image::calculateAddress(
+            m_spanUniforms.imagePtr, m_image->getDescriptor().bitsPerPixel, x, y, m_spanUniforms.imageStride);
+    }
+
+    // \todo This function writes to derived state also.
+    // \todo Plenty of fast-paths possible!
+    const Matrix3x3& s2i = m_surfaceToImageMatrix;
+    
+    Vector3 zero(0,0,1);
+    Vector3 pzero;
+
+    bool fastImage = orthoNormalCoAxialTransform(s2i, aa);
+    
+    pzero = s2i * zero;
+
+    if (fastImage)
+    {
+        RI_ASSERT(pzero.z == 1.0f);
+        m_spanUniforms.image_idxdx = RI_ROUND_TO_INT(s2i[0][0]);
+        m_spanUniforms.image_idxdy = RI_ROUND_TO_INT(s2i[0][1]);
+        m_spanUniforms.image_idydx = RI_ROUND_TO_INT(s2i[1][0]);
+        m_spanUniforms.image_idydy = RI_ROUND_TO_INT(s2i[1][1]);
+        m_spanUniforms.image_ix0 = RI_FLOOR(pzero.x + 0.5f*(s2i[0][0]+s2i[0][1]));
+        m_spanUniforms.image_iy0 = RI_FLOOR(pzero.y + 0.5f*(s2i[1][1]+s2i[1][0]));
+
+        // Adjust sample-center when using (exactly) integer coordinates.
+        
+#if 0
+        if (m_spanUniforms.image_idxdx < 0 || m_spanUniforms.image_idxdy < 0)
+            m_spanUniforms.image_ix0--;
+    
+        if (m_spanUniforms.image_idydy < 0 || m_spanUniforms.image_idydx < 0)
+            m_spanUniforms.image_iy0--;
+#endif
+
+        m_signatureState.imageGradientType = GRADIENT_TYPE_INTEGER;
+    } 
+    else if (s2i.isAffine())
+    {
+        RI_ASSERT(pzero.z == 1.0f); 
+        const RIfloat imageWidth = m_image->getWidth();
+        const RIfloat imageHeight = m_image->getHeight();
+        
+        m_spanUniforms.image_idxdx = RI_ROUND_TO_INT((s2i[0][0]/imageWidth)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_idxdy = RI_ROUND_TO_INT((s2i[0][1]/imageHeight)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_idydx = RI_ROUND_TO_INT((s2i[1][0]/imageWidth)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_idydy = RI_ROUND_TO_INT((s2i[1][1]/imageHeight)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_ix0 = RI_ROUND_TO_INT((pzero.x/imageWidth)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_iy0 = RI_ROUND_TO_INT((pzero.y/imageHeight)*(1<<GRADIENT_BITS));
+
+        m_spanUniforms.image_ix0 += (m_spanUniforms.image_idxdx + m_spanUniforms.image_idxdy)/2;
+        m_spanUniforms.image_iy0 += (m_spanUniforms.image_idydy + m_spanUniforms.image_idydx)/2;
+
+        m_spanUniforms.image_iWidth = (RIint32)imageWidth;
+        m_spanUniforms.image_iHeight = (RIint32)imageHeight;
+
+        m_signatureState.imageGradientType = GRADIENT_TYPE_FIXED;
+    } 
+    else
+    {
+        // Use floats.
+        m_spanUniforms.image_fx0 = pzero.x;
+        m_spanUniforms.image_fy0 = pzero.y;
+        m_spanUniforms.image_fw0 = pzero.z;
+        m_spanUniforms.image_fdxdx = s2i[0][0];
+        m_spanUniforms.image_fdxdy = s2i[0][1];
+        m_spanUniforms.image_fdydx = s2i[1][0];
+        m_spanUniforms.image_fdydy = s2i[1][1];
+        m_spanUniforms.image_fdwdx = s2i[2][0];
+        m_spanUniforms.image_fdwdy = s2i[2][1];
+
+        m_spanUniforms.image_fx0 += 0.5f * (m_spanUniforms.image_fdxdx + m_spanUniforms.image_fdxdy);
+        m_spanUniforms.image_fy0 += 0.5f * (m_spanUniforms.image_fdydy + m_spanUniforms.image_fdydx);
+        m_spanUniforms.image_fw0 += 0.5f * (m_spanUniforms.image_fdwdx + m_spanUniforms.image_fdwdy);
+
+        m_spanUniforms.image_fWidth = (RIfloat)m_image->getWidth();
+        m_spanUniforms.image_fHeight = (RIfloat)m_image->getHeight();
+
+        m_signatureState.imageGradientType = GRADIENT_TYPE_FLOAT;
+    }
+
+    m_signatureState.imageDesc = m_image->getDescriptor();
+}
+
+static PixelPipe::TilingMode tilingModeOfImageTilingMode(VGTilingMode it)
+{
+    switch(it)
+    {
+    case VG_TILE_PAD:
+        return PixelPipe::TILING_MODE_PAD;
+    case VG_TILE_REPEAT:
+        return PixelPipe::TILING_MODE_REPEAT;
+    case VG_TILE_REFLECT:
+        return PixelPipe::TILING_MODE_REFLECT;
+    default:
+        RI_ASSERT(it == VG_TILE_FILL);
+        return PixelPipe::TILING_MODE_FILL;
+    }
+}
+
+static PixelPipe::TilingMode tilingModeOfSpreadMode(VGColorRampSpreadMode sm)
+{
+    switch(sm)
+    {
+    case VG_COLOR_RAMP_SPREAD_PAD:
+        return PixelPipe::TILING_MODE_PAD;
+    case VG_COLOR_RAMP_SPREAD_REPEAT:
+        return PixelPipe::TILING_MODE_REPEAT;
+    default:
+        RI_ASSERT(sm == VG_COLOR_RAMP_SPREAD_REFLECT);
+        return PixelPipe::TILING_MODE_REFLECT;
+    }
+}
+
+static PixelPipe::TilingMode tilingModeOfPaint(const Paint* paint)
+{
+    switch(paint->m_paintType)
+    {
+    case VG_PAINT_TYPE_COLOR:
+        return PixelPipe::TILING_MODE_PAD;
+    case VG_PAINT_TYPE_LINEAR_GRADIENT:
+    case VG_PAINT_TYPE_RADIAL_GRADIENT:
+        return tilingModeOfSpreadMode(paint->m_colorRampSpreadMode);
+    default:
+        RI_ASSERT(paint->m_paintType == VG_PAINT_TYPE_PATTERN);
+        return tilingModeOfImageTilingMode(paint->m_patternTilingMode);
+    }
+}
+
+void PixelPipe::prepareRenderToMask()
+{
+    RI_ASSERT(m_drawable->getMaskBuffer());
+
+    m_signatureState.dstDesc = m_drawable->getMaskBuffer()->getDescriptor();
+    //RI_ASSERT(m_signatureState.dstFormat >= 0 && m_signatureState.dstFormat <= VG_lABGR_8888_PRE);
+
+    m_signatureState.maskOperation = m_maskOperation;
+}
+
+void PixelPipe::prepareSignatureState()
+{
+    m_signatureState.isRenderToMask = m_renderToMask;
+
+    if (m_signatureState.isRenderToMask)
+    {
+        prepareRenderToMask();
+        return;
+    }
+
+    m_signatureState.blendMode = getBlendMode();
+
+    m_signatureState.hasColorTransform = this->m_colorTransform;
+
+    m_signatureState.paintType = getPaintType();
+    
+    m_signatureState.paintTilingMode = tilingModeOfPaint(m_paint);
+    // \todo Derive these from the quality settings somehow.
+    // Linear and nearest should work atm.
+    m_signatureState.paintSampler = SAMPLER_TYPE_NEAREST;
+    m_signatureState.imageSampler = SAMPLER_TYPE_NEAREST;
+
+    m_signatureState.hasMasking = isMasking() && (m_drawable->getMaskBuffer() != NULL);
+    
+    m_signatureState.hasImage = m_image ? true : false;
+    m_signatureState.unsafeImageInput = !m_image ? false : m_image->isUnsafe();
+    m_signatureState.imageMode = m_imageMode;
+
+    // Formats. Note that fields that are not filled in / used get set to a derived state in a 
+    // separate function!
+
+    if (m_signatureState.paintType == (RIuint32)VG_PAINT_TYPE_COLOR)
+    {
+        RI_ASSERT(m_paint);
+        if (m_paint->getSolidColor().a == 1.0)
+            m_signatureState.fillColorTransparent = false;
+        else
+            m_signatureState.fillColorTransparent = true;
+    }
+
+    m_signatureState.dstDesc = m_drawable->getColorBuffer()->getDescriptor();
+
+    // \todo Why isn't the imagedescriptor set here?
+    if (m_signatureState.hasMasking)
+    {
+        m_signatureState.maskDesc = m_drawable->getMaskBuffer()->getDescriptor();
+    }
+
+}
+
+/**
+ * \brief   Remove redundancy from the pixel-pipeline state so that less
+ *          pipelines are generated.
+ */
+static void determineDerivedState(PixelPipe::SignatureState& derivedState, const PixelPipe::SignatureState& originalState)
+{
+    derivedState = originalState;
+
+    if (derivedState.isRenderToMask)
+    {
+        // Set a lot of defaults:
+        derivedState.blendMode = VG_BLEND_SRC;
+        derivedState.imageMode = VG_DRAW_IMAGE_NORMAL;
+        derivedState.paintType = VG_PAINT_TYPE_COLOR;
+
+        derivedState.hasImage = false;
+        derivedState.hasMasking = false;
+        derivedState.hasColorTransform = false;
+    }
+
+    if (derivedState.paintType == VG_PAINT_TYPE_COLOR)
+    {
+        derivedState.paintTilingMode = PixelPipe::TILING_MODE_PAD;
+        derivedState.paintSampler = PixelPipe::SAMPLER_TYPE_NEAREST;
+        // \todo Opaque solid colors can benefit from simpler coverage-blending
+        // becase SRC_OVER == SRC. This information has to be present in
+        // the derivedState (and not just uniform).
+    }
+
+    if (!derivedState.hasImage)
+    {
+        derivedState.imageMode = VG_DRAW_IMAGE_NORMAL;
+        derivedState.imageSampler = PixelPipe::SAMPLER_TYPE_NEAREST;
+        derivedState.imageGradientType = PixelPipe::GRADIENT_TYPE_INTEGER;
+        derivedState.imageDesc = Color::Descriptor::getDummyDescriptor();
+    } else if (derivedState.imageMode == VG_DRAW_IMAGE_NORMAL)
+    {
+        // If paint is not generated, use a common enum
+        derivedState.paintType = VG_PAINT_TYPE_COLOR;
+    }
+
+    if (derivedState.paintType != VG_PAINT_TYPE_PATTERN)
+    {
+        derivedState.patternDesc = Color::Descriptor::getDummyDescriptor();
+    }
+
+    if (!derivedState.isRenderToMask)
+        derivedState.maskOperation = VG_CLEAR_MASK;
+
+    if (!derivedState.hasMasking)
+    {
+        derivedState.maskDesc = Color::Descriptor::getDummyDescriptor();
+    }
+}
+
+
+/**
+ * \brief   Determine per-scanconversion constant state.
+ * \todo    NOTE! This also prepares the derived state at the moment.
+ */
+void PixelPipe::prepareSpanUniforms(bool aa)
+{
+    prepareSignatureState();
+
+    if (m_signatureState.hasColorTransform)
+        m_spanUniforms.colorTransformValues = m_iColorTransformValues;
+
+    RI_ASSERT(m_drawable->getColorBuffer());
+
+    const Image* dst;
+
+    if (!m_signatureState.isRenderToMask)
+        dst = m_drawable->getColorBuffer()->getImage();
+    else
+        dst = m_drawable->getMaskBuffer()->getImage();
+    
+    m_spanUniforms.dstPtr = dst->getData();
+    m_spanUniforms.dstStride = dst->getStride();
+
+    if (m_drawable->getMaskBuffer())
+    {
+        m_spanUniforms.maskPtr = m_drawable->getMaskBuffer()->m_image->getData();
+        m_spanUniforms.maskStride = m_drawable->getMaskBuffer()->m_image->getStride();
+    }
+    else
+    {
+        m_spanUniforms.maskPtr = NULL;
+        m_spanUniforms.maskStride = 0;
+    }
+
+    if (!m_renderToMask)
+    {
+        VGImageFormat prefPaintFormat = getPreferredLUTFormat();
+
+        switch (getPaintType())
+        {
+            case VG_PAINT_TYPE_COLOR:
+                prepareSolidFill();
+                break;
+            case VG_PAINT_TYPE_LINEAR_GRADIENT:
+                m_paint->generateLUT(*this, prefPaintFormat);
+                prepareLinearGradient(); 
+                break;
+            case VG_PAINT_TYPE_RADIAL_GRADIENT:
+                m_paint->generateLUT(*this, prefPaintFormat);
+                prepareRadialGradient();
+                break;
+            default:
+                RI_ASSERT(getPaintType() == VG_PAINT_TYPE_PATTERN);
+                preparePattern();
+                break;
+        }
+    }
+    else
+    {
+        prepareCoverageFill();
+    }
+
+    prepareImage(aa);
+
+    // Must be done last:
+    determineDerivedState(m_derivedState, m_signatureState);
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Computes the linear gradient function at (x,y).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+void PixelPipe::linearGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const
+{
+    RI_ASSERT(m_paint);
+    Vector2 u = m_paint->m_linearGradientPoint1 - m_paint->m_linearGradientPoint0;
+    RIfloat usq = dot(u,u);
+    if( usq <= 0.0f )
+    {   //points are equal, gradient is always 1.0f
+        g = 1.0f;
+        rho = 0.0f;
+        return;
+    }
+    RIfloat oou = 1.0f / usq;
+
+    Vector2 p(x, y);
+    p = affineTransform(m_surfaceToPaintMatrix, p);
+    p -= m_paint->m_linearGradientPoint0;
+    RI_ASSERT(usq >= 0.0f);
+    g = dot(p, u) * oou;
+    RIfloat dgdx = oou * u.x * m_surfaceToPaintMatrix[0][0] + oou * u.y * m_surfaceToPaintMatrix[1][0];
+    RIfloat dgdy = oou * u.x * m_surfaceToPaintMatrix[0][1] + oou * u.y * m_surfaceToPaintMatrix[1][1];
+    rho = (RIfloat)sqrt(dgdx*dgdx + dgdy*dgdy);
+    RI_ASSERT(rho >= 0.0f);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Computes the radial gradient function at (x,y).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::radialGradient(RIfloat &g, RIfloat &rho, RIfloat x, RIfloat y) const
+{
+    RI_ASSERT(m_paint);
+    if( m_paint->m_radialGradientRadius <= 0.0f )
+    {
+        g = 1.0f;
+        rho = 0.0f;
+        return;
+    }
+
+    RIfloat r = m_paint->m_radialGradientRadius;
+    Vector2 c = m_paint->m_radialGradientCenter;
+    Vector2 f = m_paint->m_radialGradientFocalPoint;
+    Vector2 gx(m_surfaceToPaintMatrix[0][0], m_surfaceToPaintMatrix[1][0]);
+    Vector2 gy(m_surfaceToPaintMatrix[0][1], m_surfaceToPaintMatrix[1][1]);
+
+    Vector2 fp = f - c;
+
+    //clamp the focal point inside the gradient circle
+    RIfloat fpLen = fp.length();
+    if( fpLen > 0.999f * r )
+        fp *= 0.999f * r / fpLen;
+
+    RIfloat D = -1.0f / (dot(fp,fp) - r*r);
+    Vector2 p(x, y);
+    p = affineTransform(m_surfaceToPaintMatrix, p) - c;
+    Vector2 d = p - fp;
+    RIfloat s = (RIfloat)sqrt(r*r*dot(d,d) - RI_SQR(p.x*fp.y - p.y*fp.x));
+    g = (dot(fp,d) + s) * D;
+    if(RI_ISNAN(g))
+        g = 0.0f;
+    RIfloat dgdx = D*dot(fp,gx) + (r*r*dot(d,gx) - (gx.x*fp.y - gx.y*fp.x)*(p.x*fp.y - p.y*fp.x)) * (D / s);
+    RIfloat dgdy = D*dot(fp,gy) + (r*r*dot(d,gy) - (gy.x*fp.y - gy.y*fp.x)*(p.x*fp.y - p.y*fp.x)) * (D / s);
+    rho = (RIfloat)sqrt(dgdx*dgdx + dgdy*dgdy);
+    if(RI_ISNAN(rho))
+        rho = 0.0f;
+    RI_ASSERT(rho >= 0.0f);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Maps a gradient function value to a color.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color PixelPipe::colorRamp(RIfloat gradient, RIfloat rho) const
+{
+    RI_ASSERT(m_paint);
+    RI_ASSERT(rho >= 0.0f);
+
+    Color c(0,0,0,0,m_paint->m_colorRampPremultiplied ? Color::sRGBA_PRE : Color::sRGBA);
+    Color avg;
+
+    if(rho == 0.0f)
+    {   //filter size is zero or gradient is degenerate
+        switch(m_paint->m_colorRampSpreadMode)
+        {
+        case VG_COLOR_RAMP_SPREAD_PAD:
+            gradient = RI_CLAMP(gradient, 0.0f, 1.0f);
+            break;
+        case VG_COLOR_RAMP_SPREAD_REFLECT:
+        {
+            RIfloat g = RI_MOD(gradient, 2.0f);
+            gradient = (g < 1.0f) ? g : 2.0f - g;
+            break;
+        }
+        default:
+            RI_ASSERT(m_paint->m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT);
+            gradient = gradient - (RIfloat)floor(gradient);
+            break;
+        }
+        RI_ASSERT(gradient >= 0.0f && gradient <= 1.0f);
+
+        for(int i=0;i<m_paint->m_colorRampStops.size()-1;i++)
+        {
+            if(gradient >= m_paint->m_colorRampStops[i].offset && gradient < m_paint->m_colorRampStops[i+1].offset)
+            {
+                RIfloat s = m_paint->m_colorRampStops[i].offset;
+                RIfloat e = m_paint->m_colorRampStops[i+1].offset;
+                RI_ASSERT(s < e);
+                RIfloat g = RI_CLAMP((gradient - s) / (e - s), 0.0f, 1.0f); //clamp needed due to numerical inaccuracies
+
+                Color sc = readStopColor(m_paint->m_colorRampStops, i, m_paint->m_colorRampPremultiplied);
+                Color ec = readStopColor(m_paint->m_colorRampStops, i+1, m_paint->m_colorRampPremultiplied);
+                return (1.0f-g) * sc + g * ec;  //return interpolated value
+            }
+        }
+        return readStopColor(m_paint->m_colorRampStops, m_paint->m_colorRampStops.size()-1, m_paint->m_colorRampPremultiplied);
+    }
+
+    RIfloat gmin = gradient - rho*0.5f;         //filter starting from the gradient point (if starts earlier, radial gradient center will be an average of the first and the last stop, which doesn't look good)
+    RIfloat gmax = gradient + rho*0.5f;
+
+    switch(m_paint->m_colorRampSpreadMode)
+    {
+    case VG_COLOR_RAMP_SPREAD_PAD:
+    {
+        if(gmin < 0.0f)
+            c += (RI_MIN(gmax, 0.0f) - gmin) * readStopColor(m_paint->m_colorRampStops, 0, m_paint->m_colorRampPremultiplied);
+        if(gmax > 1.0f)
+            c += (gmax - RI_MAX(gmin, 1.0f)) * readStopColor(m_paint->m_colorRampStops, m_paint->m_colorRampStops.size()-1, m_paint->m_colorRampPremultiplied);
+        gmin = RI_CLAMP(gmin, 0.0f, 1.0f);
+        gmax = RI_CLAMP(gmax, 0.0f, 1.0f);
+        c += m_paint->integrateColorRamp(gmin, gmax);
+        c *= 1.0f/rho;
+        c.clamp();  //clamp needed due to numerical inaccuracies
+        return c;
+    }
+
+    case VG_COLOR_RAMP_SPREAD_REFLECT:
+    {
+        avg = m_paint->integrateColorRamp(0.0f, 1.0f);
+        RIfloat gmini = (RIfloat)floor(gmin);
+        RIfloat gmaxi = (RIfloat)floor(gmax);
+        c = (gmaxi + 1.0f - gmini) * avg;       //full ramps
+
+        //subtract beginning
+        if(((int)gmini) & 1)
+            c -= m_paint->integrateColorRamp(RI_CLAMP(1.0f - (gmin - gmini), 0.0f, 1.0f), 1.0f);
+        else
+            c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(gmin - gmini, 0.0f, 1.0f));
+
+        //subtract end
+        if(((int)gmaxi) & 1)
+            c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(1.0f - (gmax - gmaxi), 0.0f, 1.0f));
+        else
+            c -= m_paint->integrateColorRamp(RI_CLAMP(gmax - gmaxi, 0.0f, 1.0f), 1.0f);
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(m_paint->m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT);
+        avg = m_paint->integrateColorRamp(0.0f, 1.0f);
+        RIfloat gmini = (RIfloat)floor(gmin);
+        RIfloat gmaxi = (RIfloat)floor(gmax);
+        c = (gmaxi + 1.0f - gmini) * avg;       //full ramps
+        c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(gmin - gmini, 0.0f, 1.0f));  //subtract beginning
+        c -= m_paint->integrateColorRamp(RI_CLAMP(gmax - gmaxi, 0.0f, 1.0f), 1.0f);  //subtract end
+        break;
+    }
+    }
+
+    //divide color by the length of the range
+    c *= 1.0f / rho;
+    c.clamp();  //clamp needed due to numerical inaccuracies
+
+    //hide aliasing by fading to the average color
+    const RIfloat fadeStart = 0.5f;
+    const RIfloat fadeMultiplier = 2.0f;    //the larger, the earlier fade to average is done
+
+    if(rho < fadeStart)
+        return c;
+
+    RIfloat ratio = RI_MIN((rho - fadeStart) * fadeMultiplier, 1.0f);
+    return ratio * avg + (1.0f - ratio) * c;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Computes blend.
+* \param
+* \return
+* \note     premultiplied blending formulas
+            //src
+            a = asrc
+            r = rsrc
+            //src over
+            a = asrc + adst * (1-asrc)
+            r = rsrc + rdst * (1-asrc)
+            //dst over
+            a = asrc * (1-adst) + adst
+            r = rsrc * (1-adst) + adst
+            //src in
+            a = asrc * adst
+            r = rsrc * adst
+            //dst in
+            a = adst * asrc
+            r = rdst * asrc
+            //multiply
+            a = asrc + adst * (1-asrc)
+            r = rsrc * (1-adst) + rdst * (1-asrc) + rsrc * rdst
+            //screen
+            a = asrc + adst * (1-asrc)
+            r = rsrc + rdst - rsrc * rdst
+            //darken
+            a = asrc + adst * (1-asrc)
+            r = MIN(rsrc + rdst * (1-asrc), rdst + rsrc * (1-adst))
+            //lighten
+            a = asrc + adst * (1-asrc)
+            r = MAX(rsrc + rdst * (1-asrc), rdst + rsrc * (1-adst))
+            //additive
+            a = MIN(asrc+adst,1)
+            r = rsrc + rdst
+*//*-------------------------------------------------------------------*/
+
+
+
+Color PixelPipe::blend(const Color& s, RIfloat ar, RIfloat ag, RIfloat ab, const Color& d, VGBlendMode blendMode) const
+{
+    //apply blending in the premultiplied format
+    Color r(0,0,0,0,d.getInternalFormat());
+    RI_ASSERT(s.a >= 0.0f && s.a <= 1.0f);
+    RI_ASSERT(s.r >= 0.0f && s.r <= s.a && s.r <= ar);
+    RI_ASSERT(s.g >= 0.0f && s.g <= s.a && s.g <= ag);
+    RI_ASSERT(s.b >= 0.0f && s.b <= s.a && s.b <= ab);
+    RI_ASSERT(d.a >= 0.0f && d.a <= 1.0f);
+    RI_ASSERT(d.r >= 0.0f && d.r <= d.a);
+    RI_ASSERT(d.g >= 0.0f && d.g <= d.a);
+    RI_ASSERT(d.b >= 0.0f && d.b <= d.a);
+    switch(blendMode)
+    {
+    case VG_BLEND_SRC:
+        r = s;
+        break;
+
+    case VG_BLEND_SRC_OVER:
+        r.r = s.r + d.r * (1.0f - ar);
+        r.g = s.g + d.g * (1.0f - ag);
+        r.b = s.b + d.b * (1.0f - ab);
+        r.a = s.a + d.a * (1.0f - s.a);
+        break;
+
+    case VG_BLEND_DST_OVER:
+        r.r = s.r * (1.0f - d.a) + d.r;
+        r.g = s.g * (1.0f - d.a) + d.g;
+        r.b = s.b * (1.0f - d.a) + d.b;
+        r.a = s.a * (1.0f - d.a) + d.a;
+        break;
+
+    case VG_BLEND_SRC_IN:
+        r.r = s.r * d.a;
+        r.g = s.g * d.a;
+        r.b = s.b * d.a;
+        r.a = s.a * d.a;
+        break;
+
+    case VG_BLEND_DST_IN:
+        r.r = d.r * ar;
+        r.g = d.g * ag;
+        r.b = d.b * ab;
+        r.a = d.a * s.a;
+        break;
+
+    case VG_BLEND_MULTIPLY:
+        r.r = s.r * (1.0f - d.a + d.r) + d.r * (1.0f - ar);
+        r.g = s.g * (1.0f - d.a + d.g) + d.g * (1.0f - ag);
+        r.b = s.b * (1.0f - d.a + d.b) + d.b * (1.0f - ab);
+        r.a = s.a + d.a * (1.0f - s.a);
+        break;
+
+    case VG_BLEND_SCREEN:
+        r.r = s.r + d.r * (1.0f - s.r);
+        r.g = s.g + d.g * (1.0f - s.g);
+        r.b = s.b + d.b * (1.0f - s.b);
+        r.a = s.a + d.a * (1.0f - s.a);
+        break;
+
+    case VG_BLEND_DARKEN:
+        r.r = RI_MIN(s.r + d.r * (1.0f - ar), d.r + s.r * (1.0f - d.a));
+        r.g = RI_MIN(s.g + d.g * (1.0f - ag), d.g + s.g * (1.0f - d.a));
+        r.b = RI_MIN(s.b + d.b * (1.0f - ab), d.b + s.b * (1.0f - d.a));
+        r.a = s.a + d.a * (1.0f - s.a);
+        break;
+
+    case VG_BLEND_LIGHTEN:
+        r.r = RI_MAX(s.r + d.r * (1.0f - ar), d.r + s.r * (1.0f - d.a));
+        r.g = RI_MAX(s.g + d.g * (1.0f - ag), d.g + s.g * (1.0f - d.a));
+        r.b = RI_MAX(s.b + d.b * (1.0f - ab), d.b + s.b * (1.0f - d.a));
+        //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a)
+        //in practice there can be a very slight difference because
+        //of the max operation in the blending formula that may cause color to exceed alpha.
+        //Because of this, we compute the result both ways and return the maximum.
+        r.a = RI_MAX(s.a + d.a * (1.0f - s.a), d.a + s.a * (1.0f - d.a));
+        break;
+
+    default:
+        RI_ASSERT(blendMode == VG_BLEND_ADDITIVE);
+        r.r = RI_MIN(s.r + d.r, 1.0f);
+        r.g = RI_MIN(s.g + d.g, 1.0f);
+        r.b = RI_MIN(s.b + d.b, 1.0f);
+        r.a = RI_MIN(s.a + d.a, 1.0f);
+        break;
+    }
+    return r;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Applies color transform.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::colorTransform(Color& c) const
+{
+    if(m_colorTransform)
+    {
+        c.unpremultiply();
+        c.luminanceToRGB();
+        c.r = c.r * m_colorTransformValues[0] + m_colorTransformValues[4];
+        c.g = c.g * m_colorTransformValues[1] + m_colorTransformValues[5];
+        c.b = c.b * m_colorTransformValues[2] + m_colorTransformValues[6];
+        c.a = c.a * m_colorTransformValues[3] + m_colorTransformValues[7];
+        c.clamp();
+        c.premultiply();
+    }
+}
+
+void PixelPipe::fillSpans(PPVariants& variants, const Span* spans, int nSpans) const
+{
+#if 1
+    PPCompiler& compiler = PPCompiler::getCompiler();
+
+    PPCompiler::PixelPipeHandle handle = compiler.compilePixelPipeline(m_derivedState);
+    if (handle)
+    {
+        PixelPipeFunction func = compiler.getPixelPipePtr(handle);
+        RI_ASSERT(func);
+        func(m_spanUniforms, variants, spans, nSpans);
+        compiler.releasePixelPipeline(handle);
+    } else
+#endif
+    {
+        executePixelPipeline(m_derivedState, m_spanUniforms, variants, spans, nSpans);
+    }
+}
+
+//=======================================================================
+
+}   //namespace OpenVGRI
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riPixelPipe.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,428 @@
+#ifndef __RIPIXELPIPE_H
+#define __RIPIXELPIPE_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Paint and PixelPipe classes.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#include "riImage.h"
+#endif
+
+//=======================================================================
+
+namespace OpenVGRI
+{
+
+struct Span;
+class PPCompiler;
+class PixelPipe;
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Storage and operations for VGPaint.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Paint
+{
+public:
+    enum { GRADIENT_LUT_BITS = 8 };
+    enum { GRADIENT_LUT_COUNT = 1 << GRADIENT_LUT_BITS };
+    enum { GRADIENT_LUT_MASK = (1<<GRADIENT_LUT_BITS)-1 };
+
+    struct GradientStop
+    {
+        GradientStop() : offset(0.0f), color(0.0f, 0.0f, 0.0f, 0.0f, Color::sRGBA) {}
+        RIfloat		offset;
+        Color		color;
+    };
+
+public:
+    Paint();
+    ~Paint();
+    void					addReference()							{ m_referenceCount++; }
+    int						removeReference()						{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+    void                    setColor(const Color& color) {m_paintColor = color; m_paintColor.clamp(); m_paintColor.premultiply(); }
+    void                    setGradientStops(Array<GradientStop>& inputStops, Array<GradientStop>& stops);
+    void                    generateLUT(PixelPipe& pipe, VGImageFormat targetFormat);
+    const IntegerColor*     getGradientLUT() const { return m_gradientLUT; }
+    void                    setLinearGradient(const Vector2& p0, const Vector2& p1);
+    void                    setRadialGradient(const Vector2& c, const Vector2& f, VGfloat r);
+    bool                    linearDegenerate() const;
+    bool                    radialDegenerate() const;
+    Color                   getSolidColor() const;
+    
+    Color integrateColorRamp(RIfloat gmin, RIfloat gmax) const; // \todo Private after modifications.
+    
+public:
+    VGPaintType				m_paintType;
+    Color					m_paintColor;
+    Color					m_inputPaintColor;
+    VGColorRampSpreadMode	m_colorRampSpreadMode;
+    Array<GradientStop>		m_colorRampStops;
+    Array<GradientStop>		m_inputColorRampStops;
+    VGboolean				m_colorRampPremultiplied;
+    Vector2					m_inputLinearGradientPoint0;
+    Vector2					m_inputLinearGradientPoint1;
+    Vector2					m_inputRadialGradientCenter;
+    Vector2					m_inputRadialGradientFocalPoint;
+    RIfloat					m_inputRadialGradientRadius;
+    Vector2					m_linearGradientPoint0;
+    Vector2					m_linearGradientPoint1;
+    Vector2					m_radialGradientCenter;
+    Vector2					m_radialGradientFocalPoint;
+    RIfloat					m_radialGradientRadius;
+    VGTilingMode			m_patternTilingMode;
+    Image*					m_pattern;
+private:
+    Paint(const Paint&);						//!< Not allowed.
+    const Paint& operator=(const Paint&);		//!< Not allowed.
+
+    int						m_referenceCount;
+    IntegerColor            m_gradientLUT[GRADIENT_LUT_COUNT];
+    VGImageFormat           m_lutFormat;
+    bool                    m_gradientStopsChanged;
+    bool                    m_gradientDegenerate;
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Encapsulates all information needed for painting a pixel.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define RGRAD_FLOATS
+#if defined(RGRAD_FLOATS)
+typedef RIfloat RGScalar;
+#else
+typedef double RGScalar;
+#endif
+
+class PixelPipe
+{
+public:
+    enum SamplerType 
+    {
+        SAMPLER_TYPE_NEAREST    = 0,
+        SAMPLER_TYPE_LINEAR     = 1,
+        SAMPLER_TYPE_SIZE
+    };
+    
+    enum TilingMode 
+    {
+        TILING_MODE_PAD         = 0,
+        TILING_MODE_REPEAT      = 1,
+        TILING_MODE_REFLECT     = 2,
+        TILING_MODE_FILL        = 3,
+        TILING_MODE_SIZE
+    };
+    
+    // Span per-pixel variants:
+    struct PPVariants
+    {
+        void*       dst;
+        void*       src;
+        void*       maskPtr;
+        int         coverage;
+
+        RIuint32    dstX;
+
+        RIint32     sx;
+        RIint32     sy;
+
+        RGScalar    rx;
+        RGScalar    ry;
+
+        // \todo Image sampling coordinates will be in fixed point if transform is affine,
+        // in floating point if not.
+        RGScalar    ix;
+        RGScalar    iy;
+
+        RIint32     iImageX;  
+        RIint32     iImageY;
+        RIfloat     fImageX;
+        RIfloat     fImageY;
+        RIfloat     fImageW;
+    };
+    
+    // Uniform state per-pixel
+    // \todo Organize into sub-structures?
+    struct PPUniforms
+    {
+        // \todo Do not store pointers to classes, only atoms! It should make the
+        // dynamic compilation a lot easier.
+        void*           srcPtr;
+        RIint32         srcStride;
+        void*           dstPtr;
+        RIint32         dstStride;
+        void*           maskPtr;
+        int             maskStride;
+        void*           imagePtr;
+        int             imageStride;
+        void*           patternPtr;
+        int             patternStride;
+        const IntegerColor*   gradientLookup;
+        const RIint32*        colorTransformValues;
+
+        // Linear gradient
+        RIint32         dgdx;
+        RIint32         dgdy;
+        RIint32         lgc;
+
+        // Radial gradient
+        RGScalar        rsqrp;
+        RGScalar        rfxp;
+        RGScalar        rfyp;
+        RGScalar        rx0;
+        RGScalar        ry0;
+        RGScalar        rdxdx;
+        RGScalar        rdxdy;
+        RGScalar        rdydx;
+        RGScalar        rdydy;
+
+        // Pattern. Note that pattern and image may be used at the same time.
+        RIint32         paint_width;
+        RIint32         paint_height;
+        RIint32         paint_x0;
+        RIint32         paint_y0;
+        RIint32         paint_dxdx;
+        RIint32         paint_dxdy;
+        RIint32         paint_dydx;
+        RIint32         paint_dydy;
+
+        // Image
+        RIint32         image_iWidth;
+        RIint32         image_iHeight;
+        RIint32         image_ix0;
+        RIint32         image_iy0;
+        RIint32         image_idxdx;
+        RIint32         image_idxdy;
+        RIint32         image_idydx;
+        RIint32         image_idydy;
+
+
+        RIfloat         image_fWidth;
+        RIfloat         image_fHeight;
+        RIfloat         image_fx0;
+        RIfloat         image_fy0;
+        RIfloat         image_fw0;
+        RIfloat         image_fdxdx;
+        RIfloat         image_fdxdy;
+        RIfloat         image_fdydx;
+        RIfloat         image_fdydy;
+        RIfloat         image_fdwdx;
+        RIfloat         image_fdwdy;
+
+        IntegerColor    tileFillColor;
+        IntegerColor    solidColor;
+        RIuint32        packedSolidColor;
+    };
+
+    enum ImageGradientType {
+        GRADIENT_TYPE_INTEGER   = 0,
+        GRADIENT_TYPE_FIXED     = 1,
+        GRADIENT_TYPE_FLOAT     = 2,
+        GRADIENT_TYPE_SIZE
+    };
+
+    // Signature state contains all the information necessary to compile
+    // a pixel-pipeline. Note that some of these are actually derived.
+    // \note REMEMBER TO UPDATE THE COMPILER. For now, there is now
+    // automatic mechanism to propagate changes to that component!
+    struct SignatureState
+    {
+        VGBlendMode         blendMode;
+        VGImageMode         imageMode;
+        VGPaintType         paintType;
+        VGMaskOperation     maskOperation;
+        TilingMode          paintTilingMode;
+        SamplerType         paintSampler;
+        SamplerType         imageSampler;
+
+        ImageGradientType   imageGradientType;
+
+        Color::Descriptor   dstDesc;
+        Color::Descriptor   maskDesc;
+        Color::Descriptor   imageDesc;
+        Color::Descriptor   patternDesc;
+
+        bool                hasMasking;
+        bool                hasImage;
+        bool                hasColorTransform;
+        bool                isRenderToMask;
+        bool                fillColorTransparent;
+        // When using external data for rendering an image: This is the only case
+        // where the data can be invalid in the pixel-pipe.
+        bool                unsafeImageInput; 
+
+    };
+
+public:
+    PixelPipe();	//throws bad_alloc
+    ~PixelPipe();
+
+    void	pixelPipe(int x, int y, RIuint32 coverage) const;	//rasterizer calls this function for each pixel
+    void 	fillSolidSpan(int startX, int y, int nPixels) const;
+    void	setDrawable(Drawable* drawable);
+    void	setBlendMode(VGBlendMode blendMode);
+    RI_INLINE VGBlendMode getBlendMode() const { return m_blendMode; }
+    void    setRenderToMask(bool renderToMask) { m_renderToMask = renderToMask; }
+    void    setMaskOperation(VGMaskOperation maskOperation) { m_maskOperation = maskOperation; }
+    void	setMask(bool masking);
+    void	setImage(Image* image, VGImageMode imageMode);	//image = NULL disables drawImage functionality
+    void	setSurfaceToPaintMatrix(const Matrix3x3& surfaceToPaintMatrix);
+    void	setSurfaceToImageMatrix(const Matrix3x3& surfaceToImageMatrix);
+    void	setImageQuality(VGImageQuality imageQuality);
+    void	setTileFillColor(const Color& c);
+    void	setPaint(Paint* paint);
+    void    setColorTransform(bool enable, RIfloat values[8]);
+    bool    hasColorTransform() const { return m_colorTransform; }
+    RI_INLINE const SignatureState& getSignatureState() const { return m_signatureState; }
+
+    // Functions that determine parts of derived state.
+    void    prepareSpanUniforms(bool aa);
+
+    RI_INLINE VGPaintType getPaintType() const;
+    RI_INLINE bool isMasking() const;
+    void fillSpans(PPVariants& variants, const Span* spans, int nSpans) const;
+
+    void    colorTransform(Color& c) const;
+    void    setColorTransformChanged(bool changed) { m_colorTransformChanged = changed; } // make paint friend and this private!
+    bool    colorTransformChanged() const { return m_colorTransformChanged; }
+    RI_INLINE VGImageMode getImageMode() const { return m_imageMode; }
+
+    RI_INLINE static bool isImageOnly(const SignatureState& state);
+
+private:
+
+    const Image*    getRenderTargetImage() const;
+    VGImageFormat   getPreferredLUTFormat() const;
+
+    void	prepareSolidFill();
+    void    prepareCoverageFill();
+    void    prepareLinearGradient();
+    void    prepareRadialGradient();
+    void    preparePattern();
+    void    prepareImage(bool aa);
+    void    prepareSignatureState();
+    void    prepareRenderToMask();
+    void	linearGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const;
+    void	radialGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const;
+    Color	colorRamp(RIfloat gradient, RIfloat rho) const;
+    Color	blend(const Color& s, RIfloat ar, RIfloat ag, RIfloat ab, const Color& d, VGBlendMode blendMode) const;
+
+    PixelPipe(const PixelPipe&);						//!< Not allowed.
+    const PixelPipe& operator=(const PixelPipe&);		//!< Not allowed.
+
+    Drawable*               m_drawable;
+    bool					m_masking;
+    Image*					m_image;
+    // \todo LUT within the paint class broke constness of paint.
+    Paint*			        m_paint;
+    Paint					m_defaultPaint;
+    VGBlendMode				m_blendMode;
+    VGImageMode				m_imageMode;
+    VGImageQuality			m_imageQuality;
+    Color					m_tileFillColor;
+    bool                    m_colorTransform;
+    RIfloat                 m_colorTransformValues[8];
+    RIint32                 m_iColorTransformValues[8];
+    Matrix3x3				m_surfaceToPaintMatrix;
+    Matrix3x3				m_surfaceToImageMatrix;
+    Matrix3x3               m_paintToSurfaceMatrix;
+    VGMaskOperation         m_maskOperation;
+    bool                    m_renderToMask;
+    bool                    m_colorTransformChanged;
+
+public:
+
+    enum { COLOR_TRANSFORM_BITS = 8 };
+    enum { COLOR_TRANSFORM_ONE = (1<<COLOR_TRANSFORM_BITS) };
+    enum { COLOR_TRANSFORM_MASK = (COLOR_TRANSFORM_ONE - 1) };
+    enum { GRADIENT_BITS = 16 };
+    enum { GRADIENT_MASK = (1<<GRADIENT_BITS)-1 };
+    enum { SAMPLE_BITS = 8 };
+    enum { SAMPLE_MASK = (1<<SAMPLE_BITS)-1 };
+
+private:
+
+
+    SignatureState          m_signatureState;
+    SignatureState          m_derivedState;
+
+    PPUniforms  m_spanUniforms;
+};
+
+RI_INLINE VGPaintType PixelPipe::getPaintType() const
+{
+    if (m_paint->m_paintType == VG_PAINT_TYPE_COLOR)
+        return VG_PAINT_TYPE_COLOR;
+
+    if (m_paint->m_paintType == VG_PAINT_TYPE_PATTERN && !m_paint->m_pattern)
+        return VG_PAINT_TYPE_COLOR;
+
+    if (m_paint->m_paintType == VG_PAINT_TYPE_LINEAR_GRADIENT && m_paint->linearDegenerate())
+        return VG_PAINT_TYPE_COLOR;
+
+    if (m_paint->m_paintType == VG_PAINT_TYPE_RADIAL_GRADIENT && m_paint->radialDegenerate())
+        return VG_PAINT_TYPE_COLOR;
+
+    return m_paint->m_paintType;
+}
+
+RI_INLINE bool PixelPipe::isMasking() const
+{
+    return m_masking;
+}
+
+RI_INLINE /*static*/ bool PixelPipe::isImageOnly(const SignatureState& state)
+{
+    if (state.hasImage)
+        return (state.imageMode == VG_DRAW_IMAGE_NORMAL) ? true : false;
+    else
+        return false;
+}
+
+//=======================================================================
+
+}	//namespace OpenVGRI
+
+//=======================================================================
+
+#endif /* __RIPIXELPIPE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riRasterizer.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1073 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of polygon rasterizer.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "riRasterizer.h"
+
+// TEMP!
+#ifndef __SFCOMPILER_H
+#   include "sfCompiler.h"
+#endif
+
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Rasterizer constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Rasterizer::Rasterizer() :
+    m_covBuffer(NULL),
+    m_covBufferSz(0),
+    m_edges(),
+    m_scissorEdges(),
+    m_scissor(false),
+    m_aa(true),
+    m_vpx(0),
+    m_vpy(0),
+    m_vpwidth(0),
+    m_vpheight(0),
+    m_fillRule(VG_EVEN_ODD),
+    m_pixelPipe(NULL),
+    m_nSpans(0)
+{}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Rasterizer destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Rasterizer::~Rasterizer()
+{
+    if(m_covBuffer)
+        RI_DELETE_ARRAY(m_covBuffer);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Removes all appended edges.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define EDGE_TERMINATOR 0xFFFFFFFFu
+
+void Rasterizer::clear()
+{
+    //m_edges.clear();
+    for (int i = 0; i < m_edges.size(); i++)
+        m_edges[i] = EDGE_TERMINATOR;
+
+    m_edgePool.clear();
+
+    m_edgeMin.set(0x7fffffffu, 0x7fffffffu);
+    m_edgeMax.set(0x80000000, 0x80000000);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Appends an edge to the rasterizer.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Rasterizer::addBBox(const IVector2& v)
+{
+    if(v.x < m_edgeMin.x) m_edgeMin.x = v.x;
+    if(v.y < m_edgeMin.y) m_edgeMin.y = v.y;
+    if(v.x > m_edgeMax.x) m_edgeMax.x = v.x;
+    if(v.y > m_edgeMax.y) m_edgeMax.y = v.y;
+}
+
+void Rasterizer::pushEdge(const Edge& edge)
+{
+    addBBox(edge.v0);
+    addBBox(edge.v1);
+
+    // Only add processed edges.
+
+    RI_ASSERT(edge.v0.y >= 0);
+    RI_ASSERT(edge.v0.y < edge.v1.y);	//horizontal edges should have been dropped already
+
+    ActiveEdge ae;
+    ae.direction = edge.direction;
+
+    // \todo Adjust for non-AA cases
+    // \todo verySteep is temporary. Either clip to right edge also, or validate that a proper slope can be
+    // calculated here.
+    const int slope	= RI_SAT_SHL((edge.v1.x - edge.v0.x), RASTERIZER_BITS - X_BITS) / (edge.v1.y - edge.v0.y);
+    //const bool verySteep = RI_INT_ABS(edge.v1.x - edge.v0.x) > (1 << (30-RASTERIZER_BITS)) ? true : false;
+    //const int slope	= verySteep ? 1 << 30 : RI_SHL((edge.v1.x - edge.v0.x), RASTERIZER_BITS - X_BITS) / (edge.v1.y - edge.v0.y);
+    // slope: SI.(RASTERIZER_BITS - Y_BITS)
+    const int yF 	= edge.v0.y & Y_MASK;
+    // \todo See verySteep note for this hack also. (Clip to right edge?)
+    const int xRef 	= RI_SAT_SHL(edge.v0.x, RASTERIZER_BITS - X_BITS) - (yF * slope);
+    //const int xRef 	= edge.v0.x > (1<<(30-RASTERIZER_BITS)) ? 1<<30 : RI_SHL(edge.v0.x, RASTERIZER_BITS - X_BITS) - (yF * slope);
+
+    RI_ASSERT(RI_INT_ABS(edge.v0.y <= 32767));
+    RI_ASSERT(RI_INT_ABS(edge.v1.y <= 32767));
+
+    ae.yStart 		= (RIint16)edge.v0.y;
+    ae.yEnd 	  	= (RIint16)edge.v1.y;
+    ae.xRef 		= xRef;
+    ae.slope 		= slope;
+    // Scanline range.
+    ae.minx         = xRef >> RASTERIZER_BITS;
+    ae.maxx         = (xRef + slope * (1<<Y_BITS)) >> RASTERIZER_BITS;
+
+    if (ae.minx > ae.maxx)
+        RI_ANY_SWAP(ActiveEdge::XCoord, ae.minx, ae.maxx);
+
+    if (ae.maxx < 0)
+        ae.minx = ae.maxx = LEFT_DISCARD_SHORT;
+
+    if (m_edges[ae.yStart>>Y_BITS] == EDGE_TERMINATOR)
+        ae.next = EDGE_TERMINATOR;
+    else
+        ae.next = m_edges[ae.yStart>>Y_BITS];
+
+    m_edgePool.push_back(ae);	//throws bad_alloc
+
+    RI_ASSERT(m_edgePool.size() > 0);
+    m_edges[ae.yStart>>Y_BITS] = m_edgePool.size()-1;
+}
+
+/**
+ * \brief   Clips an edge and if something remains, adds it to the list of edges.
+ * \todo    Enhance precision: Currently this just uses doubles and gets away with
+ *          it in most cases.
+ */
+void Rasterizer::clipAndAddEdge(Edge& edge)
+{
+    //if (m_edges.size() > 48)
+        //return;
+    // Check y-clips
+    // \todo Reduce amount of clips.
+    bool outLeft[2] = {(edge.v0.x < m_vpMinx), (edge.v1.x < m_vpMinx)};
+    bool outRight[2] = {(edge.v0.x > m_vpMaxx), (edge.v1.x > m_vpMaxx)};
+    bool outTop[2] = {(edge.v0.y < m_vpMiny), (edge.v1.y < m_vpMiny)};
+    bool outBottom[2] = {(edge.v0.y > m_vpMaxy), (edge.v1.y > m_vpMaxy)};
+
+    if (!(outLeft[0] || outLeft[1] || outRight[0] || outRight[1] || outTop[0] || outTop[1] || outBottom[0] || outBottom[1]))
+    {
+        pushEdge(edge);
+        return;
+    }
+
+    // \todo Make sure that checking out-of-right works with the scanconverter.
+    if ((outBottom[0] && outBottom[1]) || (outTop[0] && outTop[1]))
+        return; // Out of bounds
+
+    // \todo Clip to right edge of screen.
+    // \todo Make slope-calculation and signs consistent.
+    //
+    if (outTop[0] || outBottom[1])
+    {
+        // Clip to top/bottom.
+        double slope = (double)(edge.v1.x - edge.v0.x)/(edge.v1.y - edge.v0.y);
+
+        if (outTop[0])
+        {
+            RI_ASSERT(-(RIint64)edge.v0.y >= 0);
+            RIint32 dx = RI_ROUND_TO_INT(-slope * edge.v0.y);
+            edge.v0.y = 0;
+            edge.v0.x += dx;
+        }
+
+        if (outBottom[1])
+        {
+            RIint32 dy = edge.v1.y - m_vpMaxy;
+            RI_ASSERT(dy >= 0);
+            RIint32 dx = -RI_ROUND_TO_INT(slope * dy);
+            edge.v1.y = m_vpMaxy;
+            edge.v1.x += dx;
+        }
+
+    }
+
+    if (edge.v0.y >= edge.v1.y)
+        return;
+
+    // \todo Recheck left/right.
+    outLeft[0] = (edge.v0.x < m_vpMinx); outLeft[1] = (edge.v1.x < m_vpMinx);
+    outRight[1] = (edge.v0.x > m_vpMaxx); outRight[1] = (edge.v1.x > m_vpMaxx);
+
+    if (outLeft[0] && outLeft[1])
+    {
+        edge.v0.x = m_vpMinx;
+        edge.v1.x = m_vpMinx;
+        pushEdge(edge);
+        return;
+    }
+    if (outRight[0] && outRight[1])
+    {
+        edge.v0.x = m_vpMaxx;
+        edge.v1.x = m_vpMaxx;
+        pushEdge(edge);
+        return;
+    }
+
+    // From outside -> screen
+    if (outLeft[0] || outRight[1])
+    {
+        // infinite slope?
+        double slope = (double)((RIint64)edge.v1.y - edge.v0.y)/((RIint64)edge.v1.x - edge.v0.x);
+
+        if (outLeft[0])
+        {
+            RIint32 dx = edge.v0.x;
+            //RI_ASSERT(dx >= 0);
+            // Note the sign.
+            RIint32 dy = RI_ROUND_TO_INT(-slope * dx);
+
+            Edge vpart = edge;
+            vpart.v1.y = edge.v0.y + dy;
+            //vpart.v1.x = edge.v0.x; // = 0?
+            // \note This should be flagged instead of setting the smallest possible
+            // value because of extremely gentle slopes may cause bugs:
+            vpart.v1.x = vpart.v0.x = -0x100000;
+
+            if (vpart.v1.y > vpart.v0.y)
+                pushEdge(vpart);
+
+            edge.v0.y += dy;
+            edge.v0.x = 0;
+        }
+    }
+    // From screen -> outside
+    if (outLeft[1] || outRight[0])
+    {
+        // infinite slope?
+        double slope = (double)((RIint64)edge.v1.y - edge.v0.y)/((RIint64)edge.v1.x - edge.v0.x);
+
+        if (outLeft[1])
+        {
+            RIint32 dx = edge.v0.x;
+            RI_ASSERT(dx >= 0);
+            RIint32 dy = RI_ROUND_TO_INT(-slope * dx);
+
+            Edge vpart = edge;
+            vpart.v0.y = edge.v0.y + dy;
+            vpart.v1.x = vpart.v0.x = LEFT_DISCARD;
+
+            if (vpart.v1.y > vpart.v0.y)
+                pushEdge(vpart);
+
+            edge.v1.y = edge.v0.y + dy;
+            edge.v1.x = 0;
+        }
+    }
+
+    if (edge.v0.y >= edge.v1.y)
+        return;
+
+    // Finally, add the edge:
+    pushEdge(edge);
+}
+
+void Rasterizer::addEdge(const Vector2& v0, const Vector2& v1)
+{
+    if( m_edges.size() >= RI_MAX_EDGES )
+        throw std::bad_alloc();	//throw an out of memory error if there are too many edges
+
+    Edge e;
+
+    {
+        IVector2 i0(RI_ROUND_TO_INT(v0.x * (1<<X_BITS)), RI_ROUND_TO_INT(v0.y * (1<<Y_BITS)));
+        IVector2 i1(RI_ROUND_TO_INT(v1.x * (1<<X_BITS)), RI_ROUND_TO_INT(v1.y * (1<<Y_BITS)));
+
+        if(i0.y == i1.y)
+            return;	//skip horizontal edges (they don't affect rasterization since we scan horizontally)
+
+        if (i0.y < i1.y)
+        {
+            // Edge is going upward
+            e.v0 = i0;
+            e.v1 = i1;
+            e.direction = 1;
+        }
+        else
+        {
+            // Edge is going downward
+            e.v0 = i1;
+            e.v1 = i0;
+            e.direction = -1;
+        }
+    }
+
+    // Clip and insert.
+
+    clipAndAddEdge(e);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Set up rasterizer
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Rasterizer::setup(int vpx, int vpy, int vpwidth, int vpheight, VGFillRule fillRule, const PixelPipe* pixelPipe)
+{
+    RI_ASSERT(vpwidth >= 0 && vpheight >= 0);
+    RI_ASSERT(vpx + vpwidth >= vpx && vpy + vpheight >= vpy);
+    RI_ASSERT(fillRule == VG_EVEN_ODD || fillRule == VG_NON_ZERO);
+    RI_ASSERT(pixelPipe);
+
+    clear();
+
+    m_vpx = vpx;
+    m_vpy = vpy;
+    m_vpwidth = vpwidth;
+    m_vpheight = vpheight;
+
+    if (m_vpheight > m_edges.size())
+    {
+        int os = m_edges.size();
+        m_edges.resize(m_vpheight);
+        for (int i = os; i < m_edges.size(); i++)
+            m_edges[i] = EDGE_TERMINATOR;
+    }
+
+    m_vpMinx = RI_SHL(vpx, X_BITS);
+    m_vpMiny = RI_SHL(vpy, Y_BITS);
+    m_vpMaxx = RI_SHL(vpx + vpwidth, X_BITS);
+    m_vpMaxy = RI_SHL(vpy + vpheight, Y_BITS);
+
+    m_fillRule = fillRule;
+
+    RIuint32 fillRuleMask = fillRule == VG_NON_ZERO ? 0xffffffffu : 1;
+    m_fillRuleMask = fillRuleMask;
+
+    m_pixelPipe = pixelPipe;
+    m_covMinx = vpx+vpwidth;
+    m_covMiny = vpy+vpheight;
+    m_covMaxx = vpx;
+    m_covMaxy = vpy;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Sets scissor rectangles.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Rasterizer::setScissor(const Array<Rectangle>& scissors)
+{
+    try
+    {
+        m_scissorEdges.clear();
+        for(int i=0;i<scissors.size();i++)
+        {
+            if(scissors[i].width > 0 && scissors[i].height > 0)
+            {
+                ScissorEdge e;
+                e.miny = scissors[i].y;
+                e.maxy = RI_INT_ADDSATURATE(scissors[i].y, scissors[i].height);
+
+                e.x = scissors[i].x;
+                e.direction = 1;
+                m_scissorEdges.push_back(e);	//throws bad_alloc
+                e.x = RI_INT_ADDSATURATE(scissors[i].x, scissors[i].width);
+                e.direction = -1;
+                m_scissorEdges.push_back(e);	//throws bad_alloc
+            }
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        m_scissorEdges.clear();
+        throw;
+    }
+}
+
+void Rasterizer::setScissoring(bool enabled)
+{
+    m_scissor = enabled;
+}
+
+static RI_INLINE void small_memcpy32(void* dst, const void* src, size_t n)
+{
+    RIuint32 *d = (RIuint32*)dst;
+    const RIuint32 *s = (const RIuint32*)src;
+    while(n)
+    {
+        *d++ = *s++;
+        n-=4;
+    }
+}
+
+// \todo Move this to some debug file or remove.
+#if defined(USE_SSE2) && !defined(_WIN32)
+RI_INLINE static void print128(__m128i ll)
+{
+#if defined(RI_DEBUG)
+    unsigned long long v[2];
+    _mm_storeu_pd((double*)v, (__m128d)ll);
+    RI_PRINTF("0x%016llx %016llx\n", v[0], v[1]);
+#else
+    (void)ll;
+#endif
+}
+#endif
+
+#if defined(USE_SSE2)
+RI_INLINE static __m128i mm_mul4x32(const __m128i a, const __m128i b) {
+     __m128i res;
+#if (_MSC_VER > 1400 )
+     // \todo Simpler way to do this on intel?
+     __m128i m0 = _mm_mul_epu32(a, _mm_shuffle_epi32(b, _MM_SHUFFLE(1, 1, 0, 0)));
+     __m128i m1 = _mm_mul_epu32(a, _mm_shuffle_epi32(b, _MM_SHUFFLE(3, 3, 2, 2)));
+
+     res = _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(m0), _mm_castsi128_ps(m1), _MM_SHUFFLE(2, 0, 2, 0)));
+#else
+     __asm {
+         movdqa xmm1, a;
+         movdqa xmm2, b;
+         pshufd xmm3, xmm2, 80;
+         movdqa xmm0, xmm1;
+
+         pshufd xmm2, xmm2, 250;
+         pmuludq xmm0, xmm3;
+         pmuludq xmm1, xmm2;
+
+         shufps xmm0, xmm1, 136;
+         movdqa res, xmm0;
+     }
+#endif
+     return res;
+}
+#endif
+
+#if defined(USE_SSE2)
+RI_INLINE static void mm_get_xmasks(const __m128i& coords, const __m128i& sampleCoords, __m128i& slWindMask, __m128i& pxWindMask)
+{
+    const __m128i z = _mm_setzero_si128();
+    const __m128i xMask = _mm_cmpeq_epi16(_mm_srai_epi16(coords, Rasterizer::RASTERIZER_BITS), z);
+    const __m128i sCmp = _mm_or_si128(_mm_cmpgt_epi16(sampleCoords, coords), _mm_cmpeq_epi16(sampleCoords, coords));
+    //const __m128i sCmp = _mm_cmplt_epi16(coords, sampleCoords);
+    slWindMask = xMask;
+    pxWindMask = _mm_and_si128(xMask, sCmp);
+}
+#endif
+
+RI_INLINE static void getVerticalSubpixels(int iY, int yStart, int yEnd, int& py0, int& py1)
+{
+    const int cy = iY << Rasterizer::Y_BITS;
+    py0 = cy > yStart ? 0 : yStart & Rasterizer::Y_MASK;
+    py1 = (RI_INT_MIN(yEnd, cy + (1<<Rasterizer::Y_BITS)) - 1) & Rasterizer::Y_MASK;
+}
+
+RI_INLINE static void applyLeftEdge(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& scanline, int intY)
+{
+    // Applies the whole edge at a time. Make sure xRight < x for all y.
+    // \todo Remove duplicate code for determining the active samples
+#if defined(USE_SSE2)
+    int py0, py1;
+
+    getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1);
+
+    const __m128i csteps = _mm_set_epi16(7,6,5,4,3,2,1,0);
+
+    const __m128i ssePy0 = _mm_set1_epi16(py0-1);
+    const __m128i ssePy1 = _mm_set1_epi16(py1+1);
+
+    const __m128i yMask = _mm_and_si128(_mm_cmpgt_epi16(csteps, ssePy0), _mm_cmplt_epi16(csteps, ssePy1));
+    const __m128i dir = _mm_set1_epi16(currAe.direction);
+
+    scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(yMask, dir));
+
+#else
+    RI_ASSERT(false); // Not implemented yet.
+#endif
+}
+
+RI_INLINE static void applyLeftEdgeNoAA(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& scanline, int intY)
+{
+    // Applies the whole edge at a time. Make sure xRight < x for all y.
+    // \todo Remove duplicate code for determining the active samples?
+#if defined(USE_SSE2)
+    int py0, py1;
+
+    getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1);
+
+    //const __m128i csteps = _mm_set_epi16(4,4,4,4,4,4,4,4);
+
+    __m128i yMask;
+
+    if (py0 <= 4 && py1 >= 4)
+        yMask = _mm_set1_epi8(-1);
+    else
+        yMask = _mm_set1_epi8(0);
+
+    const __m128i dir = _mm_set1_epi16(currAe.direction);
+
+    scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(yMask, dir));
+    //scanline.sseWinding = _mm_add_epi32(scanline.sseWinding, dir);
+
+#else
+    RI_ASSERT(false); // Not implemented yet.
+#endif
+}
+
+RI_INLINE void calculateAEWinding(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& pixel, Rasterizer::Windings& scanline, int intY, int pixelX)
+{
+#define QUEEN_COORD(Y) ((Y<<(Rasterizer::RASTERIZER_BITS - Rasterizer::SAMPLE_BITS)) + (1<<(Rasterizer::RASTERIZER_BITS-Rasterizer::SAMPLE_BITS-1)))
+
+#if !defined(USE_SSE2)
+    static const int queenCoords[(1<<Rasterizer::SAMPLE_BITS)] = {
+        QUEEN_COORD(3), QUEEN_COORD(7), QUEEN_COORD(0), QUEEN_COORD(2),
+        QUEEN_COORD(5), QUEEN_COORD(1), QUEEN_COORD(6), QUEEN_COORD(4)
+    };
+
+    const int ix = pixelX >> Rasterizer::RASTERIZER_BITS;
+    const int cy = intY << Rasterizer::Y_BITS;
+
+    const int py0 = cy > currAe.yStart ? 0 : currAe.yStart & Rasterizer::Y_MASK;
+    const int py1 = (RI_INT_MIN(currAe.yEnd, cy + (1<<Rasterizer::Y_BITS)) - 1) & Rasterizer::Y_MASK;
+
+    int edgeX = currAe.xRef + (cy + py0 - (currAe.yStart & ~Rasterizer::Y_MASK)) * currAe.slope;
+
+    RI_ASSERT(py1 >= py0);
+
+    for (int s = py0; s <= py1; s++)
+    {
+        const int sampleX = pixelX + queenCoords[s];
+
+        //compute winding number by evaluating the edge functions of edges to the left of the sampling point
+        if(((edgeX >> Rasterizer::RASTERIZER_BITS) == ix))
+        {
+            if (sampleX >= edgeX)
+            {
+                pixel.winding[s] += currAe.direction;
+            }
+            scanline.winding[s] += currAe.direction;
+        }
+
+        edgeX += currAe.slope;
+    }
+#else
+
+    __m128i qCoords = _mm_set_epi16(
+        QUEEN_COORD(4), QUEEN_COORD(6), QUEEN_COORD(1), QUEEN_COORD(5),
+        QUEEN_COORD(2), QUEEN_COORD(0), QUEEN_COORD(7), QUEEN_COORD(3));
+
+    RI_ASSERT(Rasterizer::RASTERIZER_BITS <= 14);
+
+    // TEROP: Optimize conditions.
+    int py0, py1;
+    getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1);
+
+    const int cy = intY << Rasterizer::Y_BITS;
+
+    const __m128i csteps0 = _mm_set_epi32(3,2,1,0);
+    const __m128i csteps1 = _mm_set_epi32(7,6,5,4);
+
+    const __m128i ssePy0 = _mm_set1_epi32(py0-1);
+    const __m128i ssePy1 = _mm_set1_epi32(py1+1);
+
+    const __m128i yMask0 = _mm_and_si128(_mm_cmpgt_epi32(csteps0, ssePy0), _mm_cmplt_epi32(csteps0, ssePy1));
+    const __m128i yMask1 = _mm_and_si128(_mm_cmpgt_epi32(csteps1, ssePy0), _mm_cmplt_epi32(csteps1, ssePy1));
+
+    const int edgeX = currAe.xRef + (cy - (currAe.yStart & ~Rasterizer::Y_MASK)) * currAe.slope;
+    const __m128i xStart = _mm_set1_epi32(edgeX - pixelX);
+
+    const __m128i xs0 = _mm_set1_epi32(currAe.slope);
+
+    __m128i xAdd0 = mm_mul4x32(xs0, csteps0);
+    __m128i xAdd1 = mm_mul4x32(xs0, csteps1);
+    __m128i coords0 = _mm_add_epi32(xStart, xAdd0);
+    __m128i coords1 = _mm_add_epi32(xStart, xAdd1);
+    __m128i coords = _mm_packs_epi32(coords0, coords1);
+
+    __m128i dir = _mm_set1_epi16(currAe.direction);
+    __m128i yMask = _mm_packs_epi32(yMask0, yMask1);
+    __m128i mDir = _mm_and_si128(dir, yMask);
+
+    __m128i sampleCoords = qCoords;
+
+    __m128i sw, pw;
+    mm_get_xmasks(coords, sampleCoords, sw, pw);
+
+    pixel.sseWinding = _mm_add_epi16(pixel.sseWinding, _mm_and_si128(pw, mDir));
+    scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(sw, mDir));
+#endif
+
+#undef QUEEN_COORD
+
+}
+
+/**
+ * \brief   Calculate winding using one sample only.
+ * \note    This uses most of the same code as the AA-case even though it is not
+ *          necessary (one sample would be enough).
+ */
+RI_INLINE void calculateAEWindingNoAA(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& pixel, Rasterizer::Windings& scanline, int intY, int pixelX)
+{
+#if defined(USE_SSE2)
+
+#define QUEEN_COORD(Y) ((Y<<(Rasterizer::RASTERIZER_BITS - Rasterizer::SAMPLE_BITS)) + (1<<(Rasterizer::RASTERIZER_BITS-Rasterizer::SAMPLE_BITS-1)))
+    const int half = 1<<(Rasterizer::RASTERIZER_BITS-1);
+
+    __m128i sampleCoords = _mm_set1_epi16(half);
+
+    RI_ASSERT(Rasterizer::RASTERIZER_BITS <= 14);
+
+    const int cy = intY << Rasterizer::Y_BITS;
+
+    int py0, py1;
+    getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1);
+
+    __m128i yMask;
+
+    if (py0 <= 4 && py1 >= 4)
+        yMask = _mm_set1_epi8(-1);
+    else
+        yMask = _mm_set1_epi8(0);
+
+    const __m128i csteps0 = _mm_set_epi32(4,4,4,4);
+    const __m128i csteps1 = _mm_set_epi32(4,4,4,4);
+
+    const int edgeX = currAe.xRef + (cy - (currAe.yStart & ~Rasterizer::Y_MASK)) * currAe.slope;
+    const __m128i xStart = _mm_set1_epi32(edgeX - pixelX);
+
+    const __m128i xs0 = _mm_set1_epi32(currAe.slope);
+
+    __m128i xAdd0 = mm_mul4x32(xs0, csteps0);
+    __m128i xAdd1 = mm_mul4x32(xs0, csteps1);
+    __m128i coords0 = _mm_add_epi32(xStart, xAdd0);
+    __m128i coords1 = _mm_add_epi32(xStart, xAdd1);
+    __m128i coords = _mm_packs_epi32(coords0, coords1);
+
+    __m128i dir = _mm_set1_epi16(currAe.direction);
+    __m128i mDir = _mm_and_si128(dir, yMask);
+    //__m128i mDir = dir;
+
+    __m128i sw, pw;
+    mm_get_xmasks(coords, sampleCoords, sw, pw);
+
+    pixel.sseWinding = _mm_add_epi16(pixel.sseWinding, _mm_and_si128(pw, mDir));
+    scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(sw, mDir));
+
+#undef QUEEN_COORD
+
+#else
+    RI_ASSERT(false); // Not implemented.
+#endif
+}
+
+#if defined(USE_SSE2)
+RI_INLINE static int mm_winding_to_coverage(const Rasterizer::Windings& pixel, int fillRuleMask)
+{
+    // This version uses SSE2 counters.
+    __m128i mask = _mm_set1_epi16(fillRuleMask);
+    __m128i t = _mm_and_si128(mask, pixel.sseWinding);
+    __m128i z = _mm_setzero_si128();
+    __m128i isz = _mm_cmpeq_epi16(t, z);
+    __m128i ones = _mm_set1_epi16(1);
+    __m128i res = _mm_add_epi16(ones, isz);
+    __m128i add0 = _mm_add_epi16(res, _mm_shuffle_epi32(res, _MM_SHUFFLE(2, 3, 2, 3)));
+    __m128i add1 = _mm_add_epi16(add0, _mm_shuffle_epi32(add0, _MM_SHUFFLE(1, 1, 1, 1)));
+    __m128i add2 = _mm_add_epi16(add1, _mm_shufflelo_epi16(add1, _MM_SHUFFLE(1, 1, 1, 1)));
+
+    int nSamples = _mm_cvtsi128_si32(add2) & 0xff;
+    return nSamples;
+}
+#endif
+
+#define RI_DEBUG
+#if defined(RI_DEBUG)
+void maybeDumpEdges(Array<Rasterizer::ActiveEdge> &edgePool)
+{
+    return;
+    // \note This gives an idea about the edges at the rasterization stage.
+    // Input edges must be output at a different stage.
+    RI_PRINTF("lines = []\n");
+    for (int i = 0 ; i < edgePool.size(); i++)
+    {
+        const int slope = edgePool[i].slope;
+        int x0, x1, y0, y1;
+        y0 = edgePool[i].yStart;
+        y1 = edgePool[i].yEnd;
+        x0 = edgePool[i].xRef + (slope * (y0 & Rasterizer::Y_MASK));
+        x1 = (edgePool[i].xRef + (slope * (y1 - (y0 & ~Rasterizer::Y_MASK))))>>(Rasterizer::RASTERIZER_BITS-Rasterizer::X_BITS);
+        RI_PRINTF("lines += [[%d, %d], [%d, %d]]\n",x0>>(Rasterizer::RASTERIZER_BITS-Rasterizer::X_BITS),y0,x1,y1);
+    }
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Calls PixelPipe::pixelPipe for each pixel with coverage greater
+*			than zero.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+void Rasterizer::fill()
+{
+    if(m_scissor && !m_scissorEdges.size())
+        return;	//scissoring is on, but there are no scissor rectangles => nothing is visible
+
+    int firstAe = 0;
+
+    //proceed scanline by scanline
+    //keep track of edges that can intersect the pixel filters of the current scanline (Active Edge Table)
+    //until all pixels of the scanline have been processed
+    //  for all sampling points of the current pixel
+    //    determine the winding number using edge functions
+    //    add filter weight to coverage
+    //  divide coverage by the number of samples
+    //  determine a run of pixels with constant coverage
+    //  call fill callback for each pixel of the run
+
+    const int fillRuleMask = m_fillRuleMask;
+
+    int bbminx = (m_edgeMin.x >> X_BITS);
+    int bbminy = (m_edgeMin.y >> Y_BITS);
+    int bbmaxx = (m_edgeMax.x >> X_BITS)+1;
+    int bbmaxy = (m_edgeMax.y >> Y_BITS)+1;
+    int sx = RI_INT_MAX(m_vpx, bbminx);
+    int ex = RI_INT_MIN(m_vpx+m_vpwidth, bbmaxx);
+    int sy = RI_INT_MAX(m_vpy, bbminy);
+    int ey = RI_INT_MIN(m_vpy+m_vpheight, bbmaxy);
+    if(sx < m_covMinx) m_covMinx = sx;
+    if(sy < m_covMiny) m_covMiny = sy;
+    if(ex > m_covMaxx) m_covMaxx = ex;
+    if(ey > m_covMaxy) m_covMaxy = ey;
+
+#if 0
+    // Dump edges:
+    static bool dump = true;
+    if (dump)
+    {
+        RI_PRINTF("lines = []\n");
+        for (int ie = 0; dump && ie < m_edgePool.size(); ie++)
+        {
+            RI_PRINTF("lines += [[%d, %d], [%d, %d]]\n",m_edgePool[ie].v0.x, m_edgePool[ie].v0.y, m_edgePool[ie].v1.x, m_edgePool[ie].v1.y);
+        }
+        dump = false;
+    }
+
+#endif
+    int debugMagic = 0;
+
+    m_aet.clear();
+
+#if defined(RI_DEBUG)
+    maybeDumpEdges(m_edgePool);
+#endif
+
+    //fill the screen
+    for(int j = sy; j < ey; j++)
+    {
+        Windings scanlineWinding;
+        const int cminy = j << Y_BITS;
+
+        if (m_scissor)
+        {
+            // Gather scissor edges intersecting this scanline
+            // \todo Don't clear, remove unused instead!
+            m_scissorAet.clear();
+
+            for(int e = 0; e < m_scissorEdges.size(); e++)
+            {
+                const ScissorEdge& se = m_scissorEdges[e];
+
+                if(j >= se.miny && j < se.maxy)
+                    m_scissorAet.push_back(m_scissorEdges[e]);	//throws bad_alloc
+            }
+
+            //sort scissor AET by edge x
+            if (m_scissor)
+                m_scissorAet.sort();
+        }
+
+        // Drop unused edges, update remaining.
+        // \todo Combine with full sweep. Use a sort-friendly edge-discard.
+        for (int iae = firstAe; iae < m_aet.size(); iae++)
+        {
+            ActiveEdge& ae = m_aet[iae];
+
+            if (cminy >= ae.yEnd)
+            {
+                m_aet[iae] = m_aet[firstAe];
+                firstAe++;
+                continue;
+            }
+
+            /* Update existing coordinates */
+            // \todo AND instead of shift. See other places also.
+            const int y0 = (ae.yStart & ~Y_MASK);
+            const int x = ae.xRef + ((j << Y_BITS) - y0) * ae.slope;
+            ae.minx = x >> RASTERIZER_BITS;
+            ae.maxx = (x + ae.slope * (1<<Y_BITS)) >> RASTERIZER_BITS;
+
+            if (ae.minx > ae.maxx)
+                RI_ANY_SWAP(ActiveEdge::XCoord, ae.minx, ae.maxx);
+
+            // If the edge is not visible, "mark" it as immediately applicable
+            // \todo Verify that this is the correct procedure.
+
+           if (ae.maxx < 0)
+               ae.minx = ae.maxx = LEFT_DISCARD_SHORT;
+       }
+
+        /* Add new edges */
+
+        RIuint32 aeIndex = m_edges[j];
+        while (aeIndex != EDGE_TERMINATOR)
+        {
+            const ActiveEdge& ae = m_edgePool[aeIndex];
+            m_aet.push_back(ae); // \todo Just copy pointers?
+            aeIndex = ae.next;
+        }
+
+        if (firstAe >= m_aet.size())
+        {
+            RI_ASSERT(firstAe == m_aet.size());
+            continue;	//no edges on the whole scanline, skip it
+        }
+
+        //sort AET by edge minx
+        m_aet.sort(firstAe, m_aet.size() - 1);
+
+        // \todo Optimize adding and updating the edges?
+        if (m_scissor && !m_scissorAet.size())
+            continue;	// Scissoring is on, but there are no scissor rectangles on this scanline.
+
+        //fill the scanline
+        int scissorWinding = m_scissor ? 0 : 1;	//if scissoring is off, winding is always 1
+        int scissorIndex = 0;
+        int aes = firstAe;
+        int aen = firstAe;
+
+        RI_ASSERT(sx >= 0);
+
+#if 1
+        if (m_aa)
+        {
+            while ((aen < m_aet.size()) && (m_aet[aen].maxx < 0))
+            {
+                applyLeftEdge(m_aet[aen], scanlineWinding, j);
+                aen++;
+            }
+        }
+        else
+        {
+            while ((aen < m_aet.size()) && (m_aet[aen].maxx < 0))
+            {
+                applyLeftEdgeNoAA(m_aet[aen], scanlineWinding, j);
+                aen++;
+            }
+        }
+
+#if defined(RI_DEBUG)
+        for (int a = aen; a < m_aet.size(); a++)
+        {
+            RI_ASSERT(m_aet[a].maxx >= 0);
+        }
+#endif
+#endif
+
+        // \todo Combine this with the first check or reorganize the "clipping".
+        if (aen >= m_aet.size())
+            continue; // No edges within viewport. Can happen atm. when all edges are "left".
+
+        for(int i = sx; i < ex;)
+        {
+            //find edges that intersect or are to the left of the pixel antialiasing filter
+            while(aes < m_aet.size() && (i + 1) >= m_aet[aes].minx)
+                aes++;
+            //edges [0,aes[ may have an effect on winding, and need to be evaluated while sampling
+
+            // RIint8 winding[SF_SAMPLES];
+            Windings pixelWinding;
+
+            pixelWinding = scanlineWinding;
+
+            if (m_aa)
+            {
+                for(int e = aen; e < aes; e++)
+                {
+                    const ActiveEdge& currAe = m_aet[e];
+                    calculateAEWinding(currAe, pixelWinding, scanlineWinding, j, i << RASTERIZER_BITS);
+                }
+            }
+            else
+            {
+                for(int e = aen; e < aes; e++)
+                {
+                    const ActiveEdge& currAe = m_aet[e];
+                    calculateAEWindingNoAA(currAe, pixelWinding, scanlineWinding, j, i << RASTERIZER_BITS);
+                }
+            }
+
+            //compute coverage
+            int coverageSamples = 0;
+#if !defined(USE_SSE2)
+
+            for (int s = 0; s < SF_SAMPLES; s++)
+            {
+                if(pixelWinding.winding[s])
+                {
+                    coverageSamples++;
+                }
+            }
+#else
+           coverageSamples = mm_winding_to_coverage(pixelWinding, fillRuleMask);
+            _mm_empty();
+#endif
+
+            //constant coverage optimization:
+            //scan AET from left to right and skip all the edges that are completely to the left of the pixel filter.
+            //since AET is sorted by minx, the edge we stop at is the leftmost of the edges we haven't passed yet.
+            //if that edge is to the right of this pixel, coverage is constant between this pixel and the start of the edge.
+            while(aen < m_aet.size() && m_aet[aen].maxx < i)
+                aen++;
+
+            int endSpan = m_vpx + m_vpwidth;	// endSpan is the first pixel NOT part of the span
+
+            if(aen < m_aet.size())
+            {
+                endSpan = RI_INT_MAX(i+1, RI_INT_MIN(endSpan, m_aet[aen].minx));
+            }
+
+            //fill a run of pixels with constant coverage
+            if(coverageSamples)
+            {
+
+                if (!m_scissor)
+                {
+                    int fillStartX = i;	/* Inclusive */
+                    pushSpan(fillStartX, j, (endSpan - fillStartX), coverageSamples);
+                }
+                else // (scissor)
+                {
+                    int fillStartX = i;
+                    //update scissor winding number
+
+                    /* \todo Sort the scissor edges and skip unnecessary checks when scissors are used */
+                    while (scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x <= fillStartX)
+                    {
+                        scissorWinding += m_scissorAet[scissorIndex++].direction;
+                    }
+
+                    while (!scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x < endSpan)
+                    {
+                        fillStartX = m_scissorAet[scissorIndex].x;
+                        scissorWinding += m_scissorAet[scissorIndex++].direction;
+                        RI_ASSERT(fillStartX >= i);
+                    }
+
+                    RI_ASSERT(scissorWinding >= 0);
+
+                    int endScissorSpan = endSpan;
+
+                    while (scissorWinding && fillStartX < endSpan && (scissorIndex < m_scissorAet.size()))
+                    {
+
+                        // Determine the end of renderable area:
+                        while (scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x <= endSpan)
+                        {
+                            endScissorSpan = m_scissorAet[scissorIndex].x;
+                            scissorWinding += m_scissorAet[scissorIndex++].direction;
+                        }
+
+                        RI_ASSERT(fillStartX >= i);
+                        RI_ASSERT(endScissorSpan <= endSpan);
+
+                        pushSpan(fillStartX, j, (endScissorSpan - fillStartX), coverageSamples);
+                        fillStartX = endScissorSpan;
+                        endScissorSpan = endSpan;
+
+                        // Skip until within drawable area
+                        while (!scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x < endSpan)
+                        {
+                            fillStartX = m_scissorAet[scissorIndex].x;
+                            scissorWinding += m_scissorAet[scissorIndex++].direction;
+                        }
+
+                    }
+                }
+            }
+            i = endSpan;
+        }
+    }
+    commitSpans();
+#if defined(USE_SSE2)
+    _mm_empty();
+#endif
+    clear();
+}
+
+RI_INLINE void Rasterizer::commitSpans()
+{
+    if (!m_nSpans)
+        return;
+
+    m_pixelPipe->fillSpans(m_ppVariants, m_spanCache, m_nSpans);
+    m_nSpans = 0;
+
+}
+
+RI_INLINE void Rasterizer::pushSpan(int x, int y, int len, int coverage)
+{
+    //printf("x: %d, y: %d, len: %d, coverage: %d\n", x, y, len, coverage);
+    // \todo Check what causes this with scissors
+    if (len <= 0) return;
+    //RI_ASSERT(len > 0);
+
+    Span& span = m_spanCache[m_nSpans];
+
+    span.x0 = x;
+    span.y = y;
+    span.len = (RIuint16)len;
+    span.coverage = coverage;
+
+    m_nSpans++;
+
+    if (m_nSpans == N_CACHED_SPANS)
+    {
+        commitSpans();
+    }
+}
+
+//=======================================================================
+
+}	//namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riRasterizer.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,279 @@
+#ifndef __RIRASTERIZER_H
+#define __RIRASTERIZER_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief   Rasterizer class.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#ifndef __RIPIXELPIPE_H
+#include "riPixelPipe.h"
+#endif
+
+// TESTING ONLY!!
+#include "sfDynamicPixelPipe.h"
+
+#if defined(RI_DEBUG)
+#    include <stdio.h>
+#endif
+// \todo SSE2 probably has everything necessary and matches the minimum platform requirements.
+// SSE4 is probably too new. SSE3?
+// \note This will cause the code to not compile on MSVC...
+#define USE_SSE2
+
+#if defined(USE_SSE2)
+// \todo only the last include is needed: QT creator does not find types if others not included.
+#   include <mmintrin.h>
+#   include <xmmintrin.h>
+#   include <emmintrin.h>
+#endif
+
+//=======================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Scalar and vector data types used by the rasterizer.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+typedef RIfloat RScalar;    //change this if you want to have different precision for rasterizer scalars and RIfloat
+
+struct RVector2
+{
+    RI_INLINE RVector2()                            { }
+    RI_INLINE RVector2(const Vector2& v)            { x = v.x; y = v.y; }
+    RI_INLINE RVector2(RIfloat vx, RIfloat vy)      { x = vx; y = vy; }
+    RI_INLINE void set(RIfloat vx, RIfloat vy)      { x = vx; y = vy; }
+    RScalar     x;
+    RScalar     y;
+};
+
+struct IVector2
+{
+    RI_INLINE IVector2() {}
+    RI_INLINE IVector2(const IVector2& v) { x = v.x; y = v.y; }
+    RI_INLINE IVector2(const Vector2& v) { x = (int)v.x; y = (int) v.y; }
+    RI_INLINE IVector2(int vx, int vy) { x = vx; y = vy; }
+    RI_INLINE void set(int vx, int vy) { x = vx; y = vy; }
+    int x;
+    int y;
+};
+
+struct Span
+{
+    RIuint16 x0;
+    RIuint16 y;
+    RIuint16 len;
+    RIuint8  coverage;
+    RIuint8  pad; // align to 8 bytes. \temp Use qualifiers instead?
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Converts a set of edges to coverage values for each pixel and
+*           calls PixelPipe::pixelPipe for painting a pixel.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Rasterizer
+{
+public:
+    Rasterizer();   //throws bad_alloc
+    ~Rasterizer();
+
+    void        setup(int vpx, int vpy, int vpwidth, int vpheight, VGFillRule fillRule, const PixelPipe* pixelPipe);
+    void        setScissor(const Array<Rectangle>& scissors);   //throws bad_alloc
+    void        setScissoring(bool enabled);
+
+    void        clear();
+    void        addEdge(const Vector2& v0, const Vector2& v1);  //throws bad_alloc
+
+    RI_INLINE void setAntiAliasing(bool enable) { m_aa = enable; }
+    void        fill(); //throws bad_alloc
+
+    void        getBBox(int& sx, int& sy, int& ex, int& ey) const       { sx = m_covMinx; sy = m_covMiny; ex = m_covMaxx; ey = m_covMaxy; }
+
+public:
+    enum { SAMPLE_BITS = 3 };
+    enum { Y_BITS = SAMPLE_BITS };
+    enum { MAX_COVERAGE = 1<<SAMPLE_BITS };
+
+    // temp!:
+    RIuint32    *m_covBuffer;
+    size_t      m_covBufferSz;
+
+private:
+    Rasterizer(const Rasterizer&);                      //!< Not allowed.
+    const Rasterizer& operator=(const Rasterizer&);     //!< Not allowed.
+
+public:
+    struct ScissorEdge
+    {
+        ScissorEdge() {}
+        bool operator<(const ScissorEdge& e) const  { return x < e.x; }
+        int         x;
+        int         miny;
+        int         maxy;
+        int         direction;      //1 start, -1 end
+    };
+
+    struct Edge
+    {
+        Edge() {}
+        bool operator<(const Edge& e) const { return v0.y < e.v0.y; }
+#if defined(RI_DEBUG)
+        bool operator<=(const Edge& e) const {return v0.y <= e.v0.y; }
+#endif
+        IVector2    v0;
+        IVector2    v1;
+        int         direction;
+    };
+
+    struct ActiveEdge
+    {
+        typedef RIint16 XCoord;
+        typedef RIint16 YCoord;
+
+        ActiveEdge() {}
+        //bool operator<(const ActiveEdge& e) const   { return minx < e.minx; }
+        bool operator<(const ActiveEdge& e) const
+        {
+            if (minx < e.minx)
+                return true;
+            if (minx == e.minx)
+                return maxx < e.maxx;
+            return false;
+        }
+#if defined(RI_DEBUG)
+        bool operator<=(const ActiveEdge& e) const { return minx <= e.minx; }
+#endif
+        // Fixed-point edge coordinates.
+        RIuint32 next; // \todo Pointer?
+        int     direction;      //-1 down, 1 up
+        int     xRef;
+        int     slope;
+        XCoord  minx;           // for the current scanline
+        XCoord  maxx;           // for the current scanline
+        YCoord  yStart;         // for the edge
+        YCoord  yEnd;           // for the edge
+    };
+
+    enum { SF_SAMPLES = 8 };
+    enum { RASTERIZER_BITS = 14 };
+    enum { RASTERIZER_MASK = ((1<<RASTERIZER_BITS)-1) };
+    enum { Y_MASK = ((1<<Y_BITS)-1) };
+    enum { X_BITS = 7 };
+    enum { XMASK  = ((1<<X_BITS)-1) };
+    enum { LEFT_DISCARD = -0x100000 };
+    enum { LEFT_DISCARD_SHORT = -32768 };
+
+    struct Windings
+    {
+#if !defined(USE_SSE2)
+        Windings() {wq = 0;}
+        // \todo Use SSE counters or packed counters!
+        // \todo 8 samples -> 64 bits == 2 32-bit uints
+        union
+        {
+            RIint8              winding[SF_SAMPLES];
+            RIuint32            wd[SF_SAMPLES/4];
+            unsigned long long  wq;
+        };
+#else
+        Windings() { sseWinding = _mm_setzero_si128(); }
+        __m128i sseWinding;
+#endif
+     };
+
+private:
+    void                pushEdge(const Edge& edge);
+    void                clipAndAddEdge(Edge& edge);
+    void                addBBox(const IVector2& v);
+    RI_INLINE void      pushSpan(int x, int y, int len, int coverage);
+    RI_INLINE void      commitSpans();
+
+    //RI_INLINE void      calculateAEWinding(const ActiveEdge& currAe, Windings& pixel, Windings& scanline, int intY, int pixelX);
+
+    Array<ActiveEdge>   m_edgePool;
+    Array<RIuint32>     m_edges;
+    Array<ScissorEdge>  m_scissorEdges;
+    Array<ActiveEdge>   m_aet;
+    Array<ScissorEdge>  m_scissorAet;
+    bool                m_scissor;
+
+    bool                    m_aa;
+
+    IVector2            m_edgeMin;
+    IVector2            m_edgeMax;
+    int                 m_covMinx;
+    int                 m_covMiny;
+    int                 m_covMaxx;
+    int                 m_covMaxy;
+    int                 m_vpx;
+    int                 m_vpy;
+    int                 m_vpwidth;
+    int                 m_vpheight;
+    int                 m_vpMinx;
+    int                 m_vpMiny;
+    int                 m_vpMaxx;
+    int                 m_vpMaxy;
+    VGFillRule          m_fillRule;
+    RIuint32            m_fillRuleMask;
+
+    const PixelPipe*        m_pixelPipe;
+    PixelPipe::PPVariants   m_ppVariants;
+
+    enum { N_CACHED_SPANS = 64 };
+    Span                m_spanCache[N_CACHED_SPANS];
+    int                 m_nSpans;
+
+};
+
+//=======================================================================
+
+}   //namespace OpenVGRI
+
+//=======================================================================
+
+#endif /* __RIRASTERIZER_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riUtils.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,240 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __RIUTILS_H_
+#   include "riUtils.h"
+#endif
+
+#include <string.h>
+
+namespace OpenVGRI
+{
+
+/**
+ * \brief   Sets mem areas to byte(s) in c.
+ * \param   dst     Destination pointer.
+ * \param   c       Data to set into dst.
+ * \param   nElements   Amount of elements to set.
+ * \param   nBytesPerElement    Amount of bytes for each element.
+ * \note    This is moslty an image-settings support function. It is assumed that several
+ *          bytes / elements can be set at once, especially in 3-byte case.
+ */
+void riMemSet32(void* dst, RIuint32 c, size_t nElements, size_t nBytesPerElement)
+{
+    // \todo This function should be called from a function that handles npot element sizes.
+    // \todo Investigate the status of (open) std::fill implementations. Some of that code 
+    // did not _seem_ to bundle sets or use SSE, etc.
+    // \todo Use SSE instructions on Intel? 
+    
+    RI_ASSERT(dst);
+    RI_ASSERT(nElements);
+
+    switch(nBytesPerElement)
+    {
+    case 4:
+    {
+        RIuint32* ptr = (RIuint32*)dst;
+        do {
+            *ptr++ = c;
+        } while(--nElements);
+        break;
+    }
+    case 3:
+    {
+        // \todo Endianness.
+        RIuint8* ptr = (RIuint8*)dst;
+        RIuint8 b[3];
+        b[0] = c & 0xff;
+        b[1] = (c >> 8)&0xff;
+        b[2] = (c >> 16)&0xff;
+        do {
+            *ptr++ = b[0];
+            *ptr++ = b[1];
+            *ptr++ = b[2];
+        } while(--nElements);
+        break;
+    }
+    case 2:
+    {
+        size_t dws = nElements / 2; 
+        if (dws)
+        {
+            RIuint32* ptr32 = (RIuint32*)dst;
+            dst = (void*)(((RIuint8*)dst + dws * 4));
+            RIuint32 dw = c | (c<<16);
+            do {
+                *ptr32++ = dw;
+            } while(--dws);
+            nElements &= 0x01;
+        }
+        if (nElements)
+        {
+            RIuint16 *ptr16 = (RIuint16*)dst;
+            const RIuint16 w = (RIuint16)c;
+            do {
+                *ptr16++ = w;
+            } while(--nElements);
+        }
+        break;
+    }
+    default:
+    {
+        RI_ASSERT(nBytesPerElement == 1);
+        memset(dst, c, nElements);
+        break;
+    }
+    }
+
+}
+
+/**
+ * \brief   Insert bits into an array of 32-bit integers.
+ * \param   hashSize    Size of array in bytes.
+ * \param   bits        Actual bits to insert.
+ * \param   bitSize     Amount of bits to insert (max 32).
+ * \param   bitPtr      Pointer to first bit to insert [0 .. (hashSize*8)-1]
+ */
+int riInsertBits32(RIuint32* hash, size_t hashSize, RIuint32 bits, RIuint32 bitSize, int bitPtr)
+{
+    RI_ASSERT(bitSize > 0 && bitSize <= 32);
+    RI_ASSERT(bits < (1u<<bitSize));
+    RI_ASSERT((bitPtr + bitSize) < (hashSize * 32));
+
+    int idw = bitPtr >> 5;
+    int ib = bitPtr - (idw << 5);
+
+    if ((ib + bitSize) > 32)
+    {
+        int rb = ((ib + bitSize) - 32) + 1;
+        RI_ASSERT(rb > 0);
+        hash[idw] |= (bits << ib);
+        hash[idw] |= (bits >> rb);
+    } 
+    else
+    {
+        int new_ib = (ib + bitSize) & 0x1f;
+        RI_ASSERT((ib + bitSize == 32) ? new_ib == 0 : true);
+        hash[idw] |= (bits << ib);
+    }
+    return bitPtr + bitSize;
+}
+
+/**
+ * \brief   Convert an image format to (internal) index.
+ */
+int riVGImageFormatToIndex(VGImageFormat format)
+{
+    switch(format)
+    {
+    /* RGB{A,X} channel ordering */
+    case VG_sRGBX_8888:
+        return 0;
+    case VG_sRGBA_8888:
+        return 1;
+    case VG_sRGBA_8888_PRE:
+        return 2;
+    case VG_sRGB_565:
+        return 3;
+    case VG_sRGBA_5551:
+        return 4;
+    case VG_sRGBA_4444:
+        return 5;
+    case VG_sL_8:
+        return 6;
+    case VG_lRGBX_8888:
+        return 7;
+    case VG_lRGBA_8888:
+        return 8;
+    case VG_lRGBA_8888_PRE:
+        return 9;
+    case VG_lL_8:
+        return 10;
+    case VG_A_8:
+        return 11;
+    case VG_BW_1:
+        return 12;
+    case VG_A_1:
+        return 13;
+    case VG_A_4:
+        return 14;
+
+    /* {A,X}RGB channel ordering */
+    case VG_sXRGB_8888:
+        return 15;
+    case VG_sARGB_8888:
+        return 16;
+    case VG_sARGB_8888_PRE:
+        return 17;
+    case VG_sARGB_1555:
+        return 18;
+    case VG_sARGB_4444:
+        return 19;
+    case VG_lXRGB_8888:
+        return 20;
+    case VG_lARGB_8888:
+        return 21;
+    case VG_lARGB_8888_PRE:
+        return 22;
+
+    /* BGR{A,X} channel ordering */
+    case VG_sBGRX_8888:
+        return 23;
+    case VG_sBGRA_8888:
+        return 24;
+    case VG_sBGRA_8888_PRE:
+        return 25;
+    case VG_sBGR_565:
+        return 26;
+    case VG_sBGRA_5551:
+        return 27;
+    case VG_sBGRA_4444:
+        return 28;
+    case VG_lBGRX_8888:
+        return 29;
+    case VG_lBGRA_8888:
+        return 30;
+    case VG_lBGRA_8888_PRE:
+        return 31;
+
+    /* {A,X}BGR channel ordering */
+    case VG_sXBGR_8888:
+        return 32;
+    case VG_sABGR_8888:
+        return 33;
+    case VG_sABGR_8888_PRE:
+        return 34;
+    case VG_sABGR_1555:
+        return 35;
+    case VG_sABGR_4444:
+        return 36;
+    case VG_lXBGR_8888:
+        return 37;
+    case VG_lABGR_8888:
+        return 38;
+    default:
+        RI_ASSERT(format == VG_lABGR_8888_PRE);
+        return 39;
+    }
+}
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riUtils.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,63 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __RIUTILS_H_
+#define __RIUTILS_H_
+
+#ifndef __RIDEFS_H
+#   include "riDefs.h"
+#endif
+
+#include "VG/openvg.h"
+#include <string.h>
+
+// This file contains "utility" functions that did not "fit" into existing RI files.
+// Once more functionality is accumulated, the corresponding functions/classes should be
+// moved to proper files asap. For example, the memcopy functions could go into file
+// "riMemory.xxx".
+
+namespace OpenVGRI
+{
+
+            void    riMemSet32(void* dst, RIuint32 c, size_t nElements, size_t nBytesPerElement);
+RI_INLINE   void    ri_memcpy(void* dst, const void* src, size_t n);
+            int     riInsertBits32(RIuint32* hash, size_t hashSize, RIuint32 bits, RIuint32 bitSize, int bitPtr);
+            int     riVGImageFormatToIndex(VGImageFormat format);
+
+RI_INLINE void ri_memcpy(void* dst, const void* src, size_t n)
+{
+#if !defined(RI_DEBUG)
+    memcpy(dst, src, n);
+#else
+    RIuint8 *p = (RIuint8*)dst;
+    RIuint8 *q = (RIuint8*)src;
+    for (size_t i = 0; i < n; i++, p++, q++)
+    {
+        *p = *q;
+    }
+#endif
+}
+
+} // namespace OpenVG
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/riVGU.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,476 @@
+/*------------------------------------------------------------------------
+ *
+ * VGU library for OpenVG 1.1 Reference Implementation
+ * ---------------------------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of the VGU utility library for OpenVG
+ *//*-------------------------------------------------------------------*/
+
+#include "vgu.h"
+#include "openvg.h"
+#include "riMath.h"
+
+using namespace OpenVGRI;
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+static void append(VGPath path, int numSegments, const VGubyte* segments, int numCoordinates, const VGfloat* coordinates)
+{
+	RI_ASSERT(numCoordinates <= 26);
+
+	VGPathDatatype datatype = (VGPathDatatype)vgGetParameteri(path, VG_PATH_DATATYPE);
+	VGfloat scale = vgGetParameterf(path, VG_PATH_SCALE);
+	VGfloat bias = vgGetParameterf(path, VG_PATH_BIAS);
+
+	switch(datatype)
+	{
+	case VG_PATH_DATATYPE_S_8:
+	{
+		RIint8 data[26];
+		for(int i=0;i<numCoordinates;i++)
+			data[i] = (RIint8)floor((coordinates[i] - bias) / scale + 0.5f);	//add 0.5 for correct rounding
+		vgAppendPathData(path, numSegments, segments, data);
+		break;
+	}
+
+	case VG_PATH_DATATYPE_S_16:
+	{
+		RIint16 data[26];
+		for(int i=0;i<numCoordinates;i++)
+			data[i] = (RIint16)floor((coordinates[i] - bias) / scale + 0.5f);	//add 0.5 for correct rounding
+		vgAppendPathData(path, numSegments, segments, data);
+		break;
+	}
+
+	case VG_PATH_DATATYPE_S_32:
+	{
+		RIint32 data[26];
+		for(int i=0;i<numCoordinates;i++)
+			data[i] = (RIint32)floor((coordinates[i] - bias) / scale + 0.5f);	//add 0.5 for correct rounding
+		vgAppendPathData(path, numSegments, segments, data);
+		break;
+	}
+
+	default:
+	{
+		RI_ASSERT(datatype == VG_PATH_DATATYPE_F);
+		RIfloat32 data[26];
+		for(int i=0;i<numCoordinates;i++)
+			data[i] = (RIfloat32)((coordinates[i] - bias) / scale);
+		vgAppendPathData(path, numSegments, segments, data);
+		break;
+	}
+	}
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguLine(VGPath path, VGfloat x0, VGfloat y0, VGfloat x1, VGfloat y1)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	static const VGubyte segments[2] = {VG_MOVE_TO | VG_ABSOLUTE, VG_LINE_TO | VG_ABSOLUTE};
+	const VGfloat data[4] = {x0, y0, x1, y1};
+	append(path, 2, segments, 4, data);
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguPolygon(VGPath path, const VGfloat * points, VGint count, VGboolean closed)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if(!points || (((RIuintptr)points) & 3) || count <= 0)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	VGubyte segments[1] = {VG_MOVE_TO | VG_ABSOLUTE};
+	VGfloat data[2];
+	for(int i=0;i<count;i++)
+	{
+		data[0] = points[i*2+0];
+		data[1] = points[i*2+1];
+		append(path, 1, segments, 2, data);
+		segments[0] = VG_LINE_TO | VG_ABSOLUTE;
+	}
+	if(closed)
+	{
+		segments[0] = VG_CLOSE_PATH;
+		append(path, 1, segments, 0, data);
+	}
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguRect(VGPath path, VGfloat x, VGfloat y, VGfloat width, VGfloat height)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if(width <= 0 || height <= 0)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	static const VGubyte segments[5] = {VG_MOVE_TO | VG_ABSOLUTE,
+										VG_HLINE_TO | VG_ABSOLUTE,
+										VG_VLINE_TO | VG_ABSOLUTE,
+										VG_HLINE_TO | VG_ABSOLUTE,
+										VG_CLOSE_PATH};
+	const VGfloat data[5] = {x, y, x + width, y + height, x};
+	append(path, 5, segments, 5, data);
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguRoundRect(VGPath path, VGfloat x, VGfloat y, VGfloat width, VGfloat height, VGfloat arcWidth, VGfloat arcHeight)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if(width <= 0 || height <= 0)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	arcWidth = RI_CLAMP(arcWidth, 0.0f, width);
+	arcHeight = RI_CLAMP(arcHeight, 0.0f, height);
+
+	static const VGubyte segments[10] = {VG_MOVE_TO | VG_ABSOLUTE,
+										 VG_HLINE_TO | VG_ABSOLUTE,
+										 VG_SCCWARC_TO | VG_ABSOLUTE,
+										 VG_VLINE_TO | VG_ABSOLUTE,
+										 VG_SCCWARC_TO | VG_ABSOLUTE,
+										 VG_HLINE_TO | VG_ABSOLUTE,
+										 VG_SCCWARC_TO | VG_ABSOLUTE,
+										 VG_VLINE_TO | VG_ABSOLUTE,
+										 VG_SCCWARC_TO | VG_ABSOLUTE,
+										 VG_CLOSE_PATH};
+	const VGfloat data[26] = {x + arcWidth/2, y,
+							  x + width - arcWidth/2,
+							  arcWidth/2, arcHeight/2, 0, x + width, y + arcHeight/2,
+							  y + height - arcHeight/2,
+							  arcWidth/2, arcHeight/2, 0, x + width - arcWidth/2, y + height,
+							  x + arcWidth/2,
+							  arcWidth/2, arcHeight/2, 0, x, y + height - arcHeight/2,
+							  y + arcHeight/2,
+							  arcWidth/2, arcHeight/2, 0, x + arcWidth/2, y};
+	append(path, 10, segments, 26, data);
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguEllipse(VGPath path, VGfloat cx, VGfloat cy, VGfloat width, VGfloat height)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if(width <= 0 || height <= 0)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	static const VGubyte segments[4] = {VG_MOVE_TO | VG_ABSOLUTE,
+										VG_SCCWARC_TO | VG_ABSOLUTE,
+										VG_SCCWARC_TO | VG_ABSOLUTE,
+										VG_CLOSE_PATH};
+	const VGfloat data[12] = {cx + width/2, cy,
+							  width/2, height/2, 0, cx - width/2, cy,
+							  width/2, height/2, 0, cx + width/2, cy};
+	append(path, 4, segments, 12, data);
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguArc(VGPath path, VGfloat x, VGfloat y, VGfloat width, VGfloat height, VGfloat startAngle, VGfloat angleExtent, VGUArcType arcType)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if((arcType != VGU_ARC_OPEN && arcType != VGU_ARC_CHORD && arcType != VGU_ARC_PIE) || width <= 0.0f || height <= 0.0f)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	startAngle = RI_DEG_TO_RAD(startAngle);
+	angleExtent = RI_DEG_TO_RAD(angleExtent);
+
+	VGfloat w = width/2.0f;
+	VGfloat h = height/2.0f;
+
+	VGubyte segments[1];
+	VGfloat data[5];
+
+	segments[0] = VG_MOVE_TO | VG_ABSOLUTE;
+	data[0] = x + w * (VGfloat)cos(startAngle);
+	data[1] = y + h * (VGfloat)sin(startAngle);
+	append(path, 1, segments, 2, data);
+
+	data[0] = w;
+	data[1] = h;
+	data[2] = 0.0f;
+	VGfloat endAngle = startAngle + angleExtent;
+	if(angleExtent >= 0.0f)
+	{
+		segments[0] = VG_SCCWARC_TO | VG_ABSOLUTE;
+		for(VGfloat a = startAngle + RI_PI;a < endAngle; a += RI_PI)
+		{
+            if ((a + RI_PI) == a)
+                return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+			data[3] = x + w * (VGfloat)cos(a);
+			data[4] = y + h * (VGfloat)sin(a);
+			append(path, 1, segments, 5, data);
+		}
+	}
+	else
+	{
+		segments[0] = VG_SCWARC_TO | VG_ABSOLUTE;
+		for(VGfloat a = startAngle - RI_PI;a > endAngle; a -= RI_PI)
+		{
+            if ((a - RI_PI) == a)
+                return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+			data[3] = x + w * (VGfloat)cos(a);
+			data[4] = y + h * (VGfloat)sin(a);
+			append(path, 1, segments, 5, data);
+		}
+	}
+	data[3] = x + w * (VGfloat)cos(endAngle);
+	data[4] = y + h * (VGfloat)sin(endAngle);
+	append(path, 1, segments, 5, data);
+
+	if(arcType == VGU_ARC_CHORD)
+	{
+		segments[0] = VG_CLOSE_PATH;
+		append(path, 1, segments, 0, data);
+	}
+	else if(arcType == VGU_ARC_PIE)
+	{
+		segments[0] = VG_LINE_TO | VG_ABSOLUTE;
+		data[0] = x;
+		data[1] = y;
+		append(path, 1, segments, 2, data);
+		segments[0] = VG_CLOSE_PATH;
+		append(path, 1, segments, 0, data);
+	}
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguComputeWarpQuadToSquare(VGfloat sx0, VGfloat sy0, VGfloat sx1, VGfloat sy1, VGfloat sx2, VGfloat sy2, VGfloat sx3, VGfloat sy3, VGfloat * matrix)
+{
+	if(!matrix || ((RIuintptr)matrix) & 3)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	VGfloat mat[9];
+	VGUErrorCode ret = vguComputeWarpSquareToQuad(sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3, mat);
+	if(ret == VGU_BAD_WARP_ERROR)
+		return VGU_BAD_WARP_ERROR;
+	Matrix3x3 m(mat[0], mat[3], mat[6],
+				mat[1], mat[4], mat[7],
+				mat[2], mat[5], mat[8]);
+	bool nonsingular = m.invert();
+	if(!nonsingular)
+		return VGU_BAD_WARP_ERROR;
+	matrix[0] = m[0][0];
+	matrix[1] = m[1][0];
+	matrix[2] = m[2][0];
+	matrix[3] = m[0][1];
+	matrix[4] = m[1][1];
+	matrix[5] = m[2][1];
+	matrix[6] = m[0][2];
+	matrix[7] = m[1][2];
+	matrix[8] = m[2][2];
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguComputeWarpSquareToQuad(VGfloat dx0, VGfloat dy0, VGfloat dx1, VGfloat dy1, VGfloat dx2, VGfloat dy2, VGfloat dx3, VGfloat dy3, VGfloat * matrix)
+{
+	if(!matrix || ((RIuintptr)matrix) & 3)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	//from Heckbert:Fundamentals of Texture Mapping and Image Warping
+	//Note that his mapping of vertices is different from OpenVG's
+	//(0,0) => (dx0,dy0)
+	//(1,0) => (dx1,dy1)
+	//(0,1) => (dx2,dy2)
+	//(1,1) => (dx3,dy3)
+
+	VGfloat diffx1 = dx1 - dx3;
+	VGfloat diffy1 = dy1 - dy3;
+	VGfloat diffx2 = dx2 - dx3;
+	VGfloat diffy2 = dy2 - dy3;
+
+	VGfloat det = diffx1*diffy2 - diffx2*diffy1;
+	if(det == 0.0f)
+		return VGU_BAD_WARP_ERROR;
+
+	VGfloat sumx = dx0 - dx1 + dx3 - dx2;
+	VGfloat sumy = dy0 - dy1 + dy3 - dy2;
+
+	if(sumx == 0.0f && sumy == 0.0f)
+	{	//affine mapping
+		matrix[0] = dx1 - dx0;
+		matrix[1] = dy1 - dy0;
+		matrix[2] = 0.0f;
+		matrix[3] = dx3 - dx1;
+		matrix[4] = dy3 - dy1;
+		matrix[5] = 0.0f;
+		matrix[6] = dx0;
+		matrix[7] = dy0;
+		matrix[8] = 1.0f;
+		return VGU_NO_ERROR;
+	}
+
+	VGfloat oodet = 1.0f / det;
+	VGfloat g = (sumx*diffy2 - diffx2*sumy) * oodet;
+	VGfloat h = (diffx1*sumy - sumx*diffy1) * oodet;
+
+	matrix[0] = dx1-dx0+g*dx1;
+	matrix[1] = dy1-dy0+g*dy1;
+	matrix[2] = g;
+	matrix[3] = dx2-dx0+h*dx2;
+	matrix[4] = dy2-dy0+h*dy2;
+	matrix[5] = h;
+	matrix[6] = dx0;
+	matrix[7] = dy0;
+	matrix[8] = 1.0f;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguComputeWarpQuadToQuad(VGfloat dx0, VGfloat dy0, VGfloat dx1, VGfloat dy1, VGfloat dx2, VGfloat dy2, VGfloat dx3, VGfloat dy3, VGfloat sx0, VGfloat sy0, VGfloat sx1, VGfloat sy1, VGfloat sx2, VGfloat sy2, VGfloat sx3, VGfloat sy3, VGfloat * matrix)
+{
+	if(!matrix || ((RIuintptr)matrix) & 3)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	VGfloat qtos[9];
+	VGUErrorCode ret1 = vguComputeWarpQuadToSquare(sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3, qtos);
+	if(ret1 == VGU_BAD_WARP_ERROR)
+		return VGU_BAD_WARP_ERROR;
+
+	VGfloat stoq[9];
+	VGUErrorCode ret2 = vguComputeWarpSquareToQuad(dx0, dy0, dx1, dy1, dx2, dy2, dx3, dy3, stoq);
+	if(ret2 == VGU_BAD_WARP_ERROR)
+		return VGU_BAD_WARP_ERROR;
+
+	Matrix3x3 m1(qtos[0], qtos[3], qtos[6],
+				 qtos[1], qtos[4], qtos[7],
+				 qtos[2], qtos[5], qtos[8]);
+	Matrix3x3 m2(stoq[0], stoq[3], stoq[6],
+				 stoq[1], stoq[4], stoq[7],
+				 stoq[2], stoq[5], stoq[8]);
+	Matrix3x3 r = m2 * m1;
+
+	matrix[0] = r[0][0];
+	matrix[1] = r[1][0];
+	matrix[2] = r[2][0];
+	matrix[3] = r[0][1];
+	matrix[4] = r[1][1];
+	matrix[5] = r[2][1];
+	matrix[6] = r[0][2];
+	matrix[7] = r[1][2];
+	matrix[8] = r[2][2];
+	return VGU_NO_ERROR;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfAlphaRcp.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,66 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef _SFALPHARCP_H_
+#define _SFALPHARCP_H_
+
+#include "riDefs.h"
+
+namespace OpenVGRI {
+enum { ALPHA_RCP_BITS = 8};
+static const RIuint16 sc_alphaRcp[256] = {
+    0xff00,  0xff00,  0x7f80,  0x5500,  0x3fc0,  0x3300,  0x2a80,  0x246e,  
+    0x1fe0,  0x1c55,  0x1980,  0x172f,  0x1540,  0x139e,  0x1237,  0x1100,  
+    0xff0,  0xf00,  0xe2b,  0xd6c,  0xcc0,  0xc25,  0xb97,  0xb16,  
+    0xaa0,  0xa33,  0x9cf,  0x972,  0x91b,  0x8cb,  0x880,  0x83a,  
+    0x7f8,  0x7ba,  0x780,  0x749,  0x715,  0x6e4,  0x6b6,  0x68a,  
+    0x660,  0x638,  0x612,  0x5ee,  0x5cc,  0x5ab,  0x58b,  0x56d,  
+    0x550,  0x534,  0x51a,  0x500,  0x4e7,  0x4d0,  0x4b9,  0x4a3,  
+    0x48e,  0x479,  0x466,  0x452,  0x440,  0x42e,  0x41d,  0x40c,  
+    0x3fc,  0x3ec,  0x3dd,  0x3ce,  0x3c0,  0x3b2,  0x3a5,  0x397,  
+    0x38b,  0x37e,  0x372,  0x366,  0x35b,  0x350,  0x345,  0x33a,  
+    0x330,  0x326,  0x31c,  0x313,  0x309,  0x300,  0x2f7,  0x2ee,  
+    0x2e6,  0x2dd,  0x2d5,  0x2cd,  0x2c6,  0x2be,  0x2b6,  0x2af,  
+    0x2a8,  0x2a1,  0x29a,  0x293,  0x28d,  0x286,  0x280,  0x27a,  
+    0x274,  0x26e,  0x268,  0x262,  0x25c,  0x257,  0x251,  0x24c,  
+    0x247,  0x242,  0x23d,  0x238,  0x233,  0x22e,  0x229,  0x225,  
+    0x220,  0x21c,  0x217,  0x213,  0x20e,  0x20a,  0x206,  0x202,  
+    0x1fe,  0x1fa,  0x1f6,  0x1f2,  0x1ef,  0x1eb,  0x1e7,  0x1e4,  
+    0x1e0,  0x1dc,  0x1d9,  0x1d6,  0x1d2,  0x1cf,  0x1cc,  0x1c9,  
+    0x1c5,  0x1c2,  0x1bf,  0x1bc,  0x1b9,  0x1b6,  0x1b3,  0x1b0,  
+    0x1ad,  0x1ab,  0x1a8,  0x1a5,  0x1a2,  0x1a0,  0x19d,  0x19b,  
+    0x198,  0x195,  0x193,  0x190,  0x18e,  0x18c,  0x189,  0x187,  
+    0x185,  0x182,  0x180,  0x17e,  0x17c,  0x179,  0x177,  0x175,  
+    0x173,  0x171,  0x16f,  0x16d,  0x16b,  0x169,  0x167,  0x165,  
+    0x163,  0x161,  0x15f,  0x15d,  0x15b,  0x159,  0x158,  0x156,  
+    0x154,  0x152,  0x150,  0x14f,  0x14d,  0x14b,  0x14a,  0x148,  
+    0x146,  0x145,  0x143,  0x142,  0x140,  0x13e,  0x13d,  0x13b,  
+    0x13a,  0x138,  0x137,  0x135,  0x134,  0x132,  0x131,  0x130,  
+    0x12e,  0x12d,  0x12b,  0x12a,  0x129,  0x127,  0x126,  0x125,  
+    0x123,  0x122,  0x121,  0x120,  0x11e,  0x11d,  0x11c,  0x11b,  
+    0x119,  0x118,  0x117,  0x116,  0x115,  0x113,  0x112,  0x111,  
+    0x110,  0x10f,  0x10e,  0x10d,  0x10c,  0x10a,  0x109,  0x108,  
+    0x107,  0x106,  0x105,  0x104,  0x103,  0x102,  0x101,  0x100,  
+};
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfBlitter.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,132 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#include "sfBlitter.h"
+
+#include "sfCompiler.h"
+
+namespace OpenVGRI {
+
+DynamicBlitter::DynamicBlitter() :
+    m_maskOperation(VG_SET_MASK),
+    m_isMaskOperation(false),
+    m_fillColor(),
+    m_isFill(false),
+
+    m_signatureState(),
+    m_uniforms()
+{
+}
+
+DynamicBlitter::~DynamicBlitter()
+{
+}
+
+/*static*/ void DynamicBlitter::calculateHash(BlitterHash& hash, const BlitSignatureState& state)
+{
+    const RIuint32 descBits = 10;
+    const RIuint32 maskOperationBits = 3;
+    const RIuint32 boolBits = 1;
+
+    RIuint32 srcFormat = (RIuint32)(state.srcDesc.toIndex());
+    RIuint32 dstFormat = (RIuint32)(state.dstDesc.toIndex());
+    RIuint32 maskOperation = ((RIuint32)(state.maskOperation - VG_CLEAR_MASK));
+    RIuint32 incompatibleStride = ((RIuint32)state.incompatibleStrides);
+    RIuint32 isMaskOperation = ((RIuint32)state.isMaskOperation);
+    RIuint32 unsafeInput = (RIuint32)state.unsafeInput;
+    
+    int b = 0;
+
+    b = riInsertBits32(hash.value, sizeof(hash.value), srcFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), dstFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), maskOperation, maskOperationBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), incompatibleStride, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), isMaskOperation, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), unsafeInput, boolBits, b);
+}
+
+/**
+ * \brief   Blit a region. The input coordinates and dimensions must be validated outside
+ *          the blitter currently.
+ * \note    The user must also apply the storage offset to the image(s).
+ */
+void DynamicBlitter::prepareBlit(Image* dst, const Image* src, int sx, int sy, int dx, int dy, int w, int h)
+{
+    //const Image *srcImage = src->getImage();
+    //Image* dstImage = dst->m_image;
+    
+    // \todo Move these to derivation of the state?
+    m_signatureState.srcDesc = src->getDescriptor();
+    m_signatureState.dstDesc = dst->getDescriptor();
+    m_signatureState.isMaskOperation = m_isMaskOperation;
+    m_signatureState.maskOperation = m_isMaskOperation ? m_maskOperation : VG_CLEAR_MASK;
+    m_signatureState.incompatibleStrides = false;
+    m_signatureState.unsafeInput = false;
+
+    m_uniforms.src = src->getData();
+    m_uniforms.dst = dst->getData();
+    m_uniforms.srcX = sx;
+    m_uniforms.srcY = sy;
+    m_uniforms.dstX = dx;
+    m_uniforms.dstY = dy;
+    m_uniforms.width = w;
+    m_uniforms.height = h;
+    m_uniforms.srcStride = src->getStride();
+    m_uniforms.dstStride = dst->getStride();
+
+    if (m_signatureState.srcDesc.isZeroConversion(m_signatureState.dstDesc))
+    {
+        const int fullCopyStride = Image::descriptorToStride(m_signatureState.srcDesc, m_uniforms.width);
+
+        if ((m_uniforms.dstStride != m_uniforms.srcStride) || (fullCopyStride != m_uniforms.srcStride)) 
+            m_signatureState.incompatibleStrides = true;
+    }
+
+    if (src->isUnsafe())
+        m_signatureState.unsafeInput = true;
+
+}
+
+void DynamicBlitter::blit()
+{
+#if 1
+    bool compiledBlitter = false;
+    {
+        PPCompiler& compiler = PPCompiler::getCompiler();
+        PPCompiler::BlitterHandle blitterHandle = compiler.compileBlitter(getSignatureState());
+        if (blitterHandle)
+        {
+            compiledBlitter = true;
+            BlitterFunction func = compiler.getBlitterPtr(blitterHandle);
+            func(getUniforms());
+            compiler.releaseBlitter(blitterHandle);
+        }
+    }
+
+    if (!compiledBlitter)
+#endif
+    {
+        executeBlitter(getSignatureState(), getUniforms());
+    }
+}
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfBlitter.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,104 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFBLITTER_H
+#define __SFBLITTER_H
+
+#ifndef __RIDEFS_H
+#   include "riDefs.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#   include "riImage.h"
+#endif
+
+#include "VG/openvg.h"
+
+namespace OpenVGRI {
+
+class PPCompiler;
+
+struct BlitterHash {
+    BlitterHash() {value[0] = 0; }
+    bool operator==(const BlitterHash& rhs) const { return value[0] == rhs.value[0]; }
+    RIuint32 value[1];
+}; 
+
+// \todo Rename to just "Blitter" and move out of the same compilation unit.
+class DynamicBlitter {
+public:
+    struct BlitSignatureState {
+        VGMaskOperation maskOperation;
+
+        bool incompatibleStrides;
+        bool isMaskOperation;
+        bool unsafeInput;
+        
+        // Derived:
+        Color::Descriptor srcDesc;
+        Color::Descriptor dstDesc;
+    };
+
+    struct BlitUniforms {
+        void*       dst;
+        const void* src;
+        RIuint32    srcX;
+        RIuint32    srcY;
+        RIuint32    dstX;
+        RIuint32    dstY;
+        RIuint32    width;
+        RIuint32    height;
+        RIint32     srcStride;
+        RIint32     dstStride;
+    };
+
+public:
+    DynamicBlitter();
+    ~DynamicBlitter();
+
+    static void calculateHash(BlitterHash& hash, const BlitSignatureState& state);
+
+    void setMaskOperation(VGMaskOperation maskOperation)    { m_maskOperation = maskOperation; }
+    void enableMaskOperation(bool isMaskOperation)          { m_isMaskOperation = isMaskOperation; }
+    void setFillColor(const Color& fillColor)               { m_fillColor = fillColor; }
+    void enableFill(bool isFill)                            { m_isFill = isFill; }
+
+    void prepareBlit(Image* dst, const Image* src, int sx, int sy, int dx, int dy, int w, int h);
+    void blit();
+
+    const BlitSignatureState&   getSignatureState() { return m_signatureState; }
+    const BlitUniforms&         getUniforms() { return m_uniforms; }
+
+private:
+
+    VGMaskOperation     m_maskOperation;
+    bool                m_isMaskOperation;
+    Color               m_fillColor;
+    bool                m_isFill;
+    
+    BlitSignatureState  m_signatureState;
+    BlitUniforms        m_uniforms;
+};
+}
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfCompiler.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,512 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFCOMPILER_H
+#   include "sfCompiler.h"
+#endif
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+
+#include <iostream>
+#include <sstream>
+#include <stdio.h>
+
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/Bitcode/ReaderWriter.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Type.h"
+#include "llvm/Value.h"
+#include "llvm/Constant.h"
+#include "llvm/Constants.h"
+#include "llvm/Argument.h"
+#include "llvm/Transforms/Utils/Cloning.h"
+
+#include "llvm/Pass.h"
+#include "llvm/PassManager.h"
+#include "llvm/Support/StandardPasses.h"
+#include "llvm/Transforms/Utils/BasicInliner.h"
+
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/Target/TargetSelect.h"
+#include "llvm/Support/ManagedStatic.h"
+
+// This file is found as an output of compilation (in the binary directory).
+// Rationale for this is that the output is somewhat platform dependent.
+#include "binaryPixelPipe.h"
+#include "binaryBlitter.h"
+
+namespace OpenVGRI {
+
+static bool single_compiler = true;
+
+PPCompiler* PPCompiler::s_compiler = NULL;
+
+PPCompiler::PPCompiler() :
+    m_executionEngine(NULL),
+    m_ppCache(NUM_CACHED_PIXELPIPES),
+    m_blitterCache(NUM_CACHED_BLITTERS),
+    m_llvmContext()
+{
+    // \todo Make this class into a singleton?
+    RI_ASSERT(single_compiler);
+
+    if (single_compiler)
+        single_compiler = false;
+
+    ::llvm::InitializeNativeTarget();
+    init();
+}
+
+PPCompiler::~PPCompiler()
+{
+    if (m_executionEngine)
+        delete m_executionEngine;
+}
+
+PPCompiler::PPCompilerContext::PPCompilerContext() :
+    module(NULL),
+    llvmFunction(NULL)
+{
+}
+
+PPCompiler::PPCompilerContext::~PPCompilerContext()
+{
+    // All the other objects should be owned by the executionengine, and
+    // that is owned by the PPCompiler, so do nothing here.
+
+}
+
+bool PPCompiler::initPPContext(
+    PPCompilerContext&      context, 
+    const unsigned char*    data,
+    size_t                  dataSize,
+    const char*             functionName)
+{
+    try {
+        std::string err;
+
+        const char *byteCodeStart = (const char*)data;
+        const char *byteCodeEnd = (const char*)(data + dataSize);
+
+        ::llvm::MemoryBuffer* memBuffer = ::llvm::MemoryBuffer::getMemBufferCopy(byteCodeStart, byteCodeEnd);
+        
+        llvmCheckPtrError((void*)memBuffer, err);
+
+        // Make sure the module is fully read:
+        //::llvm::Module* ppModule = moduleProvider->materializeModule(&err);
+        ::llvm::Module* ppModule = ::llvm::getLazyBitcodeModule(memBuffer, getLLVMContext(), &err);
+        ppModule->MaterializeAll();
+        
+        llvmCheckPtrError(ppModule, err);
+        context.module = ppModule;
+        //ppModule->dump();
+
+        if (!m_executionEngine)
+        {
+            m_executionEngine = ::llvm::ExecutionEngine::createJIT(ppModule, &err, NULL, ::llvm::CodeGenOpt::Aggressive);
+            llvmCheckPtrError(m_executionEngine, err);
+        }
+        else
+            m_executionEngine->addModule(ppModule);
+
+        //m_executionEngine->runStaticConstructorsDestructors(false);
+
+        ::llvm::Function* originalFunc = findFunctionWithString(ppModule, functionName);
+       
+        llvmCheckPtrError((const void*)originalFunc, err);
+        context.llvmFunction = originalFunc;
+        //originalFunc->dump();
+    } catch (int err)
+    {
+        (void)err;
+        std::cerr << "*** Failed to initialize a pixelpipeline module." << std::endl;
+        return false;
+    }
+
+    return true;
+}
+
+
+/**
+ * \brief   Loads the modules this compiler supports.
+ */
+bool PPCompiler::init()
+{
+    if (!initPPContext(m_ppContext, integerPixelPipe_binary, sizeof(integerPixelPipe_binary), "executePixelPipeline"))
+        return false;
+    
+    if (!initPPContext(m_blitterContext, integerBlitter_binary, sizeof(integerBlitter_binary), "executeBlitter"))
+        return false;
+
+    m_ppCache.setLLVMInterface(m_executionEngine, m_ppContext.module);
+    m_blitterCache.setLLVMInterface(m_executionEngine, m_blitterContext.module);
+
+    return true;
+}
+
+// Helps cast void* to function pointers (may be platform dependent, usually works):
+union FuncCaster {
+    void*               ptr;
+    PixelPipeFunction   pipeFunc;
+    BlitterFunction     blitFunc; 
+};
+
+PPCompiler::PartialEvalFunc PPCompiler::compilePixelPipeline(::llvm::LLVMContext& llvmContext, PPCompilerContext& compilerContext, ConstantGenFunc constGenFunc, const void* state, const std::string& newFunctionName)
+{
+    // Get the constant state argument (must be the first in the list):
+    ::llvm::Function::arg_iterator argit = compilerContext.llvmFunction->arg_begin();
+    ::llvm::Argument& arg = *argit;
+    //arg.getType()->dump();
+
+    ::llvm::Constant* constantState = constGenFunc(state, llvmContext, arg.getType()->getContainedType(0));
+
+    RI_ASSERT(constantState);
+
+    //constantState->dump();
+
+    // \todo Even though this variable could be automatically cleaned up by the optimizations,
+    // it should be stored in the cache and destroyed along with the function when
+    // the cache-entry is dropped out.
+    ::llvm::GlobalVariable* constantStateVariable = new ::llvm::GlobalVariable(
+        *compilerContext.module, constantState->getType(), true, ::llvm::GlobalValue::PrivateLinkage, constantState, newFunctionName + "_constState");
+
+    // When to delete the global variable?
+    // -> When the pixel-pipe is removed from the cache. Also, when the compiler is deleted.
+
+    ::llvm::DenseMap<const ::llvm::Value*, ::llvm::Value*> valueMap;
+    std::pair<const ::llvm::Value*, ::llvm::Value*> valueReplacement((::llvm::Value*)&arg, constantStateVariable);
+    valueMap.insert(valueReplacement);
+
+    ::llvm::Function* specializedFunc = ::llvm::CloneFunction(compilerContext.llvmFunction, valueMap, NULL);
+    specializedFunc->setName(newFunctionName);
+    //specializedFunc->dump();
+
+    compilerContext.module->getFunctionList().push_back(specializedFunc);
+
+    // \note Currently this creates the pass manager every time a pipeline is compiled...
+    ::llvm::PassManager pm;
+    // \todo Seems like the greater the threshold, the more the pass will inline:
+    // In practice, everything should be inlineed into the resulting pipe.
+    ::llvm::Pass* inliningPass = ::llvm::createFunctionInliningPass(100000);
+    ::llvm::createStandardModulePasses(&pm, 3, false, true, true, true, false, inliningPass);
+    pm.run(*compilerContext.module);
+
+    //ppModule->dump();
+
+    //compilerContext.llvmFunction->dump();
+    PartialEvalFunc ret = {specializedFunc, constantStateVariable};
+    return ret;
+}
+
+/**
+ * \brief   Compile a pipeline if necessary. If the pipeline is cached, return a
+ *          handle to it. 
+ * \return  NULL handle if operation was not successful, otherwise a handle to the pipeline.
+ * \todo    For deferred JITting, it might make sense to return a special value
+ *          to indicate that the pipeline is under compilation.
+ * \note    LLVM compilation should be thread-safe internally.
+ */
+PPCompiler::PixelPipeHandle PPCompiler::compilePixelPipeline(const PixelPipe::SignatureState& state)
+{
+    PixelPipeHash hash;
+    calculatePPHash(hash, state);
+
+    PixelPipeEntryHandle entry = m_ppCache.findCachedItemByHash(hash);
+
+    if (!entry)
+    {
+        PartialEvalFunc pf;
+        std::string funcName = "compiledPPFunc_" + PPCompiler::stringOfArray(hash.value, sizeof(hash.value)/sizeof(hash.value[0]));
+        pf = compilePixelPipeline(getLLVMContext(), m_ppContext, createPPConstant, (const void*)&state, funcName.c_str());
+        entry = m_ppCache.cacheFunction(hash, pf.llvmFunc, pf.llvmConst);
+#if defined(RI_DEBUG) && 0
+        pf.llvmFunc->dump();
+#endif
+    }
+
+    if (!entry)
+    {
+        RI_ASSERT(false);
+        // Release the function!
+    }
+
+    return (PixelPipeHandle)entry;
+}
+
+PPCompiler::BlitterHandle PPCompiler::compileBlitter(const DynamicBlitter::BlitSignatureState& state)
+{
+    // \todo This function is almost the same as compilePixelPipeline.
+    BlitterHash hash;
+    DynamicBlitter::calculateHash(hash, state);
+
+    BlitterEntryHandle entry = m_blitterCache.findCachedItemByHash(hash);
+
+    if (!entry)
+    {
+        PartialEvalFunc pf;
+        std::string funcName = "compiledBlitterFunc_" + PPCompiler::stringOfArray(hash.value, sizeof(hash.value)/sizeof(hash.value[0]));
+        pf = compilePixelPipeline(getLLVMContext(), m_blitterContext, createBlitterConstant, (const void*)&state, funcName.c_str());
+        entry = m_blitterCache.cacheFunction(hash, pf.llvmFunc, pf.llvmConst);
+    }
+
+    if (!entry)
+    {
+        RI_ASSERT(false);
+        // Release the function!
+    }
+
+    RI_ASSERT(entry);
+
+    return (BlitterHandle)entry;
+}
+
+PixelPipeFunction PPCompiler::getPixelPipePtr(PixelPipeHandle handle)
+{
+    PixelPipeEntryHandle entryHandle = (PixelPipeEntryHandle)handle;
+    ::llvm::Function* function = m_ppCache.getFunction(entryHandle); 
+
+    FuncCaster c;
+    c.ptr = m_executionEngine->getPointerToFunction(function);
+    return c.pipeFunc;
+}
+
+BlitterFunction PPCompiler::getBlitterPtr(BlitterHandle handle)
+{
+    BlitterEntryHandle entryHandle = (BlitterEntryHandle)handle;
+    ::llvm::Function* function = m_blitterCache.getFunction(entryHandle);
+
+    FuncCaster c;
+    c.ptr = m_executionEngine->getPointerToFunction(function);
+    return c.blitFunc;
+}
+
+// Release a reference to a pixel-pipeline handle.
+void PPCompiler::releasePixelPipeline(PixelPipeHandle handle)
+{
+    PixelPipeEntryHandle entryHandle = (PixelPipeEntryHandle)handle;
+    m_ppCache.releaseEntry(entryHandle);
+}
+
+// Release a reference to a blitter handle.
+void PPCompiler::releaseBlitter(BlitterHandle handle)
+{
+    BlitterEntryHandle entryHandle = (BlitterEntryHandle)handle;
+    m_blitterCache.releaseEntry(entryHandle);
+}
+
+#if 0
+// \todo Complete this and make it fully recursive: this way all the C-structs
+// can be converted to corresponding LLVM classes at runtime.
+::llvm::Constant* PPCompiler::createConstantStruct(const void* structure, size_t structSize, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType) const
+{
+    // Only copies integer-values (int, bools)
+    RIuint8* bytePtr = (RIuint8*)structure; 
+    ::llvm::Type::subtype_iterator subtypeBegin, subtypeEnd;
+
+    subtypeBegin = structType->subtype_begin();
+    subtypeEnd = structType->subtype_end();
+
+    for(::llvm::Type::subtype_iterator it = subtypeBegin; it != subtypeEnd; ++it)
+    {
+        ::llvm::Type* elementType = *it;
+        RI_ASSERT(elementType->isSized());
+        unsigned int elementBitSize = elementType->getPrimitiveSizeInBits();
+        RI_ASSERT((elementBitSize % 8) == 0);
+        unsigned int elementSize = elementBitSize / 8;
+        RI_ASSERT(elementSize > 0 && elementSize <= 4); 
+       
+        bytePtr += elementSize;
+    }
+}
+#endif
+/**
+ * \brief   Creates a LLVM constant from a color descriptor.
+ * \todo    Create global constants from these for every possible color format!
+ */
+RI_INLINE static ::llvm::Constant* createDescConstant(const Color::Descriptor& desc, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType)
+{
+    ::llvm::Constant* constants[] = {
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.redBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.redShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.greenBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.greenShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.blueBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.blueShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.alphaBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.alphaShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.luminanceBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.luminanceShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.shape, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.vgFormat, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.internalFormat, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.bitsPerPixel, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.bytesPerPixel, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.maskBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.maskShift, true),
+    };
+
+    std::vector< ::llvm::Constant*> structConsts;
+
+    for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++)
+    {
+        structConsts.push_back(constants[i]);
+    }
+
+    ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts);
+
+    return constStruct;
+}
+
+::llvm::Constant* PPCompiler::createPPConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType)
+{
+    // Get the actual object. This is a messy way to abstract setting the structure, but
+    // there is little sense in making more classes/adapters/whatever at this point.
+    const PixelPipe::SignatureState& state = *(const PixelPipe::SignatureState*)signatureState;
+    // \todo There seems to be no way to track the structure member names once
+    // LLVM has generated the bitcode (only offsets and references to those
+    // offsets remain). Means to track proper setting of struct members in
+    // DEBUG build must be implemented in some other way.
+    // 
+    // For now, the state and this function must be kept carefully in sync!
+    
+    const int cDescriptorElementIndex = 8;
+    const ::llvm::Type* descType = structType->getContainedType(cDescriptorElementIndex);
+
+    ::llvm::Constant* constants[] = {
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.blendMode, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageMode, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintType, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.maskOperation, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintTilingMode, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintSampler, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageSampler, false),
+
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageGradientType, false),
+
+        createDescConstant(state.dstDesc, llvmContext, descType),
+        createDescConstant(state.maskDesc, llvmContext, descType),
+        createDescConstant(state.imageDesc, llvmContext, descType),
+        createDescConstant(state.patternDesc, llvmContext, descType),
+
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasMasking, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasImage, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasColorTransform, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.isRenderToMask, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.fillColorTransparent, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.unsafeImageInput, false),
+    };
+
+    std::vector< ::llvm::Constant*> structConsts;
+
+    for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++)
+    {
+        structConsts.push_back(constants[i]);
+    }
+
+    ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts);
+
+    return constStruct;
+}
+
+::llvm::Constant* PPCompiler::createBlitterConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType)
+{
+    const DynamicBlitter::BlitSignatureState& state = *(const DynamicBlitter::BlitSignatureState*)signatureState;
+    
+    const int cDescriptorElementIndex = 4;
+    const ::llvm::Type* descType = structType->getContainedType(cDescriptorElementIndex);
+
+    ::llvm::Constant* constants[] = {
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.maskOperation, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.incompatibleStrides, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.isMaskOperation, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.unsafeInput, false),
+
+        createDescConstant(state.srcDesc, llvmContext, descType),
+        createDescConstant(state.dstDesc, llvmContext, descType),
+    };
+
+    std::vector< ::llvm::Constant*> structConsts;
+
+    for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++)
+    {
+        structConsts.push_back(constants[i]);
+    }
+
+    ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts);
+
+    return constStruct;
+}
+
+/**
+ * \brief   Find a function whose name containst ``namepart''. Useful for finding c++
+ *          decorated names from modules (if they are unique).
+ * \note    Maybe should use C-functions only in the final product.
+ */
+::llvm::Function* PPCompiler::findFunctionWithString(::llvm::Module* module, const char* namepart)
+{
+    // Find a function whose name contains 'namepart'
+    llvm::Module::iterator it, end;
+    it = module->begin();
+    end = module->end();
+    for (; it != end; ++it)
+    {
+        if (!it->isDeclaration())
+            if (it->getNameStr().find(namepart) != std::string::npos)
+                return it;
+    }
+    return NULL;
+}
+
+void PPCompiler::llvmCheckPtrError(const void* ptr, std::string& err)
+{
+#if defined(RI_DEBUG)
+    (void)err;
+    //std::cout << "LLVM returned: " << ptr << ". Error string: \"" << err << "\"" << std::endl;
+#else
+    (void)err;
+#endif
+    if (!ptr)
+        throw(-1);
+}
+
+/*static*/ std::string PPCompiler::stringOfArray(const RIuint32* arr, int nElems)
+{
+    char tempBuffer[9];
+    std::stringstream out;
+    // Ambiquities resolved by using a constant width:
+    RI_ASSERT(nElems > 0);
+    int i = nElems-1;
+    do {
+        snprintf(tempBuffer, sizeof(tempBuffer), "%08x", arr[i]);
+        out << tempBuffer;
+        i--;
+    } while(i >= 0);
+
+    return out.str();
+}
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfCompiler.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,156 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFCOMPILER_H
+#define __SFCOMPILER_H
+
+#include <string>
+
+#ifndef __SFDYNAMICPIXELPIPE_H
+#   include "sfDynamicPixelPipe.h"
+#endif
+
+#ifndef __SFDYNAMICBLITTER_H
+#   include "sfDynamicBlitter.h"
+#endif
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+
+#ifndef __SFFUNCTIONCACHE_H
+#   include "sfFunctionCache.h"
+#endif
+
+#include "llvm/LLVMContext.h"
+
+// \note PPCompiler class also caches a certain amount of compiled functions.
+// It may make sense to move the cache into a separate container.
+
+// LLVM forward declarations
+namespace llvm { 
+    class Type;
+    class Constant;
+    class Function;
+    class Module;
+    class ExecutionEngine;
+}
+
+namespace OpenVGRI {
+
+// Pixel-pipeline function with constant state removed:
+typedef void (*PixelPipeFunction)(const PixelPipe::PPUniforms&, PixelPipe::PPVariants&, const Span*, int);
+// Image-blitting function with constant state removed:
+typedef void (*BlitterFunction)(const DynamicBlitter::BlitUniforms&);
+
+class PPCompiler
+{
+public:
+    typedef int PixelPipeHandle;
+    typedef int BlitterHandle;
+private:
+    // Function that generates LLVM-constant from a pixel-pipeline:
+    typedef ::llvm::Constant* (*ConstantGenFunc)(const void* structure, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType);
+
+    struct PPCompilerContext {
+        PPCompilerContext();
+        ~PPCompilerContext();
+        // Stores persistent objects related to each component (pixelpipe or blitter).
+        // Note that the execution engine must be a per-process singleton for LLVM before
+        // version 2.7!
+        ::llvm::Module* module;
+        ::llvm::Function* llvmFunction; 
+    };
+
+    struct PartialEvalFunc
+    {
+        ::llvm::Function*   llvmFunc;
+        ::llvm::GlobalVariable*   llvmConst;
+    };
+
+public:
+    PPCompiler();
+    ~PPCompiler();
+
+    static PartialEvalFunc compilePixelPipeline(::llvm::LLVMContext& llvmContext, PPCompilerContext& compilerContext, ConstantGenFunc constGenFunc, const void* state, const std::string& newFuntionName);
+
+    // These functions get an reserve a handle to a pixelpipe/blitter. MUST use release
+    // after done with the function.
+    PixelPipeHandle     compilePixelPipeline(const PixelPipe::SignatureState& state);
+    BlitterHandle       compileBlitter(const DynamicBlitter::BlitSignatureState& state);
+
+    PixelPipeFunction   getPixelPipePtr(PixelPipeHandle handle);
+    BlitterFunction     getBlitterPtr(BlitterHandle handle);
+
+    void releasePixelPipeline(PixelPipeHandle handle);
+    void releaseBlitter(BlitterHandle handle);
+
+    bool init();
+
+    // It seems that under VS, the static init order is not correct so the compiler has to be created
+    // during run-time.
+    static PPCompiler&  getCompiler() { if(!s_compiler) { s_compiler = new PPCompiler(); } return *s_compiler; }
+
+private:
+    bool initPPContext(PPCompilerContext& context, const unsigned char* data, size_t dataSize, const char* functionName);
+    //void* compileRenderingFunction(const void* signatureState, RenderingFunctionType type);
+
+    static ::llvm::Constant* createConstantStruct(const void* structure, size_t structureSize, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType);
+    static ::llvm::Constant* createPPConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType);
+    static ::llvm::Constant* createBlitterConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType);
+    static ::llvm::Function* findFunctionWithString(::llvm::Module* module, const char* namepart);
+    static void llvmCheckPtrError(const void* ptr, std::string& err);
+
+    static std::string stringOfArray(const RIuint32* arr, int nElems);
+
+private:
+    //::llvm::LLVMContext& getLLVMContext() { return ::llvm::getGlobalContext(); }
+    ::llvm::LLVMContext& getLLVMContext() { return m_llvmContext; }
+
+    // The order is important atm. because llvm context must be destroyed last:
+    //::llvm::LLVMContext& m_llvmContext;
+    PPCompilerContext m_blitterContext;
+    PPCompilerContext m_ppContext;
+    ::llvm::ExecutionEngine* m_executionEngine;
+
+    // \note Loading a system with LLVM already consumes a lot of memory, so
+    // the amount of cached functions can be grown substantially depending on
+    // requirements.
+    enum { NUM_CACHED_PIXELPIPES = 64 };
+    enum { NUM_CACHED_BLITTERS = NUM_CACHED_PIXELPIPES };
+    
+    FunctionCache<PixelPipeHash> m_ppCache;
+    FunctionCache<BlitterHash> m_blitterCache;
+    typedef FunctionCache<PixelPipeHash>::EntryHandle PixelPipeEntryHandle;
+    typedef FunctionCache<BlitterHash>::EntryHandle BlitterEntryHandle;
+    //std::vector<CacheEntry<BlitterHash> > blitterCache;
+    
+    ::llvm::LLVMContext m_llvmContext;
+
+    static PPCompiler* s_compiler;
+};
+
+}
+
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfDynamicBlitter.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,217 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#include "sfDynamicBlitter.h"
+
+#ifndef __SFBLITTER_H
+#   include "sfBlitter.h"
+#endif
+
+#ifndef __SFMASK_H
+#   include "sfMask.h"
+#endif
+
+namespace OpenVGRI {
+
+RI_INLINE static bool maskOperationRequiresLoad(VGMaskOperation op)
+{
+    switch(op)
+    {
+    case VG_CLEAR_MASK:
+    case VG_FILL_MASK:
+    case VG_SET_MASK:
+        return false;
+    default:
+        RI_ASSERT(op == VG_UNION_MASK || op == VG_INTERSECT_MASK || op == VG_SUBTRACT_MASK);
+        return true;
+    }
+}
+
+/**
+ * \brief   Blit rectangular areas between similar or different color format buffers.
+ * \note    Implementation is structured so that the per-pixel branches are minimized
+ *          even if dynamic compilation is not in use.
+ * \todo    For some reason the completely generic integer conversion does not optimize
+ *          fully run-time. Check what causes this!
+ */
+void executeBlitter(const DynamicBlitter::BlitSignatureState& state, const DynamicBlitter::BlitUniforms& uniforms)
+{
+    const void* srcPtr = Image::calculateAddress(
+        uniforms.src, state.srcDesc.bitsPerPixel, uniforms.srcX, uniforms.srcY, uniforms.srcStride); 
+    void* dstPtr = Image::calculateAddress(
+        uniforms.dst, state.dstDesc.bitsPerPixel, uniforms.dstX, uniforms.dstY, uniforms.dstStride);
+
+    // The following flag is useful for debugging. Enabling it will hurt performance.
+//#define ALWAYS_FORCE_FULL_CONVERSION
+
+    // Currently the data must be byte-aligned for memcpy optimizations:
+    const int minBpp = RI_INT_MIN(state.srcDesc.bitsPerPixel, state.dstDesc.bitsPerPixel);
+    const bool byteCopy = minBpp >= 8 ? true : false;
+    const bool forceFullConversion = state.isMaskOperation || state.unsafeInput || !byteCopy;
+    
+#if !defined(ALWAYS_FORCE_FULL_CONVERSION)
+    if (state.srcDesc.isZeroConversion(state.dstDesc) && !forceFullConversion)
+    {
+        const int fullCopyStride = Image::descriptorToStride(state.srcDesc, uniforms.width);
+
+        if ((uniforms.dstStride != uniforms.srcStride) || (fullCopyStride != uniforms.srcStride)) 
+        {
+            // memcpy individual scanlines.
+            const size_t scanLength = (size_t)RI_INT_ABS(Image::descriptorToStride(state.srcDesc, uniforms.width));
+            for (RIuint32 i = 0; i < uniforms.height; i++)
+            {
+                memcpy(dstPtr, srcPtr, scanLength);
+                dstPtr = (void*)((RIuint8*)dstPtr + uniforms.dstStride);
+                srcPtr = (void*)((RIuint8*)srcPtr + uniforms.srcStride);
+            }
+        } else
+        {
+            // memcpy the whole area
+            memcpy(dstPtr, srcPtr, uniforms.srcStride * uniforms.height);
+        }
+    } else if (state.srcDesc.isShiftConversion(state.dstDesc) && !forceFullConversion)
+    {
+        // \todo Separate to function? Replace with pointer read/write & advance.
+        if (state.srcDesc.isShiftConversionToLower(state.dstDesc))
+        {
+            // Components can be immediately shifted down to lower bit-depth.
+            for (RIuint32 j = 0; j < uniforms.height; j++)
+            {
+                RIuint8* srcStart = (RIuint8*)srcPtr;
+                RIuint8* dstStart = (RIuint8*)dstPtr;
+                RIuint32 srcX = uniforms.srcX;
+                RIuint32 dstX = uniforms.dstX;
+                for (RIuint32 i = 0; i < uniforms.width; i++)
+                {
+                    RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX); // \todo srcX!
+                    RIuint32 dc = Color::Descriptor::crossConvertToLower(c, state.srcDesc, state.dstDesc);
+                    Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc);
+
+                    srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                    dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); 
+
+                    srcX++;
+                    dstX++;
+                }
+                srcPtr = (void*)(srcStart + uniforms.srcStride);
+                dstPtr = (void*)(dstStart + uniforms.dstStride);
+            }
+        }
+        else
+        {
+            // Color components require expansion before shifting to destination color-format */
+            for (RIuint32 j = 0; j < uniforms.height; j++)
+            {
+                RIuint8* srcStart = (RIuint8*)srcPtr;
+                RIuint8* dstStart = (RIuint8*)dstPtr;
+                RIuint32 srcX = uniforms.srcX;
+                RIuint32 dstX = uniforms.dstX;
+                for (RIuint32 i = 0; i < uniforms.width; i++)
+                {
+                    RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                    IntegerColor ic = IntegerColor(c, state.srcDesc);
+                    ic.expandColor(state.srcDesc);
+                    ic.truncateColor(state.dstDesc);
+                    RIuint32 dc = ic.getPackedColor(state.dstDesc);
+                    Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc);
+
+                    srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                    dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); 
+
+                    srcX++;
+                    dstX++;
+                }
+                srcPtr = (void*)(srcStart + uniforms.srcStride);
+                dstPtr = (void*)(dstStart + uniforms.dstStride);
+            }
+        }
+    } else
+#endif
+    {
+        /* This block should handle the rest (and all) of the color-conversion cases. */
+        for (RIuint32 j = 0; j < uniforms.height; j++)
+        {
+            RIuint8* srcStart = (RIuint8*)srcPtr;
+            RIuint8* dstStart = (RIuint8*)dstPtr;
+            RIuint32 srcX = uniforms.srcX;
+            RIuint32 dstX = uniforms.dstX;
+            for (RIuint32 i = 0; i < uniforms.width; i++)
+            {
+                RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                IntegerColor ic;
+                RIuint32 dc;
+                
+                if (!state.isMaskOperation)
+                {
+                    ic = IntegerColor(c, state.srcDesc);
+                    if (state.unsafeInput)
+                        ic.clampToAlpha();
+
+                    ic.convertToFrom(state.dstDesc, state.srcDesc, false);
+                    dc = ic.getPackedColor(state.dstDesc);
+                }
+                else
+                {
+                    // Apply the given mask operation between two surfaces.
+                    IntegerColor id;
+
+                    if (maskOperationRequiresLoad(state.maskOperation))
+                    {
+                        ic.fromPackedMask(c, state.srcDesc);
+                        ic.expandMask(state.srcDesc);
+
+                        IntegerColor id;
+
+                        RIuint32 d = Image::readPackedPixelFromAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX);
+                        id.fromPackedMask(d, state.dstDesc);
+                        id.expandColor(state.dstDesc);
+
+                        RIuint32 coverage = ic.a + (ic.a >> 7);
+                        ic = intMaskOperation(coverage, id, state.maskOperation);
+                    }
+                    else
+                    {
+                        // Other ops handled with memset, not blitter
+                        RI_ASSERT(state.maskOperation == VG_SET_MASK); 
+                        ic.fromPackedMask(c, state.srcDesc);
+                        //ic.expandMask(state.srcDesc);
+                        ic.convertToFrom(state.dstDesc, state.srcDesc, true);
+                    }
+                    dc = ic.getPackedMaskColor(state.dstDesc);
+                }
+
+                Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc);
+
+                srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); 
+
+                srcX++;
+                dstX++;
+            }
+            srcPtr = (void*)(srcStart + uniforms.srcStride);
+            dstPtr = (void*)(dstStart + uniforms.dstStride);
+        }
+    }
+}
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfDynamicBlitter.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,38 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFDYNAMICBLITTER_H
+#define __SFDYNAMICBLITTER_H
+
+#ifndef __SFBLITTER_H
+#   include "sfBlitter.h"
+#endif
+
+namespace OpenVGRI {
+
+// Blitter function (may be statically compiled also)
+void executeBlitter(const DynamicBlitter::BlitSignatureState& state, const DynamicBlitter::BlitUniforms& uniforms);
+
+}
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfDynamicPixelPipe.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1533 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+// This file contains the generated pixel-pipeline code and provides
+// interface to compile and run them.
+
+#ifndef __RIRASTERIZER_H
+#   include "riRasterizer.h"
+#endif
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+
+#ifndef __SFDYNAMICPIXELPIPE_H
+#   include "sfDynamicPixelPipe.h"
+#endif
+
+#ifndef __RIUTILS_H
+#   include "riUtils.h"
+#endif
+
+#ifndef __SFMASK_H
+#   include "sfMask.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#   include "riImage.h"
+#endif
+
+#if defined(RI_DEBUG)
+#   include <stdio.h>
+#endif
+
+namespace OpenVGRI {
+
+RI_INLINE static bool alwaysLoadDst(const PixelPipe::SignatureState& state)
+{
+    if (!state.isRenderToMask)
+    {
+        if (state.hasImage)
+            return true;
+
+        VGBlendMode bm = state.blendMode;
+
+        if (bm == VG_BLEND_SRC_IN ||
+                bm == VG_BLEND_DST_OVER ||
+                bm == VG_BLEND_DST_IN ||
+                bm == VG_BLEND_ADDITIVE ||
+                bm == VG_BLEND_MULTIPLY ||
+                bm == VG_BLEND_SCREEN ||
+                bm == VG_BLEND_DARKEN ||
+                bm == VG_BLEND_LIGHTEN)
+        {
+            return true;
+        } else
+        {
+            return false;
+        }
+    }
+    else
+    {
+        switch (state.maskOperation)
+        {
+        case VG_SET_MASK:
+            return false;
+        default:
+            return true;
+        }
+    }
+}
+
+RI_INLINE static bool canSolidFill(const PixelPipe::SignatureState& state)
+{
+    if (state.isRenderToMask)
+    {
+        if (state.maskOperation == VG_SET_MASK ||
+            state.maskOperation == VG_UNION_MASK)
+            return true;
+        // \note SUBTRACT is also possible.
+        return false;
+    }
+
+    if (state.paintType != VG_PAINT_TYPE_COLOR)
+        return false;
+
+    if (state.hasImage)
+        return false;
+
+    // Some blendmodes can use dst color even if coverage == 1.0
+    if (state.blendMode != VG_BLEND_SRC && state.blendMode != VG_BLEND_SRC_OVER)
+        return false;
+
+    if (state.hasMasking)
+        return false;
+
+    if (state.fillColorTransparent)
+        return false;
+
+    if (state.hasColorTransform)
+        return false; // \todo Trace solid color alpha -> 1.0
+
+    return true;
+}
+
+RI_INLINE static int intReflectRepeat(int n, int bits)
+{
+    const int mask = (1<<bits)-1;
+    return (n ^ (n << (31 - bits) >> 31)) & mask;
+}
+
+RI_INLINE static void applyGradientRepeat(int& sx0, int& sx1, PixelPipe::TilingMode sm)
+{
+    switch (sm)
+    {
+    case PixelPipe::TILING_MODE_PAD:
+        sx0 = RI_INT_CLAMP(sx0, 0, PixelPipe::SAMPLE_MASK);
+        sx1 = RI_INT_CLAMP(sx1, 0, PixelPipe::SAMPLE_MASK);
+        break;
+    case PixelPipe::TILING_MODE_REFLECT:
+        sx0 = intReflectRepeat(sx0, PixelPipe::SAMPLE_BITS);
+        sx1 = intReflectRepeat(sx1, PixelPipe::SAMPLE_BITS);
+        break;
+    default:
+        RI_ASSERT(sm == PixelPipe::TILING_MODE_REPEAT);
+
+        sx0 = sx0 & PixelPipe::SAMPLE_MASK;
+        sx1 = sx1 & PixelPipe::SAMPLE_MASK;
+        break;
+    }
+
+    RI_ASSERT(sx0 >= 0 && sx0 < (1<<Paint::GRADIENT_LUT_BITS));
+    RI_ASSERT(sx1 >= 0 && sx1 < (1<<Paint::GRADIENT_LUT_BITS));
+
+}
+
+RI_INLINE static IntegerColor readLUTColor(const PixelPipe::PPUniforms& uniforms, int i)
+{
+    RI_ASSERT(i >= 0 && i <= Paint::GRADIENT_LUT_MASK);
+    return uniforms.gradientLookup[i];
+}
+
+
+/**
+ * \brief   Sample linear gradient using integer-arithmetic.
+ * \note    The actual gradient computation is done piecewise within the
+ *          pixel-pipeline.
+ */
+RI_INLINE static IntegerColor intLinearGradient(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v)
+{
+    RIint32 sx0 = v.sx >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS);
+    RIint32 sx1 = sx0 + 1;
+
+    applyGradientRepeat(sx0, sx1, state.paintTilingMode);
+
+    IntegerColor ic0 = readLUTColor(u, sx0 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS));
+
+    if (true)
+    {
+        return ic0;
+    } else
+    {
+        // bilinear interpolation
+        //RIint32 f1 = sx0; 
+        readLUTColor(u, sx1 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS));
+        RI_ASSERT(false);
+        return IntegerColor(0,0,0,0);
+    }
+} 
+
+/**
+ * \brief   Radial gradient implementation for the integer-pipeline. Will use float at least
+ *          for the square-root. Will return integer-color always.
+ */
+RI_INLINE static IntegerColor intRadialGradient(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v)
+{
+    RGScalar a = (v.rx * u.rfxp) + (v.ry * u.rfyp);
+    RGScalar b = u.rsqrp * (RI_SQR(v.rx) + RI_SQR(v.ry));
+    RGScalar c = RI_SQR((v.rx * u.rfyp) - (v.ry * u.rfxp));
+    RGScalar d = b - c;
+    RI_ASSERT(!RI_ISNAN(d) ? d >= 0.0f : true);
+    RGScalar g = (a + sqrtf(d));
+
+    int sx0 = RI_FLOAT_TO_FX(g, PixelPipe::SAMPLE_BITS);
+    int sx1 = sx0 + 1;
+
+    applyGradientRepeat(sx0, sx1, state.paintTilingMode);
+
+    IntegerColor ic0 = readLUTColor(u, sx0 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS));
+    RI_ASSERT(ic0.r <= 255);
+    RI_ASSERT(ic0.g <= 255);
+    RI_ASSERT(ic0.b <= 255);
+    RI_ASSERT(ic0.a <= 255);
+
+    if (false)
+    {
+        // Linear interpolation of 2 gradient samples.
+        IntegerColor ic1 = readLUTColor(u, sx1 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS));
+        //int fx0 = sx0 & PixelPipe::SAMPLE_MASK;
+        //int fx1 = PixelPipe::SAMPLE_MASK - fx0;
+        
+    }
+
+    return ic0;
+}
+
+RI_INLINE static bool applyPatternRepeat(int &x, int &y, PixelPipe::TilingMode tilingMode)
+{
+    switch (tilingMode)
+    {
+    case PixelPipe::TILING_MODE_PAD:
+        x = RI_INT_CLAMP(x, 0, PixelPipe::GRADIENT_MASK);
+        y = RI_INT_CLAMP(y, 0, PixelPipe::GRADIENT_MASK);
+        break; 
+    case PixelPipe::TILING_MODE_REPEAT:
+        x = x & PixelPipe::GRADIENT_MASK;
+        y = y & PixelPipe::GRADIENT_MASK;
+        break;
+    case PixelPipe::TILING_MODE_REFLECT:
+        x = intReflectRepeat(x, PixelPipe::GRADIENT_BITS);
+        y = intReflectRepeat(y, PixelPipe::GRADIENT_BITS);
+        break;
+    default:
+        RI_ASSERT(tilingMode == PixelPipe::TILING_MODE_FILL);
+        // Do nothing -> Fill is checked on integer coordinates.
+        break;
+    }
+    return false;
+}
+
+/**
+ * \brief   Same as applyPatternRepeat, but with pattern-space integer coordinates without
+ *          fractional part.
+ * \note    Assumes that the coordinate is in range [0,width or height].
+ */
+RI_INLINE static bool applyPatternSampleRepeat(int &x, int &y, int w, int h, PixelPipe::TilingMode tilingMode)
+{
+
+    switch (tilingMode)
+    {
+    case PixelPipe::TILING_MODE_PAD:
+        RI_ASSERT(x >= 0 && x <= w);
+        RI_ASSERT(y >= 0 && y <= h);
+        if (x >= w) x = w-1;
+        if (y >= h) y = h-1;
+        break;
+    case PixelPipe::TILING_MODE_REPEAT:
+        RI_ASSERT(x >= 0 && x <= w);
+        RI_ASSERT(y >= 0 && y <= h);
+        if (x >= w) x = 0;
+        if (y >= h) y = 0;
+        break;
+    case PixelPipe::TILING_MODE_REFLECT:
+        RI_ASSERT(x >= 0 && x <= w);
+        RI_ASSERT(y >= 0 && y <= h);
+        if (x >= w) x = w-1; // w-2?
+        if (y >= h) y = h-1; // h-2?
+        break;
+    default:
+        RI_ASSERT(tilingMode == PixelPipe::TILING_MODE_FILL);
+        if (x < 0 || x >= w) return true;
+        if (y < 0 || y >= h) return true;
+        break;
+    }
+
+    return false;
+}
+
+RI_INLINE IntegerColor readPattern(const void* basePtr, int stride, const Color::Descriptor& desc, int ix, int iy, const IntegerColor* fillColor, bool fill)
+{
+    const void* ptr = Image::calculateAddress(basePtr, desc.bitsPerPixel, ix, iy, stride);
+
+    if (!fill)
+        return IntegerColor(Image::readPackedPixelFromAddress(ptr, desc.bitsPerPixel, ix), desc);
+    else
+    {
+        RI_ASSERT(fillColor);
+        return *fillColor; 
+    }
+
+}
+
+/**
+ * \brief   Rescale the result of bilinear interpolation.
+ * \todo    See if this or individual shifts and rounds are faster on x86
+ */
+RI_INLINE static RIuint32 bilinearDiv(unsigned int c)
+{
+    RIuint32 rcp = 33026;
+
+    RIuint64 m = (RIuint64)c * rcp;
+    RIuint32 d = (RIuint32)(m >> 30);
+    return (d >> 1) + (d & 1);
+}
+
+/**
+ * \brief   Read an optionally filtered sample from an image. For multiple samples, apply repeat
+ *          for all the generated sampling points. This only implements a simple sampling: nearest
+ *          or Linear filtering and is much simpler than the original RI.
+ * \param   image       Image to sample from
+ * \param   sx0         Sample x in .8 fixed point. MUST be within the image except for FILL.
+ * \param   sy0         Sample y in .8 fixed point. MUST be within the image except for FILL.
+ * \param   samplerType Type of the sampler used.
+ * \param   tilingMode  Tiling mode for generated sample points, if required.
+ * \param   fillColor   Color to use for TILING_MODE_FILL
+ * \todo Where should we determine if a NN-sample needs to be unpacked?
+ *       -> It is also easy to just read that sample separately.
+ */
+RI_INLINE static IntegerColor intSampleImage(
+    const void* ptr,
+    int stride,
+    int w,
+    int h,
+    const Color::Descriptor& desc,
+    RIint32 sx0, 
+    RIint32 sy0, 
+    PixelPipe::SamplerType samplerType, 
+    PixelPipe::TilingMode tilingMode, 
+    const IntegerColor* fillColor)
+{
+    RI_ASSERT(fillColor || (tilingMode != PixelPipe::TILING_MODE_FILL));
+     
+    // \todo The following code is between low- and high-level representation of sampling.
+    // It should probably be modified to appear fully as low-level, since we want as many
+    // optimizations as possible.
+
+    const bool bilinear = samplerType == PixelPipe::SAMPLER_TYPE_LINEAR;
+
+    IntegerColor retColor;
+    bool maybeFill = tilingMode == PixelPipe::TILING_MODE_FILL;
+    bool fillSample = false;
+
+    RIint32 ix, iy;
+
+    IntegerColor ic00;
+
+    RIint32 fx = sx0 & 0xff;
+    RIint32 fy = sy0 & 0xff;
+
+    ix = sx0 >> PixelPipe::SAMPLE_BITS;
+    iy = sy0 >> PixelPipe::SAMPLE_BITS;
+
+    if (maybeFill)
+    {
+        if (ix < 0 || ix >= w)
+            fillSample = true;
+        if (iy < 0 || iy >= h)
+            fillSample = true;
+    }
+
+    ic00 = readPattern(ptr, stride, desc, ix, iy, fillColor, fillSample);
+
+    if (!bilinear)
+    {
+        retColor = ic00;
+        retColor.expandColor(desc); // \todo Handling of bilinear?
+    }
+    else
+    {
+        // Bilinear filtering.
+
+        IntegerColor ic01, ic10, ic11;
+        IntegerColor t0, t1;
+
+        int xs = ix + 1;
+        int ys = iy;
+
+        fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode);
+        ic01 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample);
+
+        t0 = IntegerColor::linearBlendNS(ic00, ic01, fx);
+
+        xs = ix;
+        ys = iy+1;
+        fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode);
+        ic10 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample);
+
+        xs = ix+1;
+        ys = iy+1;
+        fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode);
+        ic11 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample);
+    
+        t1 = IntegerColor::linearBlendNS(ic10, ic11, fx);
+    
+        retColor = IntegerColor::linearBlendNS(t0, t1, fy);
+
+        retColor.r = bilinearDiv(retColor.r);
+        retColor.g = bilinearDiv(retColor.g);
+        retColor.b = bilinearDiv(retColor.b);
+        retColor.a = bilinearDiv(retColor.a);
+
+        return retColor;
+    }
+
+    return retColor;
+}
+
+RI_INLINE static RIint32 gradientToFixedCoords(RIint32 gradCoord, RIint32 dim)
+{
+    return (RIint32)(((RIint64)dim * gradCoord) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS));
+}
+
+
+RI_INLINE static IntegerColor intPattern(const PixelPipe::SignatureState &state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v)
+{
+    // \todo The following code is between low- and high-level representation of sampling.
+    // It should probably be modified to appear fully as low-level, since we want as many
+    // optimizations as possible.
+
+    // "External" variables
+    const PixelPipe::TilingMode tilingMode = state.paintTilingMode;
+    const IntegerColor fillColor = u.tileFillColor;
+    const int w = u.paint_width;
+    const int h = u.paint_height;
+
+    IntegerColor retColor;
+
+    RIint32 sx0 = v.sx;
+    RIint32 sy0 = v.sy;
+
+    IntegerColor ic00;
+
+    applyPatternRepeat(sx0, sy0, tilingMode);
+    sx0 = gradientToFixedCoords(sx0, w);
+    sy0 = gradientToFixedCoords(sy0, h);
+    //sx0 = (RIint32)(((RIint64)w * sx0) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS));
+    //sy0 = (RIint32)(((RIint64)h * sy0) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS));
+
+    const void* ptr = u.patternPtr;
+    const int stride = u.patternStride;
+    const Color::Descriptor& desc = state.patternDesc;
+
+    return intSampleImage(ptr, stride, w, h, desc, sx0, sy0, state.paintSampler, tilingMode, &fillColor);
+}
+
+RI_INLINE static bool formatPremultipliedAfterSampling(const Color::Descriptor& desc, PixelPipe::SamplerType samplerType, PixelPipe::ImageGradientType gradientType)
+{
+    // Sampled at pixel centers -> no processing of colors -> does not get premultiplied
+    if (gradientType == PixelPipe::GRADIENT_TYPE_INTEGER)
+        return desc.isPremultiplied();
+
+    if (samplerType != PixelPipe::SAMPLER_TYPE_NEAREST)
+        return true;
+
+    return desc.isPremultiplied();
+}
+
+RI_INLINE static bool imagePremultipliedAfterSampling(const PixelPipe::SignatureState& state)
+{
+    RI_ASSERT(state.hasImage);
+
+    return formatPremultipliedAfterSampling(state.imageDesc, state.imageSampler, state.imageGradientType);
+}
+
+RI_INLINE static bool gradientPremultipliedAfterSampling(const PixelPipe::SignatureState& state)
+{
+    if (state.paintSampler != PixelPipe::SAMPLER_TYPE_NEAREST)
+        return true;
+
+    return true;
+
+    // Otherwise, the gradient value is a single sample, and should be in the destination
+    // color-space:
+    //return state.dstDesc.isPremultiplied();
+}
+
+RI_INLINE static bool patternPremultipliedAfterSampling(const PixelPipe::SignatureState& state)
+{
+    RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN);
+
+    return formatPremultipliedAfterSampling(state.patternDesc, state.paintSampler, PixelPipe::GRADIENT_TYPE_FIXED);
+}
+
+/**
+ * \brief   Returns true if generated paint will be in RGB, false if luminance.
+ */
+RI_INLINE static bool paintInRGB(const PixelPipe::SignatureState& state)
+{
+    if (state.paintType != VG_PAINT_TYPE_PATTERN)
+        return true;
+
+    return !state.patternDesc.isLuminance();
+}
+
+
+/**
+ * \brief   Applies color transform to input color
+ * \param   isNonlinear "true" if input is nonlinear. This only affects luminance -> RGB conversion,
+ *          other conversions happen in the input color-space.
+ * \note    Leaves the color unpremultiplied, in source color-space and converts luminance to RGB
+ * \todo    isNonlinear is not needed. It can be deduced from the state information!
+ */
+RI_INLINE static IntegerColor maybeColorTransform(const PixelPipe::SignatureState& state, const IntegerColor& c, const RIint32* colorTransformValues, bool isNonlinear)
+{
+    if (!state.hasColorTransform)
+        return c;
+
+    RI_ASSERT(state.hasImage || state.paintType == VG_PAINT_TYPE_PATTERN);
+    
+    IntegerColor r = c;
+
+    if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY)
+    {
+        r.unpremultiply();
+    }
+    else if (state.imageMode == VG_DRAW_IMAGE_STENCIL || state.paintType == VG_PAINT_TYPE_PATTERN)
+    {
+        // -> Check pattern
+        if (patternPremultipliedAfterSampling(state))
+            r.unpremultiply(); 
+    }
+    else
+    {
+        // -> Check image
+        if (imagePremultipliedAfterSampling(state))
+            r.unpremultiply();
+    }
+
+    // Check if it is necessary to convert to RGB:
+    if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY)
+    {
+        if (state.imageDesc.isLuminance() && !paintInRGB(state))
+        {
+            r.fullLuminanceToRGB(false, isNonlinear, false, isNonlinear);
+        }
+    }
+    else if (state.imageMode == VG_DRAW_IMAGE_STENCIL)
+    {
+        if (state.patternDesc.isLuminance())
+            r.fullLuminanceToRGB(false, isNonlinear, false, isNonlinear);
+    }
+    
+    // \todo Use lookup-tables in some cases?
+    r.r = (((RIint32)r.r * colorTransformValues[0]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[4];
+    r.g = (((RIint32)r.g * colorTransformValues[1]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[5];
+    r.b = (((RIint32)r.b * colorTransformValues[2]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[6];
+    r.a = (((RIint32)r.a * colorTransformValues[3]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[7];
+
+    // Clamp (integerColor?)
+    r.r = (RIuint32)RI_INT_CLAMP((int)r.r, 0, 255);
+    r.g = (RIuint32)RI_INT_CLAMP((int)r.g, 0, 255);
+    r.b = (RIuint32)RI_INT_CLAMP((int)r.b, 0, 255);
+    r.a = (RIuint32)RI_INT_CLAMP((int)r.a, 0, 255);
+
+
+    return r;
+}
+
+/// Some rounding multiplications for blends:
+
+/**
+ * \brief   Multiply with rounding.
+ */
+RI_INLINE static RIuint32 rMul2(RIuint32 c0, RIuint32 c1, RIuint32 k0, RIuint32 k1)
+{
+    RIuint32 t = c0 * k0 + c1 * k1; 
+    //RIuint32 r = (t + (t>>9)) >> 8;
+    RIuint32 r = (t + (1>>7))>>8;
+    RI_ASSERT(r <= 255);
+    return r;
+}
+
+/**
+ * \brief   Returns rounding color-multiplication: c0 + c1 * k
+ */
+RI_INLINE static RIuint32 rMul1(RIuint32 c0, RIuint32 c1, RIuint32 k)
+{
+    RIuint32 t = c1 * k;
+    RIuint32 r = c0 + ((t + (t >> 7)) >> 8);
+    RI_ASSERT(r <= 255);
+    return r;
+}
+
+/**
+ * \brief   Fixed-point multiplication
+ */
+RI_INLINE static RIuint32 rMul(RIuint32 c0, RIuint32 f)
+{
+    RIuint32 t = c0 * f;
+    return (t + (1<<7))>>8;
+}
+
+/**
+ * \brief   Multiply two colors [0, 255]
+ */
+RI_INLINE static RIuint32 cMul(RIuint32 c0, RIuint32 c1)
+{
+    RIuint32 t = c0 * c1;
+    RIuint32 r = (t + (t >> 9)) >> 8;
+    //RIuint32 t = c0 * c1;
+    //RIuint32 r = (t + (t >> 7))>>8;
+    RI_ASSERT(r <= 255);
+    return r;
+}
+
+// \todo Are signed versions required?
+RI_INLINE static RIuint32 cMin(RIuint32 c0, RIuint32 c1)
+{
+    return c0 <= c1 ? c0 : c1;
+}
+
+RI_INLINE static RIuint32 cMax(RIuint32 c0, RIuint32 c1)
+{
+    return c0 >= c1 ? c0 : c1;
+}
+
+/**
+ * \brief   Blends two integer colors. Only considers the alpha-channels within
+ *          the colors themselves. There should be a separate function to do
+ *          blending with individual channel-alphas.
+ * \note    It is also possible that LLVM is able to detect, whether individual alpha-
+ *          channels contain a single/multi alpha
+ * \todo    Overall, check how much and how fast LLVM is able to optimize out unused
+ *          expressions.
+ */
+RI_INLINE static IntegerColor blendIntegerColors(const IntegerColor& s, const IntegerColor& d, VGBlendMode blendMode)
+{
+    IntegerColor r;
+
+    switch(blendMode)
+    {
+    case VG_BLEND_SRC:
+        r = s;
+        break;
+
+    case VG_BLEND_SRC_OVER:
+    {
+        RIuint32 ia = 255 - s.a;
+        r.r = rMul1(s.r, d.r, ia);
+        r.g = rMul1(s.g, d.g, ia);
+        r.b = rMul1(s.b, d.b, ia);
+        r.a = rMul1(s.a, d.a, ia);
+        break;
+    }
+    case VG_BLEND_DST_OVER:
+    {
+        RIuint32 ia = 255 - d.a;
+        r.r = rMul1(d.r, s.r, ia);
+        r.g = rMul1(d.g, s.g, ia);
+        r.b = rMul1(d.b, s.b, ia);
+        r.a = rMul1(d.a, s.a, ia);
+        break;
+    }
+    case VG_BLEND_SRC_IN:
+    {
+        r.r = cMul(s.r, d.a);
+        r.g = cMul(s.g, d.a);
+        r.b = cMul(s.b, d.a);
+        r.a = cMul(s.a, d.a);
+        break;
+    }
+    case VG_BLEND_DST_IN:
+    {
+        r.r = cMul(d.r, s.a);
+        r.g = cMul(d.g, s.a);
+        r.b = cMul(d.b, s.a);
+        r.a = cMul(d.a, s.a);
+        break;
+    }
+    case VG_BLEND_MULTIPLY:
+    {
+        RIuint32 iasrc, iadst;
+        iasrc = 255 - s.a;
+        iadst = 255 - d.a;
+        r.r = rMul2(s.r, d.r, iadst + d.r, iasrc);
+        r.g = rMul2(s.g, d.g, iadst + d.g, iasrc);
+        r.b = rMul2(s.b, d.b, iadst + d.b, iasrc);
+        r.a = rMul1(s.a, d.a, iasrc);
+        break;
+    }
+    case VG_BLEND_SCREEN:
+    {
+        r.r = rMul1(s.r, d.r, 255 - s.r);
+        r.g = rMul1(s.g, d.g, 255 - s.g);
+        r.b = rMul1(s.b, d.b, 255 - s.b);
+        r.a = rMul1(s.a, d.a, 255 - s.a);
+        break;
+    }
+    case VG_BLEND_DARKEN:
+    {
+        RIuint32 iasrc = 255 - s.a;
+        RIuint32 iadst = 255 - d.a;
+        r.r = cMin(rMul1(s.r, d.r, iasrc), rMul1(d.r, s.r, iadst));
+        r.g = cMin(rMul1(s.g, d.g, iasrc), rMul1(d.g, s.g, iadst));
+        r.b = cMin(rMul1(s.b, d.b, iasrc), rMul1(d.b, s.b, iadst));
+        r.a = rMul1(s.a, d.a, iasrc);
+        break;
+    }
+    case VG_BLEND_LIGHTEN:
+    {
+        // \todo Compact darken w/r lighten?
+        RIuint32 iasrc = 255 - s.a;
+        RIuint32 iadst = 255 - d.a;
+        r.r = cMax(rMul1(s.r, d.r, iasrc), rMul1(d.r, s.r, iadst));
+        r.g = cMax(rMul1(s.g, d.g, iasrc), rMul1(d.g, s.g, iadst));
+        r.b = cMax(rMul1(s.b, d.b, iasrc), rMul1(d.b, s.b, iadst));
+        //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a)
+        //in practice there can be a very slight difference because
+        //of the max operation in the blending formula that may cause color to exceed alpha.
+        //Because of this, we compute the result both ways and return the maximum.
+        r.a = cMax(rMul1(s.a, d.a, iasrc), rMul1(d.a, s.a, iadst));
+        break;
+    }
+    default:
+    {
+        RI_ASSERT(blendMode == VG_BLEND_ADDITIVE);
+        r.r = cMin(s.r + d.r, 255);
+        r.g = cMin(s.g + d.g, 255);
+        r.b = cMin(s.b + d.b, 255);
+        r.a = cMin(s.a + d.a, 255);
+        break;
+    }
+    }
+    return r;
+
+}
+
+RI_INLINE static IntegerColor blendIntegerStencil(const IntegerColor& s, const IntegerColor& im, const IntegerColor& d, VGBlendMode blendMode)
+{
+    IntegerColor r;
+
+    switch(blendMode)
+    {
+    case VG_BLEND_SRC:
+        r = s;
+        break;
+
+    case VG_BLEND_SRC_OVER:
+    {
+        r.r = rMul1(s.r, d.r, 255 - im.r);
+        r.g = rMul1(s.g, d.g, 255 - im.g);
+        r.b = rMul1(s.b, d.b, 255 - im.b);
+        r.a = rMul1(s.a, d.a, 255 - s.a);
+        break;
+    }
+    case VG_BLEND_DST_OVER:
+    {
+        r = blendIntegerColors(s, d, blendMode);
+        break;
+    }
+    case VG_BLEND_SRC_IN:
+    {
+        r = blendIntegerColors(s, d, blendMode);
+        break;
+    }
+    case VG_BLEND_DST_IN:
+    {
+        r.r = cMul(d.r, im.r);
+        r.g = cMul(d.g, im.g);
+        r.b = cMul(d.b, im.b);
+        r.a = cMul(d.a, s.a);
+        break;
+    }
+    case VG_BLEND_MULTIPLY:
+    {
+        RIuint32 iadst;
+        iadst = 255 - d.a;
+        r.r = rMul2(s.r, d.r, iadst + d.r, 255 - im.r);
+        r.g = rMul2(s.g, d.g, iadst + d.g, 255 - im.g);
+        r.b = rMul2(s.b, d.b, iadst + d.b, 255 - im.b);
+        r.a = rMul1(s.a, d.a, 255 - s.a);
+        break;
+    }
+    case VG_BLEND_SCREEN:
+    {
+        r = blendIntegerColors(s, d, blendMode);
+        break;
+    }
+    case VG_BLEND_DARKEN:
+    {
+        RIuint32 iadst = 255 - d.a;
+        r.r = cMin(rMul1(s.r, d.r, 255 - im.r), rMul1(d.r, s.r, iadst));
+        r.g = cMin(rMul1(s.g, d.g, 255 - im.g), rMul1(d.g, s.g, iadst));
+        r.b = cMin(rMul1(s.b, d.b, 255 - im.b), rMul1(d.b, s.b, iadst));
+        r.a = rMul1(s.a, d.a, 255 - s.a);
+        break;
+    }
+    case VG_BLEND_LIGHTEN:
+    {
+        // \todo Compact darken w/r lighten?
+        RIuint32 iadst = 255 - d.a;
+        r.r = cMax(rMul1(s.r, d.r, 255 - im.r), rMul1(d.r, s.r, iadst));
+        r.g = cMax(rMul1(s.g, d.g, 255 - im.g), rMul1(d.g, s.g, iadst));
+        r.b = cMax(rMul1(s.b, d.b, 255 - im.b), rMul1(d.b, s.b, iadst));
+        //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a)
+        //in practice there can be a very slight difference because
+        //of the max operation in the blending formula that may cause color to exceed alpha.
+        //Because of this, we compute the result both ways and return the maximum.
+        r.a = cMax(rMul1(s.a, d.a, 255 - s.a), rMul1(d.a, s.a, iadst));
+        break;
+    }
+    default:
+    {
+        RI_ASSERT(blendMode == VG_BLEND_ADDITIVE);
+        return blendIntegerColors(s, d, blendMode);
+        break;
+    }
+    }
+    return r;
+
+}
+
+/**
+ * \brief   Perform SRC_OVER and apply coverage in a single operation.
+ * \note    It is possible to do optimizations like this for other blending operations,
+ *          but they are not as widely used -> optimize if there is a requirement.
+ * \note    Prints are included because GDB is confused about the value of r.
+ */
+static RI_INLINE IntegerColor srcOverCoverage(const IntegerColor& s, const IntegerColor& d, RIuint32 cov)
+{
+    IntegerColor r;
+    RIuint32 ac = ((s.a + (s.a>>7)) * cov);
+    ac = (ac + (1<<7))>>8;
+    RIuint32 ia = 256 - ac;
+
+    r.r = rMul2(s.r, d.r, cov, ia);
+    r.g = rMul2(s.g, d.g, cov, ia);
+    r.b = rMul2(s.b, d.b, cov, ia);
+    r.a = rMul2(s.a, d.a, cov, ia);
+    //r.r = (s.r * cov + d.r * ia) >> 8;
+    //r.g = (s.g * cov + d.g * ia) >> 8;
+    //r.b = (s.b * cov + d.b * ia) >> 8;
+    //r.a = (s.a * cov + d.a * ia) >> 8;
+
+#if defined(RI_DEBUG)
+    if (!(r.r <= r.a && r.g <= r.a && r.b <= r.a && r.a <= 255))
+    {
+        printf("r: %d, g: %d, b: %d, a: %d\n",r.r,r.g,r.b,r.a);
+        RI_ASSERT(false);
+    }
+    //RI_ASSERT(r.r <= 255 && r.g <= 255 && r.b <= 255 && r.a <= 255);
+#endif
+
+    return r;
+}
+
+/**
+ * \brief   Check if converting between two color formats requires a gamma-conversion.
+ * \todo    Move this to descriptor class.
+ */
+static RI_INLINE bool needGammaConvert(const Color::Descriptor& srcDesc, const Color::Descriptor& dstDesc)
+{
+    //if ((!srcDesc.isAlphaOnly()) && (srcDesc.isNonlinear() != dstDesc.isNonlinear()))
+        //return true;
+    if ((srcDesc.isNonlinear() != dstDesc.isNonlinear()))
+        return true;
+
+    return false;
+}
+
+
+RI_INLINE static bool preBlendPremultiplication(const PixelPipe::SignatureState& state)
+{
+    // \todo Simplify the rules (see the corresponding places in the pixelpipe
+    const bool colorTransform = state.hasColorTransform;
+
+    if (PixelPipe::isImageOnly(state))
+    {
+        if (colorTransform)
+            return true;
+
+        // Gamma conversion will leave the result premultiplied
+        if (needGammaConvert(state.imageDesc, state.dstDesc))
+            return true;
+        //if (state.imageDesc.isAlphaOnly())
+            //return false;
+
+        return !imagePremultipliedAfterSampling(state);
+    }
+
+    if (state.hasImage)
+    {
+        if (state.imageMode == VG_DRAW_IMAGE_NORMAL)
+            return !imagePremultipliedAfterSampling(state);
+        // Image color has been combined with the paint color and that requires premultiplication
+        if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY)
+            return false; // Always results in a premultiplied output color
+
+        return false; // ?
+    }
+
+    if (state.paintType == VG_PAINT_TYPE_COLOR)
+        return false;
+
+    if (state.paintType != VG_PAINT_TYPE_PATTERN)
+        return !gradientPremultipliedAfterSampling(state);
+
+    // Must be pattern
+    RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN);
+
+    if (state.hasColorTransform)
+        return true;
+
+    if (needGammaConvert(state.patternDesc, state.dstDesc))
+        return true;
+    
+    return !patternPremultipliedAfterSampling(state);
+}
+
+/**
+ * \brief   Apply coverage [0 .. 256] on color
+ * \note    This is actually "just coverage".
+ */
+RI_INLINE static IntegerColor srcCoverage(const IntegerColor& s, const IntegerColor& d, RIuint32 cov)
+{
+    IntegerColor r;
+    RIuint32 icov = 256-cov;
+    // Make function for multiplication between fixed point values (coverage is
+    // a proper [0 .. 1] value.
+    r.r = (s.r * cov + d.r * icov) >> 8;
+    r.g = (s.g * cov + d.g * icov) >> 8;
+    r.b = (s.b * cov + d.b * icov) >> 8;
+    r.a = (s.a * cov + d.a * icov) >> 8;
+
+    RI_ASSERT(r.r <= 255 && r.g <= 255 && r.b <= 255 && r.a <= 255);
+
+    return r;
+}
+
+/**
+ * \brief   Converts color gamma only. Care must be taken concerning luminance color formats.
+ * \return  Converted color in "color". This will always be unpremultiplied if gamma conversion
+ *          takes place, i.e, tries to minimize the amount of further conversions.
+ */
+RI_INLINE static void maybeGammaConvert(const Color::Descriptor& srcDesc, const Color::Descriptor& dstDesc, IntegerColor& color, bool inputPremultiplied)
+{
+    if (needGammaConvert(srcDesc, dstDesc))
+    {
+        if (inputPremultiplied)
+            color.unpremultiply();
+            //color.unpremultiply(srcDesc.isLuminance());
+
+        if (dstDesc.isNonlinear())
+            color.linearToGamma();
+        else
+            color.gammaToLinear();
+    }
+    // Output always unpremultiplied if gamma conversion takes place
+}
+
+/**
+ * \brief   Integer pixel-pipeline.
+ * \note    See internal_formats.txt for info on how the data is passed within the pipeline
+ */
+RI_INLINE static void intPixelPipe(const PixelPipe::SignatureState& signatureState, const PixelPipe::PPUniforms &uniforms, PixelPipe::PPVariants& variants)
+{
+    const RIuint32 ppMaxCoverage = Rasterizer::MAX_COVERAGE << (8 - Rasterizer::SAMPLE_BITS);
+    RIuint32 coverage = variants.coverage << (8 - Rasterizer::SAMPLE_BITS);
+    IntegerColor out;
+    IntegerColor imageColor; // imagemode != normal
+    const Color::Descriptor& dstDesc = signatureState.dstDesc;
+    const Color::Descriptor& patternDesc = signatureState.patternDesc;
+    const Color::Descriptor& imageDesc = signatureState.imageDesc;
+
+    if (!PixelPipe::isImageOnly(signatureState))
+    {
+        switch(signatureState.paintType)
+        {
+        case VG_PAINT_TYPE_COLOR:
+            out = uniforms.solidColor;
+            break;
+        case VG_PAINT_TYPE_LINEAR_GRADIENT:
+            out = intLinearGradient(signatureState, uniforms, variants);
+            variants.sx += uniforms.dgdx;
+            // \todo Optimize this so that the lookup is in premultiplied dst format!
+            // How about image-operations?
+            if ((signatureState.imageMode != VG_DRAW_IMAGE_MULTIPLY) && dstDesc.isLuminance())
+            {
+                out.fullRGBToLuminance(true, dstDesc.isNonlinear(), true, dstDesc.isNonlinear());
+            }
+            break;
+        case VG_PAINT_TYPE_RADIAL_GRADIENT:
+            out = intRadialGradient(signatureState, uniforms, variants);
+            variants.rx += uniforms.rdxdx;
+            variants.ry += uniforms.rdydx;
+
+            // \todo Optimize this so that the lookup is in premultiplied dst format!
+            if ((signatureState.imageMode != VG_DRAW_IMAGE_MULTIPLY) && dstDesc.isLuminance())
+            {
+                out.fullRGBToLuminance(true, dstDesc.isNonlinear(), true, dstDesc.isNonlinear());
+            }
+            break;
+        default:
+            RI_ASSERT(signatureState.paintType == VG_PAINT_TYPE_PATTERN);
+            out = intPattern(signatureState, uniforms, variants);
+            // color-space == pattern color-space, not always premultiplied, expanded
+            //
+            // \todo Only increment the proper pixel-counters. This requires detecting the
+            // transform type before generating the pixel-pipeline.
+            // \note Implement fastpaths for at least identity transform with image edges coinciding
+            // with the pixel edges. <- This has been done for images.
+            variants.sx += uniforms.paint_dxdx;
+            variants.sy += uniforms.paint_dydx;
+
+            if (!patternDesc.hasAlpha())
+                out.a = 255;
+
+            if (!signatureState.hasImage)
+            {
+                out = maybeColorTransform(signatureState, out, uniforms.colorTransformValues, patternDesc.isNonlinear());
+                const bool tmpPre = patternPremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform;
+                const bool outLuminance = !signatureState.hasColorTransform && imageDesc.isLuminance();
+
+                if (outLuminance != dstDesc.isLuminance())
+                {
+                    if (outLuminance)
+                        out.fullLuminanceToRGB(tmpPre, patternDesc.isNonlinear(), tmpPre, patternDesc.isNonlinear());
+                    else
+                        out.fullRGBToLuminance(tmpPre, patternDesc.isNonlinear(), tmpPre, patternDesc.isNonlinear());
+                }
+                maybeGammaConvert(patternDesc, dstDesc, out, tmpPre);
+            }
+
+            break;
+        }
+    }
+    
+    if (signatureState.hasImage)
+    {
+        switch (signatureState.imageGradientType)
+        {
+        case PixelPipe::GRADIENT_TYPE_INTEGER:
+        {
+            void* addr = Image::calculateAddress(uniforms.imagePtr, imageDesc.bitsPerPixel, variants.iImageX, variants.iImageY, uniforms.imageStride);
+            RIuint32 packedImageColor = Image::readPackedPixelFromAddress(addr, imageDesc.bitsPerPixel, variants.iImageX);
+            imageColor.fromPackedColor(packedImageColor, imageDesc);
+            imageColor.expandColor(imageDesc);
+            // color-space == image color-space, not always premultiplied, expanded
+
+            // Only integer image-gradient can have unsafe image data as an input at the moment.
+            if (signatureState.unsafeImageInput)
+            {
+                if (imageDesc.hasAlpha() && imageDesc.isPremultiplied())
+                    imageColor.clampToAlpha();
+            }
+
+            variants.iImageX += uniforms.image_idxdx;
+            variants.iImageY += uniforms.image_idydx;
+            break;
+        }
+        case PixelPipe::GRADIENT_TYPE_FIXED:
+        {
+            RI_ASSERT(!signatureState.unsafeImageInput);
+
+            RIint32 sx, sy;
+            sx = variants.iImageX;
+            sy = variants.iImageY;
+            applyPatternRepeat(sx, sy, PixelPipe::TILING_MODE_PAD);
+            sx = gradientToFixedCoords(sx, uniforms.image_iWidth);
+            sy = gradientToFixedCoords(sy, uniforms.image_iHeight);
+            imageColor = intSampleImage(
+                uniforms.imagePtr,
+                uniforms.imageStride,
+                uniforms.image_iWidth,
+                uniforms.image_iHeight,
+                imageDesc,
+                sx, sy, signatureState.imageSampler, PixelPipe::TILING_MODE_PAD, NULL);
+
+            variants.iImageX += uniforms.image_idxdx;
+            variants.iImageY += uniforms.image_idydx;
+            break;
+        }
+        default:
+        {
+            RI_ASSERT(signatureState.imageGradientType == PixelPipe::GRADIENT_TYPE_FLOAT);
+            RI_ASSERT(!signatureState.unsafeImageInput);
+
+            RIfloat fx, fy, fw, rw;
+            fx = variants.fImageX;
+            fy = variants.fImageY;
+            fw = variants.fImageW;
+            rw = 1.0f / fw;
+            RIint32 sx0, sy0;
+            fx = RI_CLAMP(fx * rw, 0.0f, uniforms.image_fWidth - 1.0f); // \todo fImageMaxX
+            fy = RI_CLAMP(fy * rw, 0.0f, uniforms.image_fHeight - 1.0f);
+            sx0 = RI_ROUND_TO_INT(fx * (1<<PixelPipe::SAMPLE_BITS));
+            sy0 = RI_ROUND_TO_INT(fy * (1<<PixelPipe::SAMPLE_BITS)); 
+
+            imageColor = intSampleImage(
+                uniforms.imagePtr,
+                uniforms.imageStride,
+                uniforms.image_iWidth,
+                uniforms.image_iHeight,
+                imageDesc,
+                sx0, sy0, signatureState.imageSampler, PixelPipe::TILING_MODE_PAD, NULL);
+
+            variants.fImageX += uniforms.image_fdxdx;
+            variants.fImageY += uniforms.image_fdydx;
+            variants.fImageW += uniforms.image_fdwdx;
+            break;
+        }
+        }
+
+        if (!imageDesc.hasAlpha())
+            imageColor.a = 255;
+        
+        if (PixelPipe::isImageOnly(signatureState))
+        {
+            RI_ASSERT(signatureState.imageMode == VG_DRAW_IMAGE_NORMAL);
+            out = maybeColorTransform(signatureState, imageColor, uniforms.colorTransformValues, imageDesc.isNonlinear());
+
+            const bool tmpPre = imagePremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform;
+            const bool outLuminance = !signatureState.hasColorTransform && imageDesc.isLuminance();
+
+            // Color-format conversion to dst before blending.
+            if (outLuminance != dstDesc.isLuminance())
+            {
+                if (outLuminance)
+                    out.fullLuminanceToRGB(tmpPre, imageDesc.isNonlinear(), tmpPre, imageDesc.isNonlinear());
+                else
+                    out.fullRGBToLuminance(tmpPre, imageDesc.isNonlinear(), tmpPre, imageDesc.isNonlinear());
+            }
+            maybeGammaConvert(imageDesc, dstDesc, out, tmpPre);
+
+            //if (!signatureState.hasColorTransform)
+                //out.premultiply();
+        }
+        else
+        {
+            RI_ASSERT(signatureState.imageMode != VG_DRAW_IMAGE_NORMAL);
+
+            if (!imagePremultipliedAfterSampling(signatureState))
+                imageColor.premultiply();
+
+            if (signatureState.imageMode == VG_DRAW_IMAGE_MULTIPLY)
+            {
+                if (signatureState.paintType == VG_PAINT_TYPE_PATTERN && 
+                    !patternPremultipliedAfterSampling(signatureState))
+                {
+                    out.premultiply();
+                }
+
+                out.r = cMul(out.r, imageColor.r);
+                out.g = cMul(out.g, imageColor.g);
+                out.b = cMul(out.b, imageColor.b);
+                out.a = cMul(out.a, imageColor.a);
+
+                out = maybeColorTransform(signatureState, out, uniforms.colorTransformValues, imageDesc.isNonlinear());
+                //const bool outLuminance = !signatureState.hasColorTransform && imageDesc.isLuminance();
+                // Color transform will always result in RGB, regardless of input.
+                const bool outLuminance = (imageDesc.isLuminance() && !paintInRGB(signatureState)) && !signatureState.hasColorTransform;
+                if (!outLuminance && dstDesc.isLuminance())
+                {
+                    // Convert to destination (luminance)
+                    out.fullRGBToLuminance(!signatureState.hasColorTransform, imageDesc.isNonlinear(), true, dstDesc.isNonlinear());
+                }
+                else if (imageDesc.isNonlinear() != dstDesc.isNonlinear())
+                {
+                    // Non-luminance gamma
+                    if (!signatureState.hasColorTransform)
+                        out.unpremultiply();
+
+                    if (dstDesc.isNonlinear())
+                        out.linearToGamma();
+                    else
+                        out.gammaToLinear();
+
+                    out.premultiply();
+                }
+                else if (signatureState.hasColorTransform)
+                    out.premultiply();
+
+                // Output dst and premultiplied.
+            } 
+            else
+            {
+                RI_ASSERT(signatureState.imageMode == VG_DRAW_IMAGE_STENCIL);
+                IntegerColor alphas, pr;
+                
+                if (signatureState.paintType == VG_PAINT_TYPE_PATTERN)
+                {
+                    out = maybeColorTransform(signatureState, out, uniforms.colorTransformValues, patternDesc.isNonlinear());
+                    const bool isLuminance = patternDesc.isLuminance() && !signatureState.hasColorTransform;
+                    // If using pattern, convert to destination color-space
+                    // \todo If not, handle this when the lookups are generated.
+                    if (isLuminance != dstDesc.isLuminance())
+                    {
+                        out.fullRGBToLuminance(patternPremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform, patternDesc.isNonlinear(), true, dstDesc.isNonlinear());
+                    }
+                    else if (patternDesc.isNonlinear() != dstDesc.isNonlinear())
+                    {
+                        if (patternPremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform)
+                            out.unpremultiply();
+
+                        if (dstDesc.isNonlinear())
+                            out.linearToGamma();
+                        else
+                            out.gammaToLinear();
+
+                        out.premultiply();
+                    } else if (signatureState.hasColorTransform || !patternPremultipliedAfterSampling(signatureState))
+                        out.premultiply();
+                }
+
+                if (dstDesc.isLuminance() && !imageDesc.isLuminance())
+                {
+                    // Convert image to luminance
+                    imageColor.rgbToLuminance();
+                    imageColor.r = imageColor.b = imageColor.b = RI_INT_MIN(imageColor.r, imageColor.a);
+                }
+
+#if defined(RI_DEBUG) && 0
+                printf("stencil r: %d, g: %d, b: %d, a: %d\n",imageColor.r,imageColor.g,imageColor.b,imageColor.a);
+                printf("input r: %d, g: %d, b: %d, a: %d\n",out.r,out.g,out.b,out.a);
+#endif
+                if (signatureState.paintType == VG_PAINT_TYPE_COLOR)
+                {
+                    // Better precision for solid color input.
+                    // Compute alpha channels
+                    alphas.r = rMul(out.a, imageColor.r);
+                    alphas.g = rMul(out.a, imageColor.g);
+                    alphas.b = rMul(out.a, imageColor.b);
+                    // Premultiply
+                    pr.r = rMul(out.r, imageColor.r);
+                    pr.g = rMul(out.g, imageColor.g);
+                    pr.b = rMul(out.b, imageColor.b);
+                    pr.a = rMul(out.a, imageColor.a);
+                }
+                else
+                {
+                    // Compute alpha channels
+                    alphas.r = cMul(out.a, imageColor.r);
+                    alphas.g = cMul(out.a, imageColor.g);
+                    alphas.b = cMul(out.a, imageColor.b);
+                    // Premultiply
+                    pr.r = cMul(out.r, imageColor.r);
+                    pr.g = cMul(out.g, imageColor.g);
+                    pr.b = cMul(out.b, imageColor.b);
+                    pr.a = cMul(out.a, imageColor.a);
+                }
+#if defined(RI_DEBUG) && 0
+                printf("alphas r: %d, g: %d, b: %d, a: %d\n",alphas.r,alphas.g,alphas.b,alphas.a);
+                printf("pr r: %d, g: %d, b: %d, a: %d\n",pr.r,pr.g,pr.b,pr.a);
+#endif
+                out = pr;
+                imageColor = alphas;
+            }
+        }
+    }
+
+    if (signatureState.hasMasking)
+    {
+        // \todo Read and process only the proper component of the mask pixel.
+        const int maskBpp = signatureState.maskDesc.bitsPerPixel;
+
+        RIuint32 packedMaskColor = Image::readPackedPixelFromAddress(variants.maskPtr, maskBpp, variants.dstX);
+        IntegerColor maskColor;
+        maskColor.fromPackedMask(packedMaskColor, signatureState.maskDesc);
+        maskColor.expandMask(signatureState.maskDesc);
+
+        RIuint32 maskCoverage = maskColor.a + (maskColor.a >> 7);
+        coverage = (coverage * maskCoverage) >> 8;
+
+        variants.maskPtr = (void*)Image::incrementPointer(variants.maskPtr, maskBpp, variants.dstX);  
+    }
+    
+#if defined(RI_DEBUG)
+    IntegerColor preblend = out;
+#endif
+    // \todo Coverage check for pixelpipes != solid color with solid output colors?
+
+    IntegerColor d(0,0,0,0);
+
+    // All operations that depend on DST are done next. Keep it organized like that.
+    if ((coverage < ppMaxCoverage) || (out.a < 255) || alwaysLoadDst(signatureState))
+    {
+        d = IntegerColor(Image::readPackedPixelFromAddress(
+            variants.dst, dstDesc.bitsPerPixel, variants.dstX), dstDesc);
+        d.expandColor(dstDesc);
+
+        if (!dstDesc.isPremultiplied())
+        {
+            d.premultiply();
+        }
+
+        // Premultiply output
+#if 0
+        if (!PixelPipe::isImageOnly(signatureState))
+        {
+            if (signatureState.paintType == VG_PAINT_TYPE_PATTERN && !patternPremultipliedAfterSampling(signatureState))
+                out.premultiply();
+            else if (signatureState.hasImage && !imagePremultipliedAfterSampling(signatureState))
+                out.premultiply();
+        }
+#endif
+
+        if (!signatureState.isRenderToMask)
+        {
+            VGBlendMode bm = signatureState.blendMode;
+
+            // Currently SRC requires premultiplication even when only applying coverage.
+            //if (bm != VG_BLEND_SRC)
+            {
+                // If the src color has not been premultiplied before, now's the time.
+                // \todo Fast path for src alpha == 255 and SRC_OVER? Others?
+                if (preBlendPremultiplication(signatureState))
+                    out.premultiply();
+            }
+
+            if (signatureState.hasImage && signatureState.imageMode == VG_DRAW_IMAGE_STENCIL)
+            {
+                out = blendIntegerStencil(out, imageColor, d, bm);
+            } 
+            else
+            {
+                switch(bm)
+                {
+                case VG_BLEND_SRC_OVER:
+                    out = srcOverCoverage(out, d, coverage);
+                    break;
+                case VG_BLEND_SRC:
+                    out = srcCoverage(out, d, coverage);
+                    break;
+                default:
+                    out = blendIntegerColors(out, d, bm);
+                    out = srcCoverage(out, d, coverage);
+                    break;
+                }
+            }
+
+#if defined(RI_DEBUG)
+            if (dstDesc.isPremultiplied())
+            {
+                RI_ASSERT(out.r <= out.a);
+                RI_ASSERT(out.g <= out.a);
+                RI_ASSERT(out.b <= out.a);
+            }
+#endif
+
+        }
+        else
+        {
+            // Mask operation
+            out = intMaskOperation(coverage, d, signatureState.maskOperation);
+        }
+
+        // out is always premultiplied at this point. Must be in destination color-space
+        if (!dstDesc.isPremultiplied())
+        { 
+            // Unpremultiply if output is not premultiplied
+            out.unpremultiply();
+        }
+    }
+    else
+    {
+        // Unpremultiply, ...
+        if (!dstDesc.isPremultiplied())
+            out.unpremultiply();
+    }
+
+    // VG_SET_MASK does not require dst load:
+    if (signatureState.isRenderToMask && signatureState.maskOperation == VG_SET_MASK)
+        out = intMaskOperation(coverage, d, VG_SET_MASK);
+
+    out.truncateColor(dstDesc);
+    Image::writePackedPixelToAddress(
+        variants.dst, dstDesc.bitsPerPixel, variants.dstX, out.getPackedColor(dstDesc));
+
+    // \todo X for bpp < 8
+    variants.dst = (void*)Image::incrementPointer(variants.dst, dstDesc.bitsPerPixel, variants.dstX);
+    //variants.dst = colorBuffer->advancePointer(variants.dst);
+    variants.dstX++;
+}
+
+RI_INLINE static void fillSolidSpan(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, int startX, int y, int nPixels, RIuint32 packedColor) 
+{
+    Image::fillPackedPixels((void*)uniforms.dstPtr, state.dstDesc.bitsPerPixel, startX, y, uniforms.dstStride, nPixels, packedColor);
+}
+
+/**
+ * \brief   This will calculate all the pixel-pipeline variants that need to be updated per-pixel.
+ * \note    There may be a need for a different, faster function for image rendering, where
+ *          there are faster methods of updating the variants.
+ */
+RI_INLINE static void prepareSpanVariants(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, const Span& span, PixelPipe::PPVariants& variants)
+{
+    //variants.dst = uniforms.dst->calculateAddress(span.x0, span.y);
+    variants.dst = Image::calculateAddress(uniforms.dstPtr, state.dstDesc.bitsPerPixel, span.x0, span.y, uniforms.dstStride);
+    variants.dstX = span.x0;
+    variants.coverage = span.coverage;
+
+    if (state.paintType != VG_PAINT_TYPE_COLOR)
+    {
+        if (state.paintType == VG_PAINT_TYPE_LINEAR_GRADIENT)
+        {
+            // \todo Adjust pixel-center.
+            int x = uniforms.dgdx * span.x0 + uniforms.dgdy * span.y + uniforms.lgc;
+            variants.sx = x;
+        } 
+        else if (state.paintType == VG_PAINT_TYPE_RADIAL_GRADIENT)
+        {
+            RGScalar x = uniforms.rdxdx * (RGScalar)span.x0 + uniforms.rdxdy * (RGScalar)span.y;
+            RGScalar y = uniforms.rdydy * (RGScalar)span.y + uniforms.rdydx * (RGScalar)span.x0;
+
+            variants.rx = x + uniforms.rx0;
+            variants.ry = y + uniforms.ry0;
+        }
+        else
+        {
+            RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN);
+            variants.sx = uniforms.paint_dxdx * span.x0 + uniforms.paint_dxdy * span.y + uniforms.paint_x0;
+            variants.sy = uniforms.paint_dydy * span.y + uniforms.paint_dydx * span.x0 + uniforms.paint_y0;
+        }
+    }
+
+    if (state.hasMasking)
+    {
+        variants.maskPtr = Image::calculateAddress(uniforms.maskPtr, state.maskDesc.bitsPerPixel, span.x0, span.y, uniforms.maskStride);
+    }
+
+    if (state.hasImage)
+    {
+        switch (state.imageGradientType)
+        {
+        case PixelPipe::GRADIENT_TYPE_INTEGER:
+        case PixelPipe::GRADIENT_TYPE_FIXED:
+            variants.iImageX = uniforms.image_ix0 + span.x0 * uniforms.image_idxdx + span.y * uniforms.image_idxdy;
+            variants.iImageY = uniforms.image_iy0 + span.y * uniforms.image_idydy + span.x0 * uniforms.image_idydx;
+            break;
+        default:
+            RI_ASSERT(state.imageGradientType == PixelPipe::GRADIENT_TYPE_FLOAT);
+            variants.fImageX = uniforms.image_fx0 + span.x0 * uniforms.image_fdxdx + span.y * uniforms.image_fdxdy;
+            variants.fImageY = uniforms.image_fy0 + span.y * uniforms.image_fdydy + span.x0 * uniforms.image_fdydx;
+            variants.fImageW = uniforms.image_fw0 + span.x0 * uniforms.image_fdwdx + span.y * uniforms.image_fdwdy;
+            break;
+        }
+    }
+}
+
+void executePixelPipeline(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans)
+{
+    RI_ASSERT(nSpans > 0);
+    for (int i = 0; i < nSpans; i++)
+    {
+        const Span& s = spans[i]; 
+
+        if (s.coverage != Rasterizer::MAX_COVERAGE || !canSolidFill(state))
+        {
+            int n = s.len;
+            RI_ASSERT(n);
+            prepareSpanVariants(state, uniforms, s, variants);
+
+            do {
+                intPixelPipe(state, uniforms, variants);
+            } while (--n);
+        } else
+        {
+            fillSolidSpan(state, uniforms, s.x0, s.y, s.len, uniforms.packedSolidColor);
+        }
+    }
+    
+}
+
+void calculatePPHash(PixelPipeHash& hash, const PixelPipe::SignatureState& derivedState)
+{
+    const RIuint32 blendModeBits = 4;
+    const RIuint32 imageModeBits = 2;
+    const RIuint32 paintTypeBits = 2;
+    const RIuint32 tilingModeBits = 2;
+    const RIuint32 samplerBits = 1;
+    const RIuint32 imageGradientTypeBits = 2;
+    const RIuint32 boolBits = 1;
+    const RIuint32 descBits = 10;
+    const RIuint32 maskOperationBits = 3;
+
+    RIuint32 blendMode = ((RIuint32)derivedState.blendMode) - ((RIuint32)VG_BLEND_SRC);
+    RIuint32 imageMode = ((RIuint32)derivedState.imageMode) - ((RIuint32)VG_DRAW_IMAGE_NORMAL);
+    RIuint32 paintType = ((RIuint32)derivedState.paintType) - ((RIuint32)VG_PAINT_TYPE_COLOR);
+    RIuint32 maskOperation = ((RIuint32)derivedState.maskOperation) - ((RIuint32)VG_CLEAR_MASK);
+    RIuint32 paintTilingMode = ((RIuint32)derivedState.paintTilingMode);
+    RIuint32 paintSampler = ((RIuint32)derivedState.paintSampler);
+    RIuint32 imageSampler = ((RIuint32)derivedState.imageSampler);
+
+    RIuint32 imageGradientType = ((RIuint32)derivedState.imageGradientType);
+
+    RIuint32 dstFormat = (RIuint32)(derivedState.dstDesc.toIndex());
+    RIuint32 maskFormat = (RIuint32)(derivedState.maskDesc.toIndex());
+    RIuint32 imageFormat = (RIuint32)(derivedState.imageDesc.toIndex());
+    RIuint32 patternFormat = (RIuint32)(derivedState.patternDesc.toIndex());
+
+    RIuint32 hasMasking = derivedState.hasMasking ? 1 : 0;
+    RIuint32 hasImage = derivedState.hasImage ? 1 : 0;
+    RIuint32 hasColorTransform = derivedState.hasColorTransform ? 1 : 0;
+    RIuint32 isMaskOperation = derivedState.isRenderToMask ? 1 : 0;
+    RIuint32 fillColorTransparent = derivedState.fillColorTransparent ? 1 : 0;
+    RIuint32 unsafeImageInput = derivedState.unsafeImageInput ? 1 : 0;
+
+    // Modify hashes according to relevant state:
+    int b = 0;
+    b = riInsertBits32(hash.value, sizeof(hash.value), blendMode, blendModeBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), imageMode, imageModeBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), paintType, paintTypeBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), maskOperation, maskOperationBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), paintTilingMode, tilingModeBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), paintSampler, samplerBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), imageSampler, samplerBits, b);
+
+    b = riInsertBits32(hash.value, sizeof(hash.value), imageGradientType, imageGradientTypeBits, b);
+
+    b = riInsertBits32(hash.value, sizeof(hash.value), dstFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), maskFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), imageFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), patternFormat, descBits, b);
+
+    b = riInsertBits32(hash.value, sizeof(hash.value), hasMasking, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), hasImage, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), hasColorTransform, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), isMaskOperation, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), fillColorTransparent, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), unsafeImageInput, boolBits, b);
+}
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfDynamicPixelPipe.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,50 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFDYNAMICPIXELPIPE_H
+#define __SFDYNAMICPIXELPIPE_H
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+
+namespace OpenVGRI {
+
+
+struct PixelPipeHash 
+{
+    PixelPipeHash() {value[0] = 0; value[1] = 0;}
+    bool operator==(const PixelPipeHash& rhs) const { return value[0] == rhs.value[0] && value[1] == rhs.value[1]; }
+
+    RIuint32 value[2];
+}; 
+// Interface to compiler?
+void pixelPipelineCall(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans);
+// Interface to rasterizer
+void executePixelPipeline(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans);
+
+void calculatePPHash(PixelPipeHash& hash, const PixelPipe::SignatureState& state);
+
+}
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfEGLInterface.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,470 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#include "SurfaceDescriptor.h"
+#include "BufferContainer.h"
+
+#include "sfEGLInterface.h"
+#include "riContext.h"
+#include "riPath.h"
+#include "vgext.h"
+#include "riImage.h"
+
+namespace 
+    {
+    EGLtoVGInterface g_EGLtoVGInterface;
+    }
+
+IEGLtoVGInterface* getVGInterface(void)
+{    
+    return &g_EGLtoVGInterface;
+}
+
+EGLtoVGInterface::EGLtoVGInterface() :
+    m_egl(NULL)
+{
+    m_contexts.reserve(4);
+}
+
+EGLtoVGInterface::~EGLtoVGInterface()
+{
+    for(int i = 0; i < m_contexts.size(); i++)
+    {
+        RI_ASSERT(m_contexts[i]);
+        RI_DELETE(m_contexts[i]);
+    }
+}
+
+void EGLtoVGInterface::SetEGLInterface( IVGtoEGLInterface* egl )
+{
+    RI_ASSERT(!m_egl);
+    m_egl = egl;
+}
+
+int EGLtoVGInterface::findContext(OpenVGRI::VGContext* contextPtr)
+{
+    return m_contexts.findIndex(contextPtr);
+}
+
+bool EGLtoVGInterface::isValidImage(void* image)
+    {
+    bool ret = false;
+    for(int i = 0; i < m_contexts.size() && !ret; i++)
+        {
+        ret = m_contexts[i]->isValidImage((VGImage)image);
+        }
+    return ret;
+    }
+
+void* EGLtoVGInterface::CreateContext( void* shareContext )
+{
+    if (shareContext)
+    {
+        if (findContext((OpenVGRI::VGContext*)shareContext) < 0)
+            return NULL;
+    }
+
+    OpenVGRI::VGContext* newContext = NULL;
+
+    try 
+    {
+        newContext = RI_NEW(OpenVGRI::VGContext, ((OpenVGRI::VGContext*)shareContext));
+        m_contexts.push_back(newContext);
+    } 
+    catch (std::bad_alloc)
+    {
+        if (newContext) 
+            delete newContext;
+
+        newContext = NULL;
+    }
+
+    return newContext;
+}
+
+bool EGLtoVGInterface::ReleaseContext( void* context )
+{
+    int contextIndex = findContext((OpenVGRI::VGContext*)context);
+
+    if (contextIndex < 0)
+        return false;
+
+    OpenVGRI::VGContext* ctx = (OpenVGRI::VGContext*)context;
+    if( !m_contexts.remove(ctx) )
+        return false;
+    
+    RI_DELETE(ctx);
+
+    return true;
+}
+
+OpenVGRI::Color::Descriptor EGLtoVGInterface::vgDescriptorFromSurfaceDescriptor(const SurfaceDescriptor* sdesc)
+{
+    const CColorDescriptor& scdesc = sdesc->m_colorDescriptor;
+    OpenVGRI::Color::Descriptor vdesc;
+    unsigned int formatBits = 0;
+
+    // VG formats are built favoring the first ones in the enum (RGBA, RGBX, etc.)
+
+    // Padded alpha (RGBX, etc.) must be handled. For example:
+    // if (vdesc.bitsPerPixel < sdesc.bitsPerPixel)
+    //      alphabits = 0, alphashift = 8
+    vdesc.bitsPerPixel = scdesc.m_bpp;
+    vdesc.bytesPerPixel = vdesc.bitsPerPixel >> 3;
+
+    vdesc.alphaBits = scdesc.m_alphaSize;
+    vdesc.alphaShift = sdesc->m_alphaShift;
+    vdesc.redBits = scdesc.m_redSize;
+    vdesc.redShift = sdesc->m_redShift;
+    vdesc.greenBits = scdesc.m_greenSize;
+    vdesc.greenShift = sdesc->m_greenShift;
+    vdesc.blueBits = scdesc.m_blueSize;
+    vdesc.blueShift = sdesc->m_blueShift;
+    vdesc.luminanceBits = scdesc.m_luminanceSize;
+    vdesc.luminanceShift = sdesc->m_luminanceShift;
+    
+    if(scdesc.isLuminance())
+        formatBits |= OpenVGRI::Color::LUMINANCE;    
+    
+    // \note Could be copied if LUMINANCE == LUMINANCE, etc.
+    if (scdesc.isPremultiplied())
+        formatBits |= OpenVGRI::Color::PREMULTIPLIED;
+
+    if (scdesc.isNonlinear())
+        formatBits |= OpenVGRI::Color::NONLINEAR;
+
+    vdesc.internalFormat = (OpenVGRI::Color::InternalFormat)formatBits;
+    // \todo format
+    vdesc.vgFormat = (VGImageFormat)-1; // Not necessarily any VG image format
+    vdesc.shape = vdesc.getShape();
+
+    return vdesc;
+}
+
+bool EGLtoVGInterface::CreateSurface(const SurfaceDescriptor* desc, BufferContainer* buffers, void* image)
+{
+    RI_ASSERT( buffers );
+    OpenVGRI::Color::Descriptor vgColorDescriptor; 
+    OpenVGRI::Image* newImage = NULL;
+    if(image)
+        {
+        if(!isValidImage(image))
+            return false;
+        newImage = (OpenVGRI::Image*)image;
+        vgColorDescriptor = newImage->getDescriptor();
+        }
+    else
+        {
+        vgColorDescriptor = vgDescriptorFromSurfaceDescriptor(desc);
+        }
+    OpenVGRI::Drawable* newDrawable = NULL;
+    
+    //VGImageQuality quality = VG_IMAGE_QUALITY_BETTER;
+
+    int w = desc->m_width;
+    int h = desc->m_height;
+    int stride = OpenVGRI::Image::descriptorToStride(vgColorDescriptor, w);
+    size_t bufSize = h * stride;
+
+    OpenVGRI::RIuint8* dataPtr = NULL;
+
+    try 
+    {
+        int maskBits = 0;
+        if( !newImage )
+            {
+            newImage = RI_NEW(OpenVGRI::Image,(vgColorDescriptor, w, h, VG_IMAGE_QUALITY_BETTER));
+            maskBits = desc->m_maskSize;
+            }
+        else
+            {
+            dataPtr = newImage->getData();
+            maskBits = newImage->getDescriptor().maskBits;
+            }
+        newDrawable = RI_NEW(OpenVGRI::Drawable, (newImage, maskBits));
+        newDrawable->addReference();
+    } 
+    catch (std::bad_alloc)
+    {
+        if (dataPtr)        RI_DELETE_ARRAY(dataPtr);
+        if (newImage)       RI_DELETE(newImage);
+        if (newDrawable)    RI_DELETE(newDrawable);
+
+        return false;
+    }
+    buffers->m_clientSurface = newDrawable;
+    buffers->m_colorBuffer = newDrawable->getColorBuffer()->getImage()->getData();
+    buffers->m_maskBuffer = newDrawable->getMaskBuffer();
+    return true;
+}
+
+bool EGLtoVGInterface::ReleaseSurface(void* surface)
+{
+    RI_ASSERT(surface);
+
+    OpenVGRI::Drawable *drawable = (OpenVGRI::Drawable*)surface;
+
+    if (!drawable->removeReference())
+        RI_DELETE(drawable);
+    
+	return true;
+}
+
+bool EGLtoVGInterface::SetCurrentSurface( void* context, void* surface )
+{
+    OpenVGRI::Drawable* drawable = (OpenVGRI::Drawable*)surface;
+    OpenVGRI::VGContext *ctx = (OpenVGRI::VGContext*)context;
+
+    int i = findContext(ctx);
+
+    if (i < 0)
+        return false;
+
+    ctx->setDefaultDrawable(drawable);
+
+    return true;
+}
+
+bool EGLtoVGInterface::ResizeSurface( void* context, void* surface, int width, int height, BufferContainer* buffers )
+    {
+    OpenVGRI::Drawable* drawable = (OpenVGRI::Drawable*)surface;
+    OpenVGRI::VGContext *ctx = (OpenVGRI::VGContext*)context;
+    int i = findContext(ctx);
+    if(i < 0)
+        return false;
+    
+    try 
+    {
+        drawable->resize( ctx, width, height );
+    } 
+    catch (std::bad_alloc) 
+    {
+        return false;
+    }
+    buffers->m_clientSurface = drawable;
+    buffers->m_colorBuffer = drawable->getColorBuffer()->getImage()->getData();
+    buffers->m_maskBuffer = drawable->getMaskBuffer();
+    return true;
+    }
+
+bool EGLtoVGInterface::IsValidImage( void* image, CColorDescriptor* colorDesc, int* width, int* height )
+{
+    bool ret = isValidImage(image);
+    if(ret)
+        {
+        *width = ((OpenVGRI::Image*)image)->getWidth();
+        *height = ((OpenVGRI::Image*)image)->getHeight();
+        const OpenVGRI::Color::Descriptor& desc = ((OpenVGRI::Image*)image)->getDescriptor();
+        colorDesc->m_bpp = desc.bitsPerPixel;
+        colorDesc->m_redSize = desc.redBits;
+        colorDesc->m_greenSize = desc.greenBits;
+        colorDesc->m_blueSize = desc.blueBits;
+        colorDesc->m_alphaSize = desc.alphaBits;
+        colorDesc->m_luminanceSize = desc.luminanceBits;
+        colorDesc->m_alphaMaskSize = desc.maskBits;
+        colorDesc->m_format = (CColorDescriptor::ColorFormat)desc.internalFormat;
+        }
+
+    return ret;
+}
+
+bool EGLtoVGInterface::IsImageInUse( void* image )
+{
+    bool ret = false;
+    if(image && isValidImage(image))
+        {
+        ret = ((OpenVGRI::Image*)image)->isInUse();
+        }
+    return ret;
+}
+
+void* EGLtoVGInterface::CreateImage()
+{
+    RI_ASSERT(false);
+	return NULL;
+}
+
+bool EGLtoVGInterface::ReleaseImage()
+{
+    RI_ASSERT(false);
+	return false;
+}
+
+void EGLtoVGInterface::Flush()
+{
+    vgFlush();
+}
+
+void EGLtoVGInterface::Finish()
+{
+    vgFinish();
+}
+
+fpVGProc EGLtoVGInterface::GetVGProcAddress( const char *procname )
+{
+    fpVGProc ret = NULL;
+    if(strcmp(procname, "vgePathCoordsSizeInBytes") == 0)
+        {
+        ret = (fpVGProc)vgePathCoordsSizeInBytes;
+        }
+    return ret;
+}
+
+void EGLtoVGInterface::CopyBuffers( void* buffer, int stride, void* surface )
+    {
+    OpenVGRI::Drawable *drawable = (OpenVGRI::Drawable*)surface;
+    int width = drawable->getColorBuffer()->getWidth();
+    int height = drawable->getColorBuffer()->getHeight();
+	// \todo Pixel format.
+    VGImageFormat format = VG_sARGB_8888_PRE;
+    vgReadPixels( buffer, stride, format, 0, 0, width, height );
+    }
+
+void EGLtoVGInterface::UpdateBuffers( void* buffer, int stride, const SurfaceDescriptor* desc )
+    {
+    // \todo format, errors
+    VGImageFormat format = VG_sARGB_8888_PRE;
+    vgWritePixels( buffer, stride, format, 0, 0, desc->m_width, desc->m_height );
+    }
+
+bool EGLtoVGInterface::IsRootImage( void* image )
+    {
+    if( !image ) return false;    
+    if ( vgGetParent( (VGImage)image ) )
+        {
+        // if vgGetParent returns not NULL image it is not parent image
+        // , only child image has parent image, and this should return false
+        return false;
+        }
+    // vgGetParent is NULL and image is parent image
+    return true;
+    }                                                    
+
+void EGLtoVGInterface::GetImageData( void* image, SurfaceDescriptor& desc, void* data )
+    {
+    OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image;
+    if( !image )
+        {
+        return;
+        }
+    desc.m_height = vgimage->getHeight();
+    desc.m_width  = vgimage->getWidth();
+    int bufSize;
+    
+    OpenVGRI::Color::Descriptor colorDesc   = vgimage->getDescriptor();
+	VGImageFormat vgFormat;
+	// Convert some formats into more GL-friendly formats.
+	if( colorDesc.vgFormat == VG_BW_1 )
+		{
+		vgFormat = VG_lL_8;
+		}
+	else if( colorDesc.vgFormat == VG_A_1 || colorDesc.vgFormat == VG_A_4 )
+		{
+		vgFormat = VG_A_8;
+		}
+	else
+		{
+		vgFormat = colorDesc.vgFormat;
+		}
+    desc.m_colorDescriptor.m_format = (CColorDescriptor::ColorFormat)colorDesc.internalFormat;
+    desc.m_alphaShift     = colorDesc.alphaShift;
+    desc.m_blueShift      = colorDesc.blueShift;
+    desc.m_greenShift     = colorDesc.greenShift;
+    desc.m_redShift       = colorDesc.redShift;
+    desc.m_luminanceShift = colorDesc.luminanceShift;
+    desc.m_stride         = vgimage->getStride();
+
+    bufSize = (desc.m_stride * desc.m_height);
+    // Allocate data from memory.
+    data = RI_NEW_ARRAY(OpenVGRI::RIuint8, bufSize);
+    // Get data from VG
+    vgGetImageSubData( (VGImage)vgimage, data, vgimage->getStride(), vgFormat, 0, 0, vgimage->getWidth(), vgimage->getWidth() );
+
+    }
+
+void EGLtoVGInterface::AddRef( void* image )
+    {
+    OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image;
+    if( !image )
+        {
+        return;
+        }
+    vgimage->addReference();
+    }
+
+void EGLtoVGInterface::RemoveRef( void* image )
+    {
+    OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image;
+    if( !image )
+        {
+        return;
+        }
+    vgimage->removeReference();
+    }
+
+/*static*/ IVGtoEGLInterface* EGLtoVGInterface::GetEGLInterface()
+{
+    return g_EGLtoVGInterface.m_egl;
+}
+
+void* OpenVGRI::eglvgGetCurrentVGContext(void)
+{
+    return EGLtoVGInterface::GetEGLInterface()->GetVGContext();
+}
+
+bool OpenVGRI::eglvgIsInUse(void* image)
+{
+    return EGLtoVGInterface::GetEGLInterface()->IsImageInUse(image);
+}
+
+bool OpenVGRI::eglvgLockSurface(bool read, bool write)
+{
+	return EGLtoVGInterface::GetEGLInterface()->LockVGSurface(read, write);
+}
+
+bool OpenVGRI::eglvgUnlockSurface()
+{
+	return EGLtoVGInterface::GetEGLInterface()->UnlockVGSurface();
+}
+
+void OpenVGRI::OSAcquireMutex(void)
+{
+}
+
+void OpenVGRI::OSReleaseMutex(void) 
+{
+}
+
+void OpenVGRI::eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride )
+    {
+    SurfaceDescriptor surfDesc;
+    EGLtoVGInterface::GetEGLInterface()->GetDescForImage( image, surfDesc );
+    desc = EGLtoVGInterface::vgDescriptorFromSurfaceDescriptor( &surfDesc );
+    width = surfDesc.m_width;
+    height = surfDesc.m_height;
+    stride = surfDesc.m_stride;
+    }
+
+void* OpenVGRI::eglvgGetImageData( void* image )
+    {
+    return EGLtoVGInterface::GetEGLInterface()->GetDataForImage( image );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfEGLInterface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,89 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef _SFEGLINTERFACE_H_
+#define _SFEGLINTERFACE_H_
+
+#include "riImage.h"
+#include "VGInterface.h"
+
+
+// Get pointer to global interface object.
+extern "C" { RI_API_CALL IEGLtoVGInterface* getVGInterface(void); }
+extern "C" { RI_API_CALL VGErrorCode vgPlatsimGetError(void); }
+
+namespace OpenVGRI 
+{
+    void* eglvgGetCurrentVGContext(void);
+    bool  eglvgIsInUse(void* image);
+	bool  eglvgLockSurface(bool read, bool write);
+    bool  eglvgUnlockSurface();
+	void  OSAcquireMutex(void);
+	void  OSReleaseMutex(void);
+    void  eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride );
+    void* eglvgGetImageData( void* image );
+}
+
+// Services from OpenVG to EGL
+class EGLtoVGInterface : public IEGLtoVGInterface
+{
+public:
+    EGLtoVGInterface();
+    ~EGLtoVGInterface();
+
+    void    SetEGLInterface( IVGtoEGLInterface* egl );
+    void*   CreateContext( void* shareContext );
+    bool    ReleaseContext( void* context );
+    bool    CreateSurface( const SurfaceDescriptor* desc, BufferContainer* buffers, void* image );
+    bool    ReleaseSurface(void* surface);
+    bool    SetCurrentSurface( void* context, void* surface );
+    bool    ResizeSurface( void* context, void* surface, int width, int height, BufferContainer* buffers );
+    bool    IsValidImage( void* image, CColorDescriptor* colorDesc, int* width, int* height );
+    bool    IsImageInUse( void* image );
+    void*   CreateImage();
+    bool    ReleaseImage();
+    void    Flush();
+    void    Finish();
+    fpVGProc GetVGProcAddress( const char *procname );
+    void    CopyBuffers( void* buffer, int stride, void* surface );
+    void    UpdateBuffers( void* buffer, int stride, const SurfaceDescriptor* desc );
+    bool    IsRootImage( void* buffer );
+    void    GetImageData( void* image, SurfaceDescriptor& desc, void* data );
+    void    AddRef( void* image );
+    void    RemoveRef( void* image );
+
+    // Methods for local OpenVG-implementation. To be called only from OpenVG internals.
+    static IVGtoEGLInterface* GetEGLInterface();
+    static OpenVGRI::Color::Descriptor vgDescriptorFromSurfaceDescriptor(const SurfaceDescriptor* sdesc); // \todo static
+    
+private:    
+    int     findContext(OpenVGRI::VGContext* contextPtr);
+    bool    isValidImage(void* image);
+
+private:
+    OpenVGRI::Array<OpenVGRI::VGContext*>   m_contexts;
+    IVGtoEGLInterface*                      m_egl;
+
+};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfFunctionCache.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,310 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFFUNCTIONCACHE_H
+#define __SFFUNCTIONCACHE_H
+
+// (LRU) Cache for compiled pixelpipe functions. Never takes ownership of
+// any of the objects.
+// \todo LRU might not be the best strategy or the best strategy might
+// depend on the use-case -> create more of these.
+
+#include "riArray.h"
+
+#if defined(__unix__)
+#   include <pthread.h>
+#else
+#   include <windows.h>
+#endif
+
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/Module.h"
+
+namespace llvm {
+    class Function;
+}
+
+namespace OpenVGRI {
+
+template<class HashClass> class FunctionCache 
+{
+private:
+    enum { IMPLEMENTATION_MAX_CACHE_ENTRIES = 1024 };
+    //enum { MAX_GLOBAL_TIME = 10000};
+    enum { MAX_GLOBAL_TIME = RI_UINT32_MAX };
+
+    struct CacheEntry 
+    {
+        CacheEntry() : refCount(1) {}
+        CacheEntry(HashClass aHash, ::llvm::Function* aFunc, ::llvm::GlobalVariable* aConst, RIuint32 theUT) : refCount(1) {hash = aHash; llvmFunction = aFunc; llvmConstant = aConst; ut = theUT;}
+        bool operator==(const CacheEntry& rhs) const { return hash == rhs.hash; }
+        bool operator<(const CacheEntry& rhs) const { return ut < rhs.ut; } // Sort by time of usage.
+
+        HashClass           hash;
+        ::llvm::Function*   llvmFunction;
+        ::llvm::GlobalVariable*   llvmConstant;
+        RIuint32            ut;
+        RIint32             refCount;
+    };
+
+public:
+    typedef CacheEntry* EntryHandle;
+
+public:
+    FunctionCache(int nMaxEntries) :
+        m_time(0)
+    {
+        // Limit so that if the cache is too large, you must optimize the implementation.
+        // Also note that the optimized pixel pipes are most likely small, so it would 
+        // be better to have a fast cache and a lot of entries!
+        // \note A simple optimization is to sort the usage time sort order and remove the last
+        // item in the array (instead of the first).
+        RI_ASSERT(nMaxEntries > 0 && nMaxEntries < IMPLEMENTATION_MAX_CACHE_ENTRIES); 
+        m_nMaxEntries = nMaxEntries;
+        m_entries.reserve(nMaxEntries);
+    }
+
+    ~FunctionCache() 
+    {
+        for (int i = 0; i < m_entries.size(); i++)
+        {
+            clearEntry(m_entries[i]);
+        }
+    }
+    
+    // This info is needed for the module to remove functions and deallocate executable
+    // functions:
+    void setLLVMInterface(::llvm::ExecutionEngine* ee, ::llvm::Module* module)
+    {
+        m_executionEngine = ee;
+        m_module = module;
+    }
+
+    // \todo If we never need the entry index, the locking can be
+    // simplified a lot.
+    // Must lock the cache during this operation!
+    EntryHandle findCachedItemByHash(const HashClass& hash)
+    {
+        acquireMutex();
+        int i = findCachedItemIndexByHash(hash, true);
+        if (i == -1)
+        {
+            releaseMutex();
+            return NULL;
+        }
+        EntryHandle handle = &m_entries[i];
+        releaseMutex();
+        
+        return handle;
+    }
+
+    /**
+     * \brief   Caches a function. Sets the reference count to 1
+     * \return  EntryHandle != NULL on success.
+     * \todo    The cache must be locked during the operation.
+     */
+    EntryHandle cacheFunction(HashClass hash, ::llvm::Function* function, ::llvm::GlobalVariable* constant)
+    {
+        acquireMutex();
+        RI_ASSERT(findCachedItemIndexByHash(hash) == -1);
+
+        if (m_entries.size() == m_nMaxEntries)
+        {
+            if (!removeLRU())
+            {
+                releaseMutex();
+                return NULL;
+            }
+        }
+
+        m_entries.push_back(CacheEntry(hash, function, constant, m_time));
+        
+        RI_ASSERT(m_entries.size() > 0);
+        EntryHandle ret = &m_entries[m_entries.size()-1];
+        incrementGlobalTime();
+
+        releaseMutex();
+        return ret;
+    }
+
+    ::llvm::Function* getFunction(EntryHandle handle)
+    {
+        return handle->llvmFunction;
+    }
+
+    // \note Does not remove the function from cache!
+    void releaseEntry(EntryHandle handle)
+    {
+        RI_ASSERT(handle->refCount > 0);
+        handle->refCount--;
+    }
+
+private:
+    void incrementGlobalTime()
+    {
+        m_time++;
+        if (m_time == MAX_GLOBAL_TIME)
+            rebaseUsageTime();
+    }
+
+    void incrementAccessTime(CacheEntry &entry)
+    {
+        entry.ut = m_time;
+        incrementGlobalTime();
+    }
+
+    int findCachedItemIndexByHash(const HashClass& hash, bool reserve = false)
+    {
+        // \note Could just overload operator== from entry and use the Array.find function.
+        for (int i = 0; i < m_entries.size(); i++)
+        {
+            if (m_entries[i].hash == hash)
+            {
+                if (reserve)
+                {
+                    incrementAccessTime(m_entries[i]);
+                    m_entries[i].refCount++;
+                }
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    void clearEntry(CacheEntry& entry)
+    {
+        m_executionEngine->freeMachineCodeForFunction(entry.llvmFunction);
+        entry.llvmFunction->eraseFromParent();
+        //entry.llvmConstant->eraseFromParent();
+    }
+
+    /**
+     * \return  true if LRU item was successfully removed, false otherwise.
+     * \note    Could try other pipes, but it is unlikely that the cache gets filled
+     *          so soon that the blit for the least recently used blit has not been
+     *          released.
+     * \todo    Implement drop of other cache-entries?
+     */
+    bool removeLRU() 
+    {
+        // \note This is pretty inefficient for many cache size:
+        // After first LRU removal, the cache is almost sorted anyway, so
+        // more efficient solution should be implemented.
+        //
+        m_entries.sort();
+
+        if (m_entries[0].refCount > 0)
+            return false;
+
+        clearEntry(m_entries[0]);
+        m_entries.remove(m_entries[0]);
+
+        return true;
+    }
+
+    void rebaseUsageTime()
+    {
+        RIuint32 i;
+        m_entries.sort();
+        RI_ASSERT(m_entries.size() > 0);
+        for(i = 0; i < (RIuint32)m_entries.size(); i++)
+        {
+            m_entries[i].ut = i;
+        };
+        m_time = i;
+    }
+
+    static void acquireMutex();
+    static void releaseMutex();
+
+private:
+    ::llvm::Module              *m_module;
+    ::llvm::ExecutionEngine     *m_executionEngine;
+
+    RIuint32            m_time;
+    Array <CacheEntry>  m_entries;
+    int                 m_nMaxEntries;
+
+    static bool             s_mutexInitialized;
+#if defined(__unix__)
+    static pthread_mutex_t  s_mutex;
+#else
+    static CRITICAL_SECTION s_mutex;
+#endif
+};
+
+template<class HashClass>
+bool FunctionCache<HashClass>::s_mutexInitialized = false;
+
+#if defined(__unix__)
+template<class HashClass>
+pthread_mutex_t FunctionCache<HashClass>::s_mutex;
+#else
+template<class HashClass>
+CRITICAL_SECTION FunctionCache<HashClass>::s_mutex;
+#endif
+
+template<class HashClass>
+void FunctionCache<HashClass>::acquireMutex()
+{
+    if (!s_mutexInitialized)
+    {
+#if defined(__unix__)
+        int ret;
+        pthread_mutexattr_t attr;
+        ret = pthread_mutexattr_init(&attr);	//initially not locked
+        RI_ASSERT(!ret);	//check that there aren't any errors
+        ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);	//count the number of recursive locks
+        RI_ASSERT(!ret);	//check that there aren't any errors
+        ret = pthread_mutex_init(&s_mutex, &attr);
+        pthread_mutexattr_destroy(&attr);
+        RI_ASSERT(!ret);	//check that there aren't more errors
+#else
+        ::InitializeCriticalSection(&s_mutex);
+#endif
+        s_mutexInitialized = true;
+    }
+#if defined(__unix__)
+    int ret = pthread_mutex_lock(&s_mutex);
+    RI_ASSERT(!ret);
+#else
+    ::EnterCriticalSection(&s_mutex);
+#endif
+}
+
+template<class HashClass>
+void FunctionCache<HashClass>::releaseMutex()
+{
+    RI_ASSERT(s_mutexInitialized);
+#if defined(__unix__)
+    int ret = pthread_mutex_unlock(&s_mutex);
+    RI_ASSERT(!ret);
+#else
+    ::LeaveCriticalSection(&s_mutex);
+#endif
+}
+
+}
+
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfGammaLUT.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,100 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef _SFGAMMARCP_H_
+#define _SFGAMMARCP_H_
+
+#include "riDefs.h"
+
+namespace OpenVGRI {
+static const RIuint8 sc_sRGB_to_lRGB[256] = {
+    0x0,  0x0,  0x0,  0x0,  0x0,  0x0,  0x0,  0x1,  
+    0x1,  0x1,  0x1,  0x1,  0x1,  0x1,  0x1,  0x1,  
+    0x1,  0x1,  0x2,  0x2,  0x2,  0x2,  0x2,  0x2,  
+    0x2,  0x2,  0x3,  0x3,  0x3,  0x3,  0x3,  0x4,  
+    0x4,  0x4,  0x4,  0x4,  0x5,  0x5,  0x5,  0x5,  
+    0x5,  0x6,  0x6,  0x6,  0x6,  0x7,  0x7,  0x7,  
+    0x8,  0x8,  0x8,  0x8,  0x9,  0x9,  0x9,  0xa,  
+    0xa,  0xa,  0xb,  0xb,  0xc,  0xc,  0xc,  0xd,  
+    0xd,  0xe,  0xe,  0xe,  0xf,  0xf,  0x10,  0x10,  
+    0x11,  0x11,  0x12,  0x12,  0x12,  0x13,  0x13,  0x14,  
+    0x15,  0x15,  0x16,  0x16,  0x17,  0x17,  0x18,  0x18,  
+    0x19,  0x1a,  0x1a,  0x1b,  0x1b,  0x1c,  0x1d,  0x1d,  
+    0x1e,  0x1f,  0x1f,  0x20,  0x21,  0x21,  0x22,  0x23,  
+    0x23,  0x24,  0x25,  0x26,  0x26,  0x27,  0x28,  0x29,  
+    0x29,  0x2a,  0x2b,  0x2c,  0x2d,  0x2d,  0x2e,  0x2f,  
+    0x30,  0x31,  0x32,  0x33,  0x33,  0x34,  0x35,  0x36,  
+    0x37,  0x38,  0x39,  0x3a,  0x3b,  0x3c,  0x3d,  0x3e,  
+    0x3f,  0x40,  0x41,  0x42,  0x43,  0x44,  0x45,  0x46,  
+    0x47,  0x48,  0x49,  0x4a,  0x4c,  0x4d,  0x4e,  0x4f,  
+    0x50,  0x51,  0x52,  0x54,  0x55,  0x56,  0x57,  0x58,  
+    0x5a,  0x5b,  0x5c,  0x5d,  0x5f,  0x60,  0x61,  0x63,  
+    0x64,  0x65,  0x67,  0x68,  0x69,  0x6b,  0x6c,  0x6d,  
+    0x6f,  0x70,  0x72,  0x73,  0x74,  0x76,  0x77,  0x79,  
+    0x7a,  0x7c,  0x7d,  0x7f,  0x80,  0x82,  0x83,  0x85,  
+    0x86,  0x88,  0x8a,  0x8b,  0x8d,  0x8e,  0x90,  0x92,  
+    0x93,  0x95,  0x97,  0x98,  0x9a,  0x9c,  0x9d,  0x9f,  
+    0xa1,  0xa3,  0xa4,  0xa6,  0xa8,  0xaa,  0xac,  0xad,  
+    0xaf,  0xb1,  0xb3,  0xb5,  0xb7,  0xb8,  0xba,  0xbc,  
+    0xbe,  0xc0,  0xc2,  0xc4,  0xc6,  0xc8,  0xca,  0xcc,  
+    0xce,  0xd0,  0xd2,  0xd4,  0xd6,  0xd8,  0xda,  0xdc,  
+    0xde,  0xe0,  0xe2,  0xe5,  0xe7,  0xe9,  0xeb,  0xed,  
+    0xef,  0xf2,  0xf4,  0xf6,  0xf8,  0xfa,  0xfd,  0xff,  
+};
+
+static const RIuint8 sc_lRGB_to_sRGB[256] = {
+    0x0,  0xd,  0x16,  0x1c,  0x21,  0x26,  0x2a,  0x2e,  
+    0x31,  0x35,  0x38,  0x3a,  0x3d,  0x40,  0x42,  0x44,  
+    0x47,  0x49,  0x4b,  0x4d,  0x4f,  0x51,  0x53,  0x55,  
+    0x56,  0x58,  0x5a,  0x5b,  0x5d,  0x5f,  0x60,  0x62,  
+    0x63,  0x65,  0x66,  0x67,  0x69,  0x6a,  0x6c,  0x6d,  
+    0x6e,  0x70,  0x71,  0x72,  0x73,  0x74,  0x76,  0x77,  
+    0x78,  0x79,  0x7a,  0x7b,  0x7d,  0x7e,  0x7f,  0x80,  
+    0x81,  0x82,  0x83,  0x84,  0x85,  0x86,  0x87,  0x88,  
+    0x89,  0x8a,  0x8b,  0x8c,  0x8d,  0x8e,  0x8f,  0x90,  
+    0x91,  0x92,  0x93,  0x93,  0x94,  0x95,  0x96,  0x97,  
+    0x98,  0x99,  0x9a,  0x9a,  0x9b,  0x9c,  0x9d,  0x9e,  
+    0x9f,  0x9f,  0xa0,  0xa1,  0xa2,  0xa3,  0xa3,  0xa4,  
+    0xa5,  0xa6,  0xa7,  0xa7,  0xa8,  0xa9,  0xaa,  0xaa,  
+    0xab,  0xac,  0xad,  0xad,  0xae,  0xaf,  0xaf,  0xb0,  
+    0xb1,  0xb2,  0xb2,  0xb3,  0xb4,  0xb4,  0xb5,  0xb6,  
+    0xb6,  0xb7,  0xb8,  0xb8,  0xb9,  0xba,  0xba,  0xbb,  
+    0xbc,  0xbc,  0xbd,  0xbe,  0xbe,  0xbf,  0xc0,  0xc0,  
+    0xc1,  0xc2,  0xc2,  0xc3,  0xc3,  0xc4,  0xc5,  0xc5,  
+    0xc6,  0xc7,  0xc7,  0xc8,  0xc8,  0xc9,  0xca,  0xca,  
+    0xcb,  0xcb,  0xcc,  0xcd,  0xcd,  0xce,  0xce,  0xcf,  
+    0xcf,  0xd0,  0xd1,  0xd1,  0xd2,  0xd2,  0xd3,  0xd3,  
+    0xd4,  0xd5,  0xd5,  0xd6,  0xd6,  0xd7,  0xd7,  0xd8,  
+    0xd8,  0xd9,  0xda,  0xda,  0xdb,  0xdb,  0xdc,  0xdc,  
+    0xdd,  0xdd,  0xde,  0xde,  0xdf,  0xdf,  0xe0,  0xe0,  
+    0xe1,  0xe2,  0xe2,  0xe3,  0xe3,  0xe4,  0xe4,  0xe5,  
+    0xe5,  0xe6,  0xe6,  0xe7,  0xe7,  0xe8,  0xe8,  0xe9,  
+    0xe9,  0xea,  0xea,  0xeb,  0xeb,  0xec,  0xec,  0xed,  
+    0xed,  0xed,  0xee,  0xee,  0xef,  0xef,  0xf0,  0xf0,  
+    0xf1,  0xf1,  0xf2,  0xf2,  0xf3,  0xf3,  0xf4,  0xf4,  
+    0xf5,  0xf5,  0xf6,  0xf6,  0xf6,  0xf7,  0xf7,  0xf8,  
+    0xf8,  0xf9,  0xf9,  0xfa,  0xfa,  0xfb,  0xfb,  0xfb,  
+    0xfc,  0xfc,  0xfd,  0xfd,  0xfe,  0xfe,  0xff,  0xff,  
+};
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/sfMask.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,85 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFMASK_H
+#define __SFMASK_H
+
+#include "VG/openvg.h"
+
+#ifndef __RIDEFS_H
+#   include "riDefs.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#   include "riImage.h"
+#endif
+
+// Contains implementations of some mask operations that are needed in both the
+// pixel-pipeline and the blitter.
+
+namespace OpenVGRI {
+
+RI_INLINE IntegerColor intMaskOperation(RIuint32 coverage, const IntegerColor& d, VGMaskOperation maskOperation);
+
+RI_INLINE IntegerColor intMaskOperation(RIuint32 coverage, const IntegerColor& d, VGMaskOperation maskOperation)
+{
+    RIuint32 newCoverage;
+    switch (maskOperation)
+    {
+        case VG_SET_MASK:
+            // \note This should work approximately if coverage < 256 always.
+            // See other cases for proper conversions.
+            return IntegerColor(0, 0, 0, coverage); // nop.
+            break;
+        case VG_UNION_MASK:
+        {
+            RIuint32 oldCoverage = d.a;
+            oldCoverage += (oldCoverage >> 7);
+            RIuint32 im = 256 - coverage;
+            RIuint32 ip = 256 - oldCoverage;
+            newCoverage = 256 - ((im * ip) >> 8);
+            break;
+        }
+        case VG_INTERSECT_MASK:
+        {
+            RIuint32 oldCoverage = d.a;
+            oldCoverage += (oldCoverage >> 7);
+            newCoverage = (coverage * oldCoverage) >> 8;
+            break;
+        }
+        default:
+        {
+            RI_ASSERT(maskOperation == VG_SUBTRACT_MASK);
+            RIuint32 im = 256 - coverage;
+            RIuint32 oldCoverage = d.a;
+            oldCoverage += (oldCoverage >> 7);
+            newCoverage = (oldCoverage * im) >> 8;
+            break;
+        }
+    }
+    return IntegerColor(0, 0, 0, newCoverage - (newCoverage >> 8));
+}
+
+}
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/linux/riEGLOS.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,258 @@
+/*------------------------------------------------------------------------
+ *
+ * EGL 1.3
+ * -------
+ *
+ * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Linux specific EGL functionality, modified from macosx source file
+ * \note
+  *//*-------------------------------------------------------------------*/
+
+#include "riEGLOS.h"
+
+#include <pthread.h>
+#include <sys/errno.h>
+#include <GL/gl.h>
+#include <GL/glut.h>
+
+#if defined(None)
+#   undef None
+#endif
+
+#include "sfCompiler.h"
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void* OSGetCurrentThreadID(void)
+{
+    return (void*)pthread_self();   //TODO this is not safe
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static pthread_mutex_t mutex;
+static int mutexRefCount = 0;
+static bool mutexInitialized = false;
+//acquired mutex cannot be deinited
+void OSDeinitMutex(void)
+{
+    RI_ASSERT(mutexInitialized);
+    RI_ASSERT(mutexRefCount == 0);
+    int ret = pthread_mutex_destroy(&mutex);
+    RI_ASSERT(ret != EINVAL);	//assert that the mutex has been initialized
+    RI_ASSERT(ret != EAGAIN);	//assert that the maximum number of recursive locks hasn't been exceeded
+    RI_ASSERT(!ret);	//check that there aren't other errors
+    RI_UNREF(ret);
+}
+void OSAcquireMutex(void)
+{
+    if(!mutexInitialized)
+    {
+        int ret;
+        pthread_mutexattr_t attr;
+        ret = pthread_mutexattr_init(&attr);	//initially not locked
+        RI_ASSERT(!ret);	//check that there aren't any errors
+        ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);	//count the number of recursive locks
+        RI_ASSERT(!ret);	//check that there aren't any errors
+        ret = pthread_mutex_init(&mutex, &attr);
+        pthread_mutexattr_destroy(&attr);
+        RI_ASSERT(!ret);	//check that there aren't more errors
+        RI_UNREF(ret);
+        mutexInitialized = true;
+    }
+    int ret = pthread_mutex_lock(&mutex);
+    RI_ASSERT(ret != EINVAL);	//assert that the mutex has been initialized
+    RI_ASSERT(ret != EAGAIN);	//assert that the maximum number of recursive locks hasn't been exceeded
+    RI_ASSERT(ret != EDEADLK);	//recursive mutexes shouldn't return this
+    RI_ASSERT(!ret);	//check that there aren't other errors
+    RI_UNREF(ret);
+    mutexRefCount++;
+}
+void OSReleaseMutex(void)
+{
+    RI_ASSERT(mutexInitialized);
+    mutexRefCount--;
+    RI_ASSERT(mutexRefCount >= 0);
+    int ret = pthread_mutex_unlock(&mutex);
+    RI_ASSERT(ret != EPERM);	//assert that the current thread owns the mutex
+    RI_ASSERT(!ret);	//check that there aren't more errors
+    RI_UNREF(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static bool isBigEndian()
+{
+    static const RIuint32 v = 0x12345678u;
+    const RIuint8* p = (const RIuint8*)&v;
+    RI_ASSERT (*p == (RIuint8)0x12u || *p == (RIuint8)0x78u);
+    return (*p == (RIuint8)(0x12)) ? true : false;
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window)
+{
+    try
+    {
+        OSWindowContext* ctx = RI_NEW(OSWindowContext, ());
+        ctx->window = (int)window;
+        ctx->tmp = NULL;
+        ctx->tmpWidth = 0;
+        ctx->tmpHeight = 0;
+        return ctx;
+    }
+    catch(std::bad_alloc)
+    {
+        return NULL;
+    }
+}
+
+void OSDestroyWindowContext(OSWindowContext* ctx)
+{
+    if(ctx)
+    {
+        RI_DELETE_ARRAY(ctx->tmp);
+        RI_DELETE(ctx);
+    }
+}
+
+bool OSIsWindow(const OSWindowContext* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        //TODO implement
+        return true;
+    }
+    return false;
+}
+
+void OSGetWindowSize(const OSWindowContext* ctx, int& width, int& height)
+{
+    if(ctx)
+    {
+        int currWin = glutGetWindow();
+        glutSetWindow((int)ctx->window);
+        width = glutGet(GLUT_WINDOW_WIDTH);
+        height = glutGet(GLUT_WINDOW_HEIGHT);
+        glutSetWindow(currWin);
+    }
+    else
+    {
+        width = 0;
+        height = 0;
+    }
+}
+
+void OSBlitToWindow(OSWindowContext* ctx, const Drawable* drawable)
+{
+    if(ctx)
+    {
+        int w = drawable->getWidth();
+        int h = drawable->getHeight();
+
+        int currWin = glutGetWindow();
+        glutSetWindow((int)ctx->window);
+
+        if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h)
+        {
+            RI_DELETE_ARRAY(ctx->tmp);
+            ctx->tmp = NULL;
+            try
+            {
+                ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h);	//throws bad_alloc
+                ctx->tmpWidth = w;
+                ctx->tmpHeight = h;
+            }
+            catch(std::bad_alloc)
+            {
+                //do nothing
+            }
+        }
+
+        if(ctx->tmp)
+        {
+            glViewport(0, 0, w, h);
+            glDisable(GL_DEPTH_TEST);
+            glMatrixMode(GL_PROJECTION);
+            glLoadIdentity();
+            glMatrixMode(GL_MODELVIEW);
+            glLoadIdentity();
+            //NOTE: we assume here that the display is always in sRGB color space
+            VGImageFormat f = VG_sABGR_8888_PRE;
+            if(isBigEndian())
+                f = VG_sRGBA_8888_PRE;
+            static bool flip = false;
+            if (!flip)
+            {
+                vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h);
+                //flip = true;
+            }
+            else
+            {
+                void* ptr = (void*)((RIuint8*)ctx->tmp + (w*sizeof(unsigned int)*(h-1)));
+                vgReadPixels(ptr, -w*sizeof(unsigned int), f, 0, 0, w, h);
+                flip = false;
+            }
+            glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp);
+        }
+
+        glutSwapBuffers();	//shows the OpenGL frame buffer
+        glutSetWindow(currWin);		//restore the current window
+    }
+}
+
+EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id)
+{
+    RI_UNREF(display_id);
+    return (EGLDisplay)1;    //support only a single display
+}
+
+}   //namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/macosx/riEGLOS.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,409 @@
+/*------------------------------------------------------------------------
+ *
+ * EGL 1.3
+ * -------
+ *
+ * Copyright (c) 2007 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.
+ *
+ *//**
+ * \file
+ * \brief	Mac OS X specific EGL functionality
+ * \note
+  *//*-------------------------------------------------------------------*/
+
+#include "egl.h"
+#include "riImage.h"
+#include <pthread.h>
+#include <sys/errno.h>
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+void* OSGetCurrentThreadID(void)
+{
+	return (void*)pthread_self();   //TODO this is not safe
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+static pthread_mutex_t mutex;
+static int mutexRefCount = 0;
+static bool mutexInitialized = false;
+//acquired mutex cannot be deinited
+void OSDeinitMutex(void)
+{
+	RI_ASSERT(mutexInitialized);
+	RI_ASSERT(mutexRefCount == 0);
+	int ret = pthread_mutex_destroy(&mutex);
+	RI_ASSERT(ret != EINVAL);	//assert that the mutex has been initialized
+	RI_ASSERT(ret != EAGAIN);	//assert that the maximum number of recursive locks hasn't been exceeded
+	RI_ASSERT(!ret);	//check that there aren't other errors
+	RI_UNREF(ret);
+}
+void OSAcquireMutex(void)
+{
+	if(!mutexInitialized)
+    {
+        int ret;
+        pthread_mutexattr_t attr;
+        ret = pthread_mutexattr_init(&attr);	//initially not locked
+        RI_ASSERT(!ret);	//check that there aren't any errors
+        ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);	//count the number of recursive locks
+        RI_ASSERT(!ret);	//check that there aren't any errors
+        ret = pthread_mutex_init(&mutex, &attr);
+        pthread_mutexattr_destroy(&attr);
+        RI_ASSERT(!ret);	//check that there aren't more errors
+        RI_UNREF(ret);
+        mutexInitialized = true;
+    }
+	int ret = pthread_mutex_lock(&mutex);
+	RI_ASSERT(ret != EINVAL);	//assert that the mutex has been initialized
+	RI_ASSERT(ret != EAGAIN);	//assert that the maximum number of recursive locks hasn't been exceeded
+	RI_ASSERT(ret != EDEADLK);	//recursive mutexes shouldn't return this
+	RI_ASSERT(!ret);	//check that there aren't other errors
+	RI_UNREF(ret);
+	mutexRefCount++;
+}
+void OSReleaseMutex(void)
+{
+	RI_ASSERT(mutexInitialized);
+	mutexRefCount--;
+	RI_ASSERT(mutexRefCount >= 0);
+	int ret = pthread_mutex_unlock(&mutex);
+	RI_ASSERT(ret != EPERM);	//assert that the current thread owns the mutex
+	RI_ASSERT(!ret);	//check that there aren't more errors
+	RI_UNREF(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+static bool isBigEndian()
+{
+	static const RIuint32 v = 0x12345678u;
+	const RIuint8* p = (const RIuint8*)&v;
+	RI_ASSERT (*p == (RIuint8)0x12u || *p == (RIuint8)0x78u);
+	return (*p == (RIuint8)(0x12)) ? true : false;
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+#ifdef RI_USE_GLUT
+#   include <OpenGL/gl.h>
+#   include <GLUT/glut.h>
+
+struct OSWindowContext
+{
+    int                 window;
+    unsigned int*       tmp;
+    int                 tmpWidth;
+    int                 tmpHeight;
+};
+
+OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window)
+{
+    try
+    {
+        OSWindowContext* ctx = RI_NEW(OSWindowContext, ());
+        ctx->window = window;
+        ctx->tmp = NULL;
+        ctx->tmpWidth = 0;
+        ctx->tmpHeight = 0;
+        return ctx;
+    }
+	catch(std::bad_alloc)
+	{
+		return NULL;
+	}
+}
+
+void OSDestroyWindowContext(OSWindowContext* ctx)
+{
+    if(ctx)
+    {
+        RI_DELETE_ARRAY(ctx->tmp);
+        RI_DELETE(ctx);
+    }
+}
+
+bool OSIsWindow(const void* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        //TODO implement
+        return true;
+    }
+    return false;
+}
+
+void OSGetWindowSize(const OSWindowContext* ctx, int& width, int& height)
+{
+    if(ctx)
+    {
+        int currWin = glutGetWindow();
+        glutSetWindow((int)ctx->window);
+        width = glutGet(GLUT_WINDOW_WIDTH);
+        height = glutGet(GLUT_WINDOW_HEIGHT);
+        glutSetWindow(currWin);
+    }
+    else
+    {
+        width = 0;
+        height = 0;
+    }
+}
+
+void OSBlitToWindow(OSWindowContext* ctx, const Drawable* drawable)
+{
+    if(ctx)
+    {
+        int w = drawable->getWidth();
+        int h = drawable->getHeight();
+
+        int currWin = glutGetWindow();
+        glutSetWindow((int)ctx->window);
+
+        if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h)
+        {
+            RI_DELETE_ARRAY(ctx->tmp);
+            ctx->tmp = NULL;
+            try
+            {
+                ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h);	//throws bad_alloc
+                ctx->tmpWidth = w;
+                ctx->tmpHeight = h;
+            }
+            catch(std::bad_alloc)
+            {
+                //do nothing
+            }
+        }
+
+        if(ctx->tmp)
+        {
+            glViewport(0, 0, w, h);
+            glDisable(GL_DEPTH_TEST);
+            glMatrixMode(GL_PROJECTION);
+            glLoadIdentity();
+            glMatrixMode(GL_MODELVIEW);
+            glLoadIdentity();
+            //NOTE: we assume here that the display is always in sRGB color space
+            VGImageFormat f = VG_sXBGR_8888;
+            if(isBigEndian())
+                f = VG_sRGBX_8888;
+            vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h);
+            glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp);
+        }
+
+        glutSwapBuffers();	//shows the OpenGL frame buffer
+        glutSetWindow(currWin);		//restore the current window
+    }
+}
+
+#else
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+//Mac OS X native
+#include <OpenGL/gl.h>
+#include <AGL/agl.h>
+
+struct OSWindowContext
+{
+    AGLPixelFormat      aglPixFmt;
+    AGLContext          aglContext;
+    WindowPtr           window;
+    unsigned int*       tmp;
+    int                 tmpWidth;
+    int                 tmpHeight;
+};
+
+void* OSCreateWindowContext(EGLNativeWindowType window)
+{
+    OSWindowContext* ctx = NULL;
+    try
+    {
+        ctx = RI_NEW(OSWindowContext, ());
+    }
+	catch(std::bad_alloc)
+	{
+		return NULL;
+	}
+
+    GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_DEPTH_SIZE, 32, AGL_NONE };
+    ctx->aglPixFmt = aglChoosePixelFormat(NULL, 0, attrib);
+    if(!ctx->aglPixFmt)
+    {
+        RI_DELETE(ctx);
+        return NULL;
+    }
+
+    ctx->aglContext = aglCreateContext(ctx->aglPixFmt, NULL);
+    if(!ctx->aglContext)
+    {
+        aglDestroyPixelFormat(ctx->aglPixFmt);
+        RI_DELETE(ctx);
+        return NULL;
+    }
+
+    GLint opaque = 1;
+    GLint sync = 1;
+    aglSetInteger(ctx->aglContext, AGL_SURFACE_OPACITY, &opaque);
+    aglSetInteger(ctx->aglContext, AGL_SWAP_INTERVAL, &sync);
+
+    ctx->window = (WindowPtr)window;
+    ctx->tmp = NULL;
+    ctx->tmpWidth = 0;
+    ctx->tmpHeight = 0;
+    return ctx;
+}
+
+void OSDestroyWindowContext(void* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        aglSetDrawable(ctx->aglContext, NULL);
+        aglSetCurrentContext(NULL);
+        aglDestroyContext(ctx->aglContext);
+        aglDestroyPixelFormat(ctx->aglPixFmt);
+        RI_DELETE_ARRAY(ctx->tmp);
+        RI_DELETE(ctx);
+    }
+}
+
+bool OSIsWindow(const void* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        if(IsValidWindowPtr(ctx->window))
+            return true;
+    }
+    return false;
+}
+
+void OSGetWindowSize(const void* context, int& width, int& height)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        Rect rectPort;
+        GetWindowPortBounds(ctx->window, &rectPort);
+        width = rectPort.right - rectPort.left;
+        height = rectPort.bottom - rectPort.top;
+    }
+    else
+    {
+        width = 0;
+        height = 0;
+    }
+}
+
+void OSBlitToWindow(void* context, const Drawable* drawable)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        int w = drawable->getWidth();
+        int h = drawable->getHeight();
+
+        GrafPtr portSave = NULL;
+        GetPort(&portSave);
+        SetPort((GrafPtr)GetWindowPort(ctx->window));
+        aglSetDrawable(ctx->aglContext, GetWindowPort(ctx->window));
+        aglSetCurrentContext(ctx->aglContext);
+
+        if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h)
+        {
+            RI_DELETE_ARRAY(ctx->tmp);
+            ctx->tmp = NULL;
+            try
+            {
+                ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h);	//throws bad_alloc
+                ctx->tmpWidth = w;
+                ctx->tmpHeight = h;
+            }
+            catch(std::bad_alloc)
+            {
+                //do nothing
+            }
+        }
+
+        if(ctx->tmp)
+        {
+            glViewport(0, 0, w, h);
+            glDisable(GL_DEPTH_TEST);
+            glMatrixMode(GL_PROJECTION);
+            glLoadIdentity();
+            glMatrixMode(GL_MODELVIEW);
+            glLoadIdentity();
+            //NOTE: we assume here that the display is always in sRGB color space
+            VGImageFormat f = VG_sXBGR_8888;
+            if(isBigEndian())
+                f = VG_sRGBX_8888;
+            vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h);
+            glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp);
+        }
+
+        aglSwapBuffers(ctx->aglContext);
+        SetPort(portSave);
+    }
+}
+
+#endif
+
+EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id)
+{
+    RI_UNREF(display_id);
+    return (EGLDisplay)1;    //support only a single display
+}
+
+}   //namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/null/riEGLOS.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,160 @@
+/*------------------------------------------------------------------------
+ *
+ * EGL 1.3
+ * -------
+ *
+ * Copyright (c) 2007 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.
+ *
+ *//**
+ * \file
+ * \brief	Generic OS EGL functionality (not thread safe, no window rendering)
+ * \note
+  *//*-------------------------------------------------------------------*/
+
+#include "egl.h"
+#include "riImage.h"
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+void* OSGetCurrentThreadID(void)
+{
+	return NULL;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+static int mutexRefCount = 0;
+static bool mutexInitialized = false;
+//acquired mutex cannot be deinited
+void OSDeinitMutex(void)
+{
+	RI_ASSERT(mutexInitialized);
+	RI_ASSERT(mutexRefCount == 0);
+}
+void OSAcquireMutex(void)
+{
+	if(!mutexInitialized)
+    {
+        mutexInitialized = true;
+    }
+	mutexRefCount++;
+}
+void OSReleaseMutex(void)
+{
+	RI_ASSERT(mutexInitialized);
+	mutexRefCount--;
+	RI_ASSERT(mutexRefCount >= 0);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+struct OSWindowContext
+{
+    int                 tmpWidth;
+    int                 tmpHeight;
+};
+
+void* OSCreateWindowContext(EGLNativeWindowType window)
+{
+    OSWindowContext* ctx = NULL;
+    try
+    {
+        ctx = RI_NEW(OSWindowContext, ());
+    }
+	catch(std::bad_alloc)
+	{
+		return NULL;
+	}
+    ctx->tmpWidth = 0;
+    ctx->tmpHeight = 0;
+    return ctx;
+}
+
+void OSDestroyWindowContext(void* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        RI_DELETE(ctx);
+    }
+}
+
+bool OSIsWindow(const void* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        return true;
+    }
+    return false;
+}
+
+void OSGetWindowSize(const void* context, int& width, int& height)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        width = ctx->tmpWidth;
+        height = ctx->tmpHeight;
+    }
+    else
+    {
+        width = 0;
+        height = 0;
+    }
+}
+
+void OSBlitToWindow(void* context, const Drawable* drawable)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        ctx->tmpWidth = drawable->getWidth();
+        ctx->tmpHeight = drawable->getHeight();
+    }
+}
+
+EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id)
+{
+    RI_UNREF(display_id);
+    return (EGLDisplay)1;    //support only a single display
+}
+
+}   //namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riApi.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,3839 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementations of OpenVG API functions.
+ * \note	The actual processing is done in Path, Image, Rasterizer and PixelPipe classes.
+ *//*-------------------------------------------------------------------*/
+
+#include "openvg.h"
+#include "vgext.h"
+#include "riContext.h"
+#include "riRasterizer.h"
+#include "riPixelPipe.h"
+#include "riPath.h"
+#include <stdio.h>
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/* EGL&OS functions for use in an OpenVG implementation */
+// \note To ensure that different EGLs work in parallel, these functions must be implemented.
+// They may be wrappers if the underlying EGL is more complicated that miniEGL.
+void* eglvgGetCurrentVGContext(void);
+bool  eglvgIsInUse(void* image);
+bool  eglvgLockSurface(bool read, bool write);
+bool  eglvgUnlockSurface();
+void  OSAcquireMutex(void);
+void  OSReleaseMutex(void);
+void  eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride );
+void*  eglvgGetImageData( void* image );
+
+#define RI_NO_RETVAL
+
+//this must be the first line in an API function
+#define RI_GET_CONTEXT(RETVAL) \
+    OSAcquireMutex(); \
+    VGContext* context = (VGContext*)eglvgGetCurrentVGContext(); \
+    if(!context) \
+    { \
+        OSReleaseMutex(); \
+        return RETVAL;\
+    }
+
+#define RI_IF_ERROR(COND, ERRORCODE, RETVAL) \
+    if(COND) { context->setError(ERRORCODE); OSReleaseMutex(); return RETVAL; }
+
+//all API functions must call this as their last operation (also functions that don't return values)
+//NOTE: don't evaluate anything or read state in RETVAL (it'll be executed after the mutex has been released)
+#define RI_RETURN(RETVAL) \
+    { OSReleaseMutex(); \
+    return RETVAL; }
+
+static bool isAligned(const void* ptr, int alignment)
+{
+    RI_ASSERT(alignment == 1 || alignment == 2 || alignment == 4);
+    if(((RIuintptr)ptr) & (alignment-1))
+        return false;
+    return true;
+}
+
+static bool isAligned(const void* ptr, VGImageFormat format)
+{
+    RI_ASSERT(isValidImageFormat(format));
+    int alignment = Color::formatToDescriptor(format).bitsPerPixel >> 3;
+    if(alignment <= 1)
+        return true;	//one bit or byte per pixel
+    return isAligned(ptr, alignment);
+}
+
+bool isValidImageFormat(int f)
+{
+    if(f < VG_sRGBX_8888 || f > VG_lABGR_8888_PRE)
+        return false;
+    return true;
+}
+
+}	//namespace OpenVGRI
+
+using namespace OpenVGRI;
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgFlush(void)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    //the RI doesn't cache anything, so this is a no-op
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgFinish(void)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    //the RI doesn't cache anything, so this is a no-op
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGErrorCode RI_APIENTRY vgGetError(void)
+{
+    RI_GET_CONTEXT(VG_NO_CONTEXT_ERROR);
+    VGErrorCode error = context->m_error;
+    context->m_error = VG_NO_ERROR;
+    RI_RETURN(error);
+}
+
+VGErrorCode RI_APIENTRY vgPlatsimGetError(void)
+{
+    RI_GET_CONTEXT(VG_NO_CONTEXT_ERROR);
+    VGErrorCode error = context->m_error;
+    RI_RETURN(error);
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+namespace OpenVGRI
+{
+
+RIfloat inputFloat(VGfloat f)
+{
+    //this function is used for all floating point input values
+    if(RI_ISNAN(f)) return 0.0f;	//convert NaN to zero
+    return RI_CLAMP(f, -RI_FLOAT_MAX, RI_FLOAT_MAX);	//clamp +-inf to +-RIfloat max
+}
+
+Vector2 inputVector2(const Vector2& v)
+{
+    return Vector2(inputFloat(v.x), inputFloat(v.y));
+}
+
+Color inputColor(const Color& c)
+{
+    Color r = c;
+    r.r = inputFloat(r.r);
+    r.g = inputFloat(r.g);
+    r.b = inputFloat(r.b);
+    r.a = inputFloat(r.a);
+    return r;
+}
+
+static int inputFloatToInt(VGfloat value)
+{
+    double v = (double)floor(value);
+    v = v > (double)RI_INT32_MAX ? (double)RI_INT32_MAX : v;
+    v = v < (double)RI_INT32_MIN ? (double)RI_INT32_MIN : v;
+    return (int)v;
+}
+
+static int paramToInt(const void* values, bool floats, int count, int i)
+{
+    RI_ASSERT(i >= 0);
+    if(i >= count || !values)
+        return 0;
+    if(floats)
+        return inputFloatToInt(((const VGfloat*)values)[i]);
+    return (int)((const VGint*)values)[i];
+}
+
+static RIfloat paramToFloat(const void* values, bool floats, int count, int i)
+{
+    RI_ASSERT(i >= 0);
+    if(i >= count || !values)
+        return 0.0f;
+    if(floats)
+        return ((const VGfloat*)values)[i];
+    return (RIfloat)((const VGint*)values)[i];
+}
+
+static void floatToParam(void* output, bool outputFloats, int count, int i, VGfloat value)
+{
+    RI_ASSERT(i >= 0);
+    RI_ASSERT(output);
+    if(i >= count)
+        return;
+    if(outputFloats)
+        ((VGfloat*)output)[i] = value;
+    else
+        ((VGint*)output)[i] = (VGint)inputFloatToInt(value);
+}
+
+static void intToParam(void* output, bool outputFloats, int count, int i, VGint value)
+{
+    RI_ASSERT(i >= 0);
+    RI_ASSERT(output);
+    if(i >= count)
+        return;
+    if(outputFloats)
+        ((VGfloat*)output)[i] = (VGfloat)value;
+    else
+        ((VGint*)output)[i] = value;
+}
+
+}	//namespace OpenVGRI
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void setifv(VGContext* context, VGParamType type, VGint count, const void* values, bool floats)
+{
+    RI_ASSERT(context);
+    RI_ASSERT(!count || (count && values));
+
+    int ivalue = paramToInt(values, floats, count, 0);
+    RIfloat fvalue = paramToFloat(values, floats, count, 0);
+
+    switch(type)
+    {
+    case VG_MATRIX_MODE:
+        if(count != 1 || ivalue < VG_MATRIX_PATH_USER_TO_SURFACE || ivalue > VG_MATRIX_GLYPH_USER_TO_SURFACE)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_matrixMode = (VGMatrixMode)ivalue;
+        break;
+
+    case VG_FILL_RULE:
+        if(count != 1 || ivalue < VG_EVEN_ODD || ivalue > VG_NON_ZERO)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_fillRule = (VGFillRule)ivalue;
+        break;
+
+    case VG_IMAGE_QUALITY:
+        if(count != 1 || !(ivalue == VG_IMAGE_QUALITY_NONANTIALIASED || ivalue == VG_IMAGE_QUALITY_FASTER || ivalue == VG_IMAGE_QUALITY_BETTER))	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_imageQuality = (VGImageQuality)ivalue;
+        break;
+
+    case VG_RENDERING_QUALITY:
+        if(count != 1 || !(ivalue == VG_RENDERING_QUALITY_NONANTIALIASED || ivalue == VG_RENDERING_QUALITY_FASTER || ivalue == VG_RENDERING_QUALITY_BETTER))	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_renderingQuality = (VGRenderingQuality)ivalue;
+        break;
+
+    case VG_BLEND_MODE:
+        if(count != 1 || ivalue < VG_BLEND_SRC || ivalue > VG_BLEND_ADDITIVE)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_blendMode = (VGBlendMode)ivalue;
+        break;
+
+    case VG_IMAGE_MODE:
+        if(count != 1 || ivalue < VG_DRAW_IMAGE_NORMAL || ivalue > VG_DRAW_IMAGE_STENCIL)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_imageMode = (VGImageMode)ivalue;
+        break;
+
+    case VG_SCISSOR_RECTS:
+    {
+        if(count & 3)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }	//count must be a multiple of four
+        try
+        {
+            Array<OpenVGRI::Rectangle> scissor;
+            for(int i=0;i<RI_INT_MIN(count, RI_MAX_SCISSOR_RECTANGLES*4);i+=4)
+            {
+                OpenVGRI::Rectangle s;
+                s.x = paramToInt(values, floats, count, i+0);
+                s.y = paramToInt(values, floats, count, i+1);
+                s.width = paramToInt(values, floats, count, i+2);
+                s.height = paramToInt(values, floats, count, i+3);
+                scissor.push_back(s);	//throws bad_alloc
+            }
+            context->m_scissor.swap(scissor);	//replace context data
+        }
+        catch(std::bad_alloc)
+        {
+            context->setError(VG_OUT_OF_MEMORY_ERROR);
+        }
+        break;
+    }
+
+    case VG_COLOR_TRANSFORM:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_colorTransform = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_COLOR_TRANSFORM_VALUES:
+        if(count != 8 || !values) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        {
+            for(int i=0;i<8;i++)
+            {
+                context->m_inputColorTransformValues[i] = paramToFloat(values, floats, count, i);
+                context->m_colorTransformValues[i] = inputFloat(context->m_inputColorTransformValues[i]);
+            }
+        }
+        break;
+
+    case VG_STROKE_LINE_WIDTH:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputStrokeLineWidth = fvalue;
+        context->m_strokeLineWidth = inputFloat(fvalue);
+        break;
+
+    case VG_STROKE_CAP_STYLE:
+        if(count != 1 || ivalue < VG_CAP_BUTT || ivalue > VG_CAP_SQUARE)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_strokeCapStyle = (VGCapStyle)ivalue;
+        break;
+
+    case VG_STROKE_JOIN_STYLE:
+        if(count != 1 || ivalue < VG_JOIN_MITER || ivalue > VG_JOIN_BEVEL)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_strokeJoinStyle = (VGJoinStyle)ivalue;
+        break;
+
+    case VG_STROKE_MITER_LIMIT:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputStrokeMiterLimit = fvalue;
+        context->m_strokeMiterLimit = inputFloat(fvalue);
+        break;
+
+    case VG_STROKE_DASH_PATTERN:
+    {
+        try
+        {
+            Array<RIfloat> inputStrokeDashPattern;
+            Array<RIfloat> strokeDashPattern;
+            for(int i=0;i<RI_INT_MIN(count, RI_MAX_DASH_COUNT);i++)
+            {
+                RIfloat v = paramToFloat(values, floats, count, i);
+                inputStrokeDashPattern.push_back(v);	//throws bad_alloc
+                strokeDashPattern.push_back(inputFloat(v));	//throws bad_alloc
+            }
+            context->m_inputStrokeDashPattern.swap(inputStrokeDashPattern);	//replace context data
+            context->m_strokeDashPattern.swap(strokeDashPattern);	//replace context data
+        }
+        catch(std::bad_alloc)
+        {
+            context->setError(VG_OUT_OF_MEMORY_ERROR);
+        }
+        break;
+    }
+
+    case VG_STROKE_DASH_PHASE:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputStrokeDashPhase = fvalue;
+        context->m_strokeDashPhase = inputFloat(fvalue);
+        break;
+
+    case VG_STROKE_DASH_PHASE_RESET:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_strokeDashPhaseReset = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_TILE_FILL_COLOR:
+        if(count != 4 || !values) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputTileFillColor.set(paramToFloat(values, floats, count, 0),
+                                     paramToFloat(values, floats, count, 1),
+                                     paramToFloat(values, floats, count, 2),
+                                     paramToFloat(values, floats, count, 3),
+                                     Color::sRGBA);
+        context->m_tileFillColor = inputColor(context->m_inputTileFillColor);
+        break;
+
+    case VG_GLYPH_ORIGIN:
+        if(count != 2 || !values) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputGlyphOrigin.x = paramToFloat(values, floats, count, 0);
+        context->m_inputGlyphOrigin.y = paramToFloat(values, floats, count, 1);
+        context->m_glyphOrigin = inputVector2(context->m_inputGlyphOrigin);
+        break;
+
+    case VG_CLEAR_COLOR:
+        if(count != 4 || !values) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_inputClearColor.set(paramToFloat(values, floats, count, 0),
+                                  paramToFloat(values, floats, count, 1),
+                                  paramToFloat(values, floats, count, 2),
+                                  paramToFloat(values, floats, count, 3),
+                                  Color::sRGBA);
+        context->m_clearColor = inputColor(context->m_inputClearColor);
+        break;
+
+    case VG_MASKING:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_masking = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_SCISSORING:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_scissoring = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_PIXEL_LAYOUT:
+        if(count != 1 || ivalue < VG_PIXEL_LAYOUT_UNKNOWN || ivalue > VG_PIXEL_LAYOUT_BGR_HORIZONTAL)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_pixelLayout = (VGPixelLayout)ivalue;
+        break;
+
+    case VG_SCREEN_LAYOUT:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        break;	//setting read-only values has no effect
+
+    case VG_FILTER_FORMAT_LINEAR:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_filterFormatLinear = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_FILTER_FORMAT_PREMULTIPLIED:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        context->m_filterFormatPremultiplied = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_FILTER_CHANNEL_MASK:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        //undefined bits are ignored
+        context->m_filterChannelMask = (VGbitfield)ivalue;
+        break;
+
+    case VG_MAX_SCISSOR_RECTS:
+    case VG_MAX_DASH_COUNT:
+    case VG_MAX_KERNEL_SIZE:
+    case VG_MAX_SEPARABLE_KERNEL_SIZE:
+    case VG_MAX_COLOR_RAMP_STOPS:
+    case VG_MAX_IMAGE_WIDTH:
+    case VG_MAX_IMAGE_HEIGHT:
+    case VG_MAX_IMAGE_PIXELS:
+    case VG_MAX_IMAGE_BYTES:
+    case VG_MAX_FLOAT:
+    case VG_MAX_GAUSSIAN_STD_DEVIATION:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        break;	//setting read-only values has no effect
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetf(VGParamType type, VGfloat value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR ||
+                type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//vector type value
+    VGfloat values[1] = {value};
+    setifv(context, type, 1, values, true);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSeti(VGParamType type, VGint value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR ||
+                type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//vector type value
+    VGint values[1] = {value};
+    setifv(context, type, 1, values, false);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetiv(VGParamType type, VGint count, const VGint * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count < 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR((!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    setifv(context, type, count, values, false);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetfv(VGParamType type, VGint count, const VGfloat * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count < 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR((!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    setifv(context, type, count, values, true);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getifv(VGContext* context, VGParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_MATRIX_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_matrixMode);
+        break;
+
+    case VG_FILL_RULE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_fillRule);
+        break;
+
+    case VG_IMAGE_QUALITY:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_imageQuality);
+        break;
+
+    case VG_RENDERING_QUALITY:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_renderingQuality);
+        break;
+
+    case VG_BLEND_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_blendMode);
+        break;
+
+    case VG_IMAGE_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_imageMode);
+        break;
+
+    case VG_SCISSOR_RECTS:
+    {
+        if(count > context->m_scissor.size()*4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        for(int i=0;i<context->m_scissor.size();i++)
+        {
+            intToParam(values, floats, count, i*4+0, context->m_scissor[i].x);
+            intToParam(values, floats, count, i*4+1, context->m_scissor[i].y);
+            intToParam(values, floats, count, i*4+2, context->m_scissor[i].width);
+            intToParam(values, floats, count, i*4+3, context->m_scissor[i].height);
+        }
+        break;
+    }
+
+    case VG_COLOR_TRANSFORM:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_colorTransform);
+        break;
+
+    case VG_COLOR_TRANSFORM_VALUES:
+        if(count > 8) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        {
+            for(int i=0;i<count;i++)
+            {
+                floatToParam(values, floats, count, i, context->m_inputColorTransformValues[i]);
+            }
+        }
+        break;
+
+    case VG_STROKE_LINE_WIDTH:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputStrokeLineWidth);
+        break;
+
+    case VG_STROKE_CAP_STYLE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_strokeCapStyle);
+        break;
+
+    case VG_STROKE_JOIN_STYLE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_strokeJoinStyle);
+        break;
+
+    case VG_STROKE_MITER_LIMIT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputStrokeMiterLimit);
+        break;
+
+    case VG_STROKE_DASH_PATTERN:
+    {
+        if(count > context->m_inputStrokeDashPattern.size())	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        for(int i=0;i<context->m_inputStrokeDashPattern.size();i++)
+            floatToParam(values, floats, count, i, context->m_inputStrokeDashPattern[i]);
+        break;
+    }
+
+    case VG_STROKE_DASH_PHASE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputStrokeDashPhase);
+        break;
+
+    case VG_STROKE_DASH_PHASE_RESET:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_strokeDashPhaseReset);
+        break;
+
+    case VG_TILE_FILL_COLOR:
+        if(count > 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputTileFillColor.r);
+        floatToParam(values, floats, count, 1, context->m_inputTileFillColor.g);
+        floatToParam(values, floats, count, 2, context->m_inputTileFillColor.b);
+        floatToParam(values, floats, count, 3, context->m_inputTileFillColor.a);
+        break;
+
+    case VG_CLEAR_COLOR:
+        if(count > 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputClearColor.r);
+        floatToParam(values, floats, count, 1, context->m_inputClearColor.g);
+        floatToParam(values, floats, count, 2, context->m_inputClearColor.b);
+        floatToParam(values, floats, count, 3, context->m_inputClearColor.a);
+        break;
+
+    case VG_GLYPH_ORIGIN:
+        if(count > 2)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, context->m_inputGlyphOrigin.x);
+        floatToParam(values, floats, count, 1, context->m_inputGlyphOrigin.y);
+        break;
+
+    case VG_MASKING:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_masking);
+        break;
+
+    case VG_SCISSORING:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_scissoring);
+        break;
+
+    case VG_PIXEL_LAYOUT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_pixelLayout);
+        break;
+
+    case VG_SCREEN_LAYOUT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, VG_PIXEL_LAYOUT_UNKNOWN);
+        break;
+
+    case VG_FILTER_FORMAT_LINEAR:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_filterFormatLinear);
+        break;
+
+    case VG_FILTER_FORMAT_PREMULTIPLIED:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_filterFormatPremultiplied);
+        break;
+
+    case VG_FILTER_CHANNEL_MASK:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, context->m_filterChannelMask);
+        break;
+
+    case VG_MAX_SCISSOR_RECTS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_SCISSOR_RECTANGLES);
+        break;
+
+    case VG_MAX_DASH_COUNT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_DASH_COUNT);
+        break;
+
+    case VG_MAX_KERNEL_SIZE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_KERNEL_SIZE);
+        break;
+
+    case VG_MAX_SEPARABLE_KERNEL_SIZE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_SEPARABLE_KERNEL_SIZE);
+        break;
+
+    case VG_MAX_COLOR_RAMP_STOPS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_COLOR_RAMP_STOPS);
+        break;
+
+    case VG_MAX_IMAGE_WIDTH:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_IMAGE_WIDTH);
+        break;
+
+    case VG_MAX_IMAGE_HEIGHT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_IMAGE_HEIGHT);
+        break;
+
+    case VG_MAX_IMAGE_PIXELS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_IMAGE_PIXELS);
+        break;
+
+    case VG_MAX_IMAGE_BYTES:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, RI_MAX_IMAGE_BYTES);
+        break;
+
+    case VG_MAX_FLOAT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, RI_FLOAT_MAX);
+        break;
+
+    case VG_MAX_GAUSSIAN_STD_DEVIATION:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, RI_MAX_GAUSSIAN_STD_DEVIATION);
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGfloat RI_APIENTRY vgGetf(VGParamType type)
+{
+    RI_GET_CONTEXT(0.0f);
+    RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR ||
+                type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, 0.0f);	//vector type value
+    RIfloat ret = 0.0f;
+    getifv(context, type, 1, &ret, true);
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGint RI_APIENTRY vgGeti(VGParamType type)
+{
+    RI_GET_CONTEXT(0);
+    RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR ||
+                type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, 0);	//vector type value
+    VGint ret = 0;
+    getifv(context, type, 1, &ret, false);
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetiv(VGParamType type, VGint count, VGint * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    getifv(context, type, count, values, false);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetfv(VGParamType type, VGint count, VGfloat * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    getifv(context, type, count, values, true);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGint RI_APIENTRY vgGetVectorSize(VGParamType type)
+{
+    RI_GET_CONTEXT(0);
+    VGint ret = 0;
+    switch(type)
+    {
+    case VG_MATRIX_MODE:
+    case VG_FILL_RULE:
+    case VG_IMAGE_QUALITY:
+    case VG_RENDERING_QUALITY:
+    case VG_BLEND_MODE:
+    case VG_IMAGE_MODE:
+        ret = 1;
+        break;
+
+    case VG_SCISSOR_RECTS:
+        ret = 4*context->m_scissor.size();
+        break;
+
+    case VG_COLOR_TRANSFORM:
+        ret = 1;
+        break;
+
+    case VG_COLOR_TRANSFORM_VALUES:
+        ret = 8;
+        break;
+
+    case VG_STROKE_LINE_WIDTH:
+    case VG_STROKE_CAP_STYLE:
+    case VG_STROKE_JOIN_STYLE:
+    case VG_STROKE_MITER_LIMIT:
+        ret = 1;
+        break;
+
+    case VG_STROKE_DASH_PATTERN:
+        ret = context->m_inputStrokeDashPattern.size();
+        break;
+
+    case VG_STROKE_DASH_PHASE:
+    case VG_STROKE_DASH_PHASE_RESET:
+        ret = 1;
+        break;
+
+    case VG_TILE_FILL_COLOR:
+    case VG_CLEAR_COLOR:
+        ret = 4;
+        break;
+
+    case VG_GLYPH_ORIGIN:
+        ret = 2;
+        break;
+
+    case VG_MASKING:
+    case VG_SCISSORING:
+    case VG_PIXEL_LAYOUT:
+    case VG_SCREEN_LAYOUT:
+    case VG_FILTER_FORMAT_LINEAR:
+    case VG_FILTER_FORMAT_PREMULTIPLIED:
+    case VG_FILTER_CHANNEL_MASK:
+    case VG_MAX_SCISSOR_RECTS:
+    case VG_MAX_DASH_COUNT:
+    case VG_MAX_KERNEL_SIZE:
+    case VG_MAX_SEPARABLE_KERNEL_SIZE:
+    case VG_MAX_COLOR_RAMP_STOPS:
+    case VG_MAX_IMAGE_WIDTH:
+    case VG_MAX_IMAGE_HEIGHT:
+    case VG_MAX_IMAGE_PIXELS:
+    case VG_MAX_IMAGE_BYTES:
+    case VG_MAX_FLOAT:
+    case VG_MAX_GAUSSIAN_STD_DEVIATION:
+        ret = 1;
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void setPaintParameterifv(VGContext* context, Paint* paint, VGPaintParamType paramType, VGint count, const void* values, bool floats)
+{
+    RI_ASSERT(context);
+    RI_ASSERT(paint);
+
+    int ivalue = paramToInt(values, floats, count, 0);
+
+    switch(paramType)
+    {
+    case VG_PAINT_TYPE:
+        if(count != 1 || ivalue < VG_PAINT_TYPE_COLOR || ivalue > VG_PAINT_TYPE_PATTERN)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_paintType = (VGPaintType)ivalue;
+        break;
+
+    case VG_PAINT_COLOR:
+        RI_TRACE("\n***** Setting solid color to paint.\n");
+        RI_TRACE("** ptr: %x\n", (int)paint);
+        if(count != 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_inputPaintColor.set(paramToFloat(values, floats, count, 0),
+                                     paramToFloat(values, floats, count, 1),
+                                     paramToFloat(values, floats, count, 2),
+                                     paramToFloat(values, floats, count, 3),
+                                     Color::sRGBA);
+        RI_TRACE("** input solid color: [%.3f %.3f %.3f %.4f]\n", paint->m_inputPaintColor.r, paint->m_inputPaintColor.g, paint->m_inputPaintColor.b, paint->m_inputPaintColor.a);
+        paint->setColor(inputColor(paint->m_inputPaintColor));
+        RI_TRACE("** -> [%.3f %.3f %.3f %.3f]\n", paint->m_paintColor.r, paint->m_paintColor.g, paint->m_paintColor.b, paint->m_paintColor.a);
+        break;
+
+    case VG_PAINT_COLOR_RAMP_SPREAD_MODE:
+        if(count != 1 || ivalue < VG_COLOR_RAMP_SPREAD_PAD || ivalue > VG_COLOR_RAMP_SPREAD_REFLECT)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_colorRampSpreadMode = (VGColorRampSpreadMode)ivalue;
+        break;
+
+    case VG_PAINT_COLOR_RAMP_STOPS:
+    {
+        int numStops = count/5;
+        if(count != numStops*5)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }	//count must be a multiple of five
+        try
+        {
+            Array<Paint::GradientStop> colorRampStops;
+            Array<Paint::GradientStop> inputColorRampStops;
+            RIfloat prevOffset = -RI_FLOAT_MAX;
+            bool valid = true;
+            for(int i=0;i<RI_INT_MIN(numStops, RI_MAX_COLOR_RAMP_STOPS);i++)	//NOTE: ignores the final stop if there is not enough parameters
+            {
+                Paint::GradientStop gs;
+                gs.offset = paramToFloat(values, floats, count, i*5);
+                gs.color.set(paramToFloat(values, floats, count, i*5+1),
+                             paramToFloat(values, floats, count, i*5+2),
+                             paramToFloat(values, floats, count, i*5+3),
+                             paramToFloat(values, floats, count, i*5+4),
+                             Color::sRGBA);
+                inputColorRampStops.push_back(gs);
+
+                if(gs.offset < prevOffset)
+                    valid = false;	//decreasing sequence, ignore it
+
+                if(gs.offset >= 0.0f && gs.offset <= 1.0f)
+                {
+                    gs.color.clamp();
+
+                    if(!colorRampStops.size() && gs.offset > 0.0f)
+                    {	//the first valid stop is not at 0, replicate the first one
+                        RIfloat tmp = gs.offset;
+                        gs.offset = 0.0f;
+                        colorRampStops.push_back(gs);	//throws bad_alloc
+                        gs.offset = tmp;
+                    }
+                    colorRampStops.push_back(gs);	//throws bad_alloc
+                }
+                prevOffset = gs.offset;
+            }
+            if(valid && colorRampStops.size() && colorRampStops[colorRampStops.size()-1].offset < 1.0f)
+            {	//there is at least one stop, but the last one is not at 1, replicate the last one
+                Paint::GradientStop gs = colorRampStops[colorRampStops.size()-1];
+                gs.offset = 1.0f;
+                colorRampStops.push_back(gs);	//throws bad_alloc
+            }
+            if(!valid || !colorRampStops.size())
+            {	//there are no valid stops, add implicit stops
+                colorRampStops.clear();
+                Paint::GradientStop gs;
+                gs.offset = 0.0f;
+                gs.color.set(0,0,0,1,Color::sRGBA);
+                colorRampStops.push_back(gs);	//throws bad_alloc
+                gs.offset = 1.0f;
+                gs.color.set(1,1,1,1,Color::sRGBA);
+                colorRampStops.push_back(gs);	//throws bad_alloc
+            }
+            RI_ASSERT(colorRampStops.size() >= 2 && colorRampStops.size() <= RI_MAX_COLOR_RAMP_STOPS);
+            //paint->m_colorRampStops.swap(colorRampStops);	//set paint array
+            //paint->m_inputColorRampStops.swap(inputColorRampStops);	//set paint array
+            paint->setGradientStops(inputColorRampStops, colorRampStops);
+            //paint->generateLUT();
+        }
+        catch(std::bad_alloc)
+        {
+            context->setError(VG_OUT_OF_MEMORY_ERROR);
+        }
+        break;
+    }
+
+    case VG_PAINT_COLOR_RAMP_PREMULTIPLIED:
+        if(count != 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_colorRampPremultiplied = ivalue ? VG_TRUE : VG_FALSE;
+        break;
+
+    case VG_PAINT_LINEAR_GRADIENT:
+        if(count != 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_inputLinearGradientPoint0.set(paramToFloat(values, floats, count, 0),
+                                          paramToFloat(values, floats, count, 1));
+        paint->m_inputLinearGradientPoint1.set(paramToFloat(values, floats, count, 2),
+                                          paramToFloat(values, floats, count, 3));
+        paint->setLinearGradient(
+            inputVector2(paint->m_inputLinearGradientPoint0),
+            inputVector2(paint->m_inputLinearGradientPoint1));
+
+        break;
+
+    case VG_PAINT_RADIAL_GRADIENT:
+        if(count != 5)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_inputRadialGradientCenter.set(paramToFloat(values, floats, count, 0),
+                                          paramToFloat(values, floats, count, 1));
+        paint->m_inputRadialGradientFocalPoint.set(paramToFloat(values, floats, count, 2),
+                                              paramToFloat(values, floats, count, 3));
+        paint->m_inputRadialGradientRadius = paramToFloat(values, floats, count, 4);
+        paint->setRadialGradient(
+            inputVector2(paint->m_inputRadialGradientCenter),
+            inputVector2(paint->m_inputRadialGradientFocalPoint),
+            inputFloat(paint->m_inputRadialGradientRadius));
+        //paint->m_radialGradientCenter = inputVector2(paint->m_inputRadialGradientCenter);
+        //paint->m_radialGradientFocalPoint = inputVector2(paint->m_inputRadialGradientFocalPoint);
+        //paint->m_radialGradientRadius = inputFloat(paint->m_inputRadialGradientRadius);
+        break;
+
+    case VG_PAINT_PATTERN_TILING_MODE:
+        if(count != 1 || ivalue < VG_TILE_FILL || ivalue > VG_TILE_REFLECT)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        paint->m_patternTilingMode = (VGTilingMode)ivalue;
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetParameterf(VGHandle object, VGint paramType, VGfloat value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isMaskLayer = context->isValidMaskLayer(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle
+    RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT ||
+                paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //vector valued parameter
+    VGfloat values[1] = {value};
+    if(isImage)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPath)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont);
+        setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, values, true);
+    }
+    else if(isMaskLayer)
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isFont);
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont);
+        if (paramType != VG_FONT_NUM_GLYPHS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetParameteri(VGHandle object, VGint paramType, VGint value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isMaskLayer = context->isValidMaskLayer(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle
+    RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT ||
+                paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//vector valued parameter
+    VGint values[1] = {value};
+    if(isImage)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPath)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont);
+        setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, values, false);
+    }
+    else if(isMaskLayer)
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isFont);
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont);
+        if (paramType != VG_FONT_NUM_GLYPHS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetParameterfv(VGHandle object, VGint paramType, VGint count, const VGfloat * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count < 0 || (!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isMaskLayer = context->isValidMaskLayer(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle
+    if(isImage)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPath)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont);
+        setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, true);
+    }
+    else if(isMaskLayer)
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isFont);
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont);
+        if (paramType != VG_FONT_NUM_GLYPHS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetParameteriv(VGHandle object, VGint paramType, VGint count, const VGint * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count < 0 || (!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isMaskLayer = context->isValidMaskLayer(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle
+    if(isImage)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPath)
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont);
+        if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont);
+        setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, false);
+    }
+    else if(isMaskLayer)
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isFont);
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    else
+    {	//read only, the function does nothing
+        RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont);
+        if (paramType != VG_FONT_NUM_GLYPHS)
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getPaintParameterifv(VGContext* context, Paint* paint, VGPaintParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_PAINT_TYPE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, paint->m_paintType);
+        break;
+
+    case VG_PAINT_COLOR:
+        if(count > 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, paint->m_inputPaintColor.r);
+        floatToParam(values, floats, count, 1, paint->m_inputPaintColor.g);
+        floatToParam(values, floats, count, 2, paint->m_inputPaintColor.b);
+        floatToParam(values, floats, count, 3, paint->m_inputPaintColor.a);
+        break;
+
+    case VG_PAINT_COLOR_RAMP_SPREAD_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, paint->m_colorRampSpreadMode);
+        break;
+
+    case VG_PAINT_COLOR_RAMP_STOPS:
+        {
+            if(count > paint->m_inputColorRampStops.size()*5)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+            int j = 0;
+            for(int i=0;i<paint->m_inputColorRampStops.size();i++)
+            {
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].offset);
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.r);
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.g);
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.b);
+                floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.a);
+            }
+            break;
+        }
+
+    case VG_PAINT_COLOR_RAMP_PREMULTIPLIED:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, paint->m_colorRampPremultiplied);
+        break;
+
+    case VG_PAINT_LINEAR_GRADIENT:
+        if(count > 4)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, paint->m_inputLinearGradientPoint0.x);
+        floatToParam(values, floats, count, 1, paint->m_inputLinearGradientPoint0.y);
+        floatToParam(values, floats, count, 2, paint->m_inputLinearGradientPoint1.x);
+        floatToParam(values, floats, count, 3, paint->m_inputLinearGradientPoint1.y);
+        break;
+
+    case VG_PAINT_RADIAL_GRADIENT:
+        if(count > 5)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, paint->m_inputRadialGradientCenter.x);
+        floatToParam(values, floats, count, 1, paint->m_inputRadialGradientCenter.y);
+        floatToParam(values, floats, count, 2, paint->m_inputRadialGradientFocalPoint.x);
+        floatToParam(values, floats, count, 3, paint->m_inputRadialGradientFocalPoint.y);
+        floatToParam(values, floats, count, 4, paint->m_inputRadialGradientRadius);
+        break;
+
+    case VG_PAINT_PATTERN_TILING_MODE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, paint->m_patternTilingMode);
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getPathParameterifv(VGContext* context, Path* path, VGPathParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_PATH_FORMAT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, path->getFormat());
+        break;
+
+    case VG_PATH_DATATYPE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, path->getDatatype());
+        break;
+
+    case VG_PATH_SCALE:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, path->getScale());
+        break;
+
+    case VG_PATH_BIAS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        floatToParam(values, floats, count, 0, path->getBias());
+        break;
+
+    case VG_PATH_NUM_SEGMENTS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, path->getNumSegments());
+        break;
+
+    case VG_PATH_NUM_COORDS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, path->getNumCoordinates());
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getImageParameterifv(VGContext* context, Image* image, VGImageParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_IMAGE_FORMAT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        RI_ASSERT(isValidImageFormat(image->getDescriptor().vgFormat));
+        intToParam(values, floats, count, 0, image->getDescriptor().vgFormat);
+        break;
+
+    case VG_IMAGE_WIDTH:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, image->getWidth());
+        break;
+
+    case VG_IMAGE_HEIGHT:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, image->getHeight());
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void getFontParameterifv(VGContext* context, Font* font, VGFontParamType type, VGint count, void* values, bool floats)
+{
+    switch(type)
+    {
+    case VG_FONT_NUM_GLYPHS:
+        if(count > 1)	{ context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; }
+        intToParam(values, floats, count, 0, font->getNumGlyphs());
+        break;
+
+    default:
+        context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid VGParamType
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGfloat RI_APIENTRY vgGetParameterf(VGHandle object, VGint paramType)
+{
+    RI_GET_CONTEXT(0.0f);
+    RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT ||
+                paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, 0.0f);	//vector valued parameter
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0.0f);	//invalid object handle
+    VGfloat ret = 0.0f;
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, 1, &ret, true);
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, 1, &ret, true);
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, &ret, true);
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, 1, &ret, true);
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGint RI_APIENTRY vgGetParameteri(VGHandle object, VGint paramType)
+{
+    RI_GET_CONTEXT(0);
+    RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT ||
+                paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, 0);	//vector valued parameter
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0);	//invalid object handle
+    VGint ret = 0;
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, 1, &ret, false);
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, 1, &ret, false);
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, &ret, false);
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, 1, &ret, false);
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetParameterfv(VGHandle object, VGint paramType, VGint count, VGfloat * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count <= 0 || !values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid object handle
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, count, values, true);
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, count, values, true);
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, true);
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, count, values, true);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetParameteriv(VGHandle object, VGint paramType, VGint count, VGint * values)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(count <= 0 || !values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid object handle
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, count, values, false);
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, count, values, false);
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, false);
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, count, values, false);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGint RI_APIENTRY vgGetParameterVectorSize(VGHandle object, VGint paramType)
+{
+    RI_GET_CONTEXT(0);
+    bool isImage = context->isValidImage(object);
+    bool isPath = context->isValidPath(object);
+    bool isPaint = context->isValidPaint(object);
+    bool isFont = context->isValidFont(object);
+    RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0);	//invalid object handle
+    int ret = 0;
+    if(isImage)
+    {
+        RI_ASSERT(!isPath && !isPaint && !isFont);
+        switch(paramType)
+        {
+        case VG_IMAGE_FORMAT:
+        case VG_IMAGE_WIDTH:
+        case VG_IMAGE_HEIGHT:
+            ret = 1;
+            break;
+
+        default:
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid paramType
+            break;
+        }
+    }
+    else if(isPath)
+    {
+        RI_ASSERT(!isImage && !isPaint && !isFont);
+        switch(paramType)
+        {
+        case VG_PATH_FORMAT:
+        case VG_PATH_DATATYPE:
+        case VG_PATH_SCALE:
+        case VG_PATH_BIAS:
+        case VG_PATH_NUM_SEGMENTS:
+        case VG_PATH_NUM_COORDS:
+            ret = 1;
+            break;
+
+        default:
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid paramType
+            break;
+        }
+    }
+    else if(isPaint)
+    {
+        RI_ASSERT(!isImage && !isPath && !isFont);
+        switch(paramType)
+        {
+        case VG_PAINT_TYPE:
+        case VG_PAINT_COLOR_RAMP_SPREAD_MODE:
+        case VG_PAINT_PATTERN_TILING_MODE:
+            ret = 1;
+            break;
+
+        case VG_PAINT_COLOR:
+        case VG_PAINT_LINEAR_GRADIENT:
+            ret = 4;
+            break;
+
+        case VG_PAINT_COLOR_RAMP_STOPS:
+            ret = ((Paint*)object)->m_inputColorRampStops.size() * 5;
+            break;
+
+        case VG_PAINT_COLOR_RAMP_PREMULTIPLIED:
+            ret = 1;
+            break;
+
+        case VG_PAINT_RADIAL_GRADIENT:
+            ret = 5;
+            break;
+
+        default:
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid paramType
+            break;
+        }
+    }
+    else
+    {
+        RI_ASSERT(!isImage && !isPath && !isPaint && isFont);
+        switch(paramType)
+        {
+        case VG_FONT_NUM_GLYPHS:
+            ret = 1;
+            break;
+
+        default:
+            context->setError(VG_ILLEGAL_ARGUMENT_ERROR);	//invalid paramType
+            break;
+        }
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static Matrix3x3* getCurrentMatrix(VGContext* context)
+{
+    RI_ASSERT(context);
+    switch(context->m_matrixMode)
+    {
+    case VG_MATRIX_PATH_USER_TO_SURFACE:
+        return &context->m_pathUserToSurface;
+
+    case VG_MATRIX_IMAGE_USER_TO_SURFACE:
+        return &context->m_imageUserToSurface;
+
+    case VG_MATRIX_FILL_PAINT_TO_USER:
+        return &context->m_fillPaintToUser;
+
+    case VG_MATRIX_STROKE_PAINT_TO_USER:
+        return &context->m_strokePaintToUser;
+
+    default:
+        RI_ASSERT(context->m_matrixMode == VG_MATRIX_GLYPH_USER_TO_SURFACE);
+        return &context->m_glyphUserToSurface;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgLoadIdentity(void)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    Matrix3x3* d = getCurrentMatrix(context);
+    d->identity();
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgLoadMatrix(const VGfloat * m)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Matrix3x3* d = getCurrentMatrix(context);
+    d->set(inputFloat(m[0]), inputFloat(m[3]), inputFloat(m[6]),
+           inputFloat(m[1]), inputFloat(m[4]), inputFloat(m[7]),
+           inputFloat(m[2]), inputFloat(m[5]), inputFloat(m[8]));
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetMatrix(VGfloat * m)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Matrix3x3* d = getCurrentMatrix(context);
+    m[0] = (*d)[0][0];
+    m[1] = (*d)[1][0];
+    m[2] = (*d)[2][0];
+    m[3] = (*d)[0][1];
+    m[4] = (*d)[1][1];
+    m[5] = (*d)[2][1];
+    m[6] = (*d)[0][2];
+    m[7] = (*d)[1][2];
+    m[8] = (*d)[2][2];
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgMultMatrix(const VGfloat * m)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Matrix3x3 n(inputFloat(m[0]), inputFloat(m[3]), inputFloat(m[6]),
+                inputFloat(m[1]), inputFloat(m[4]), inputFloat(m[7]),
+                inputFloat(m[2]), inputFloat(m[5]), inputFloat(m[8]));
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+        n[2].set(0,0,1);
+
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgTranslate(VGfloat tx, VGfloat ty)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    Matrix3x3 n(1, 0, inputFloat(tx),
+                0, 1, inputFloat(ty),
+                0, 0, 1 );
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgScale(VGfloat sx, VGfloat sy)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    Matrix3x3 n(inputFloat(sx), 0,              0,
+                0,              inputFloat(sy), 0,
+                0,              0,              1 );
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgShear(VGfloat shx, VGfloat shy)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    Matrix3x3 n(1,               inputFloat(shx), 0,
+                inputFloat(shy), 1,               0,
+                0,               0,               1);
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgRotate(VGfloat angle)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RIfloat a = RI_DEG_TO_RAD(inputFloat(angle));
+    Matrix3x3 n((RIfloat)cos(a), -(RIfloat)sin(a), 0,
+                (RIfloat)sin(a),  (RIfloat)cos(a), 0,
+                0,              0,             1 );
+    Matrix3x3* d = getCurrentMatrix(context);
+    *d *= n;
+
+    d->validate();
+    //d->assertValid();
+
+    if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE)
+    {
+        (*d)[2].set(0,0,1);	//force affinity
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgMask(VGHandle mask, VGMaskOperation operation, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    const bool isImage = context->isValidImage(mask);
+    const bool isMaskLayer = context->isValidMaskLayer(mask);
+    const bool needInput = (operation != VG_CLEAR_MASK) && (operation != VG_FILL_MASK);
+    RI_IF_ERROR(operation != VG_CLEAR_MASK && operation != VG_FILL_MASK && !isImage && !isMaskLayer, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(operation != VG_CLEAR_MASK && operation != VG_FILL_MASK && isImage && eglvgIsInUse((Image*)mask), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(operation < VG_CLEAR_MASK || operation > VG_SUBTRACT_MASK, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    RI_IF_ERROR(isMaskLayer && drawable->getNumSamples() != ((Surface*)mask)->getNumSamples(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    if(!drawable || !drawable->getMaskBuffer())
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment or context has no mask buffer
+    }
+
+    if(isImage)
+        drawable->getMaskBuffer()->mask(context->getBlitter(), (Image*)mask, operation, x, y, width, height);
+    else
+    {
+        RI_ASSERT(!isMaskLayer ? !needInput : true);
+        drawable->getMaskBuffer()->mask(context->getBlitter(), (!mask || !needInput) ? NULL : ((Surface*)mask)->getImage(), operation, x, y, width, height);
+    }
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+void RI_APIENTRY vgRenderToMask(VGPath path, VGbitfield paintModes, VGMaskOperation operation)
+{
+    Path* iPath = (Path*)path;
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!paintModes || (paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+    RI_IF_ERROR(operation < VG_CLEAR_MASK || operation > VG_SUBTRACT_MASK, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* curr = context->getCurrentDrawable();
+    const Surface* mask = curr->getMaskBuffer();
+    if(!curr || !curr->getMaskBuffer())
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment or context has no mask buffer
+    }
+
+    if(operation == VG_CLEAR_MASK || operation == VG_FILL_MASK)
+    {
+        //RI_ASSERT(false); // should call fill!
+        Image* dummy = NULL;
+        curr->getMaskBuffer()->mask(context->getBlitter(), dummy, operation, 0, 0, curr->getWidth(), curr->getHeight());
+        RI_RETURN(RI_NO_RETVAL);
+    }
+
+    try
+    {
+        // Create a temporary image to render the path on for some mask operations.
+        // \todo tero: There are optimizations that can do all the mask operations in one pass, but it
+        // takes too much time to implement them now.
+        Drawable *tmpDrawable = NULL;
+        
+        try 
+        {
+            if (operation == VG_INTERSECT_MASK)
+            {
+                tmpDrawable = RI_NEW(Drawable, (Color::formatToDescriptor(VG_A_8), curr->getWidth(), curr->getHeight(), 1, 0));
+            }
+        } catch (std::bad_alloc e)
+        {
+            throw e;
+        }
+         
+        //Drawable drawable(Color::formatToDescriptor(VG_A_8), curr->getWidth(), curr->getHeight(), curr->getNumSamples(), 1);    //TODO 0 mask bits (mask buffer is not used)
+
+        Rasterizer& rasterizer = context->m_rasterizer;
+        rasterizer.clear();
+
+        rasterizer.setScissoring(context->m_scissoring ? true : false);
+        if(context->m_scissoring)
+            rasterizer.setScissor(context->m_scissor);	//throws bad_alloc
+
+        PixelPipe& pixelPipe = context->m_pixelPipe;
+
+        // \hack If the mask operation is intersect, we render normally to tempbuffer!
+        if (!tmpDrawable)
+            pixelPipe.setRenderToMask(true);
+        else
+            pixelPipe.setRenderToMask(false);
+
+        bool skipFill = false;
+
+        if (operation == VG_SET_MASK)
+        {
+            Surface *maskSurface = curr->getMaskBuffer();
+            maskSurface->clear(Color(), 0, 0, maskSurface->getWidth(), maskSurface->getHeight());
+            skipFill = true;
+        }
+
+        skipFill = skipFill && (paintModes & VG_STROKE_PATH);
+
+        pixelPipe.setMaskOperation(operation);
+        pixelPipe.setDrawable(tmpDrawable ? tmpDrawable : curr);
+        pixelPipe.setImage(NULL, VG_DRAW_IMAGE_NORMAL);
+        pixelPipe.setMask(false);
+        pixelPipe.setPaint(NULL);   //use default paint (solid color alpha = 1)
+        pixelPipe.setBlendMode(VG_BLEND_SRC_OVER);   //write solid color * coverage to dest
+        bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true;
+        rasterizer.setAntiAliasing(aa);
+
+        Matrix3x3 userToSurface = context->m_pathUserToSurface;
+        userToSurface[2].set(0,0,1);	//force affinity
+
+        if((paintModes & VG_FILL_PATH) && (!skipFill))
+        {
+            rasterizer.clear();
+            rasterizer.setup(0, 0, mask->getWidth(), mask->getHeight(), context->m_fillRule, &pixelPipe);
+            pixelPipe.prepareSpanUniforms(aa);
+            iPath->fill(userToSurface, rasterizer);	//throws bad_alloc
+            rasterizer.fill();	//throws bad_alloc
+            //curr->getMaskBuffer()->mask(drawable.getColorBuffer(), operation, 0, 0, drawable.getWidth(), drawable.getHeight());
+            if (tmpDrawable)
+            {
+                RI_ASSERT(operation == VG_INTERSECT_MASK);
+                curr->getMaskBuffer()->mask(context->getBlitter(), tmpDrawable->getColorBuffer()->getImage(), operation, 0, 0, tmpDrawable->getWidth(), tmpDrawable->getHeight());
+
+                if (paintModes & VG_STROKE_PATH)
+                {
+                    Surface* tmpSurf = tmpDrawable->getColorBuffer();
+                    tmpSurf->clear(Color(), 0, 0, 
+                        tmpSurf->getWidth(), tmpSurf->getHeight());
+                }
+                else
+                {
+                    RI_DELETE(tmpDrawable);
+                    tmpDrawable = NULL;
+                }
+            }
+
+        }
+
+        if((paintModes & VG_STROKE_PATH) && context->m_strokeLineWidth > 0.0f)
+        {
+            pixelPipe.prepareSpanUniforms(aa);
+            rasterizer.clear();
+            rasterizer.setup(0, 0, mask->getWidth(), mask->getHeight(), VG_NON_ZERO, &pixelPipe);
+
+            iPath->stroke(userToSurface, rasterizer, context->m_strokeDashPattern, context->m_strokeDashPhase, context->m_strokeDashPhaseReset ? true : false,
+                 context->m_strokeLineWidth, context->m_strokeCapStyle, context->m_strokeJoinStyle, RI_MAX(context->m_strokeMiterLimit, 1.0f));	//throws bad_alloc
+            rasterizer.fill();	//throws bad_alloc
+            //curr->getMaskBuffer()->mask(drawable.getColorBuffer(), operation, 0, 0, drawable.getWidth(), drawable.getHeight());
+
+            if (tmpDrawable)
+            {
+                RI_ASSERT(operation == VG_INTERSECT_MASK);
+                curr->getMaskBuffer()->mask(context->getBlitter(), tmpDrawable->getColorBuffer()->getImage(), operation, 0, 0, tmpDrawable->getWidth(), tmpDrawable->getHeight());
+                RI_DELETE(tmpDrawable);
+                tmpDrawable = NULL;
+            }
+        }
+        RI_ASSERT(!tmpDrawable);
+
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGMaskLayer RI_APIENTRY vgCreateMaskLayer(VGint width, VGint height)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(width > RI_MAX_IMAGE_WIDTH || height > RI_MAX_IMAGE_HEIGHT || width*height > RI_MAX_IMAGE_PIXELS ||
+                width*height > RI_MAX_IMAGE_BYTES, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    Drawable* curr = context->getCurrentDrawable();
+    if(!curr || !curr->getMaskBuffer())
+        RI_RETURN(VG_INVALID_HANDLE);   //no current drawing surface
+
+    Surface* layer = NULL;
+    try
+    {
+        layer = RI_NEW(Surface, (Color::formatToDescriptor(VG_A_8), width, height, curr->getNumSamples()));	//throws bad_alloc
+        RI_ASSERT(layer);
+        context->m_maskLayerManager->addResource(layer, context);	//throws bad_alloc
+        layer->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height);
+        RI_RETURN((VGMaskLayer)layer);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(layer);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyMaskLayer(VGMaskLayer maskLayer)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid handle
+
+    context->m_maskLayerManager->removeResource((Surface*)maskLayer);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgFillMaskLayer(VGMaskLayer maskLayer, VGint x, VGint y, VGint width, VGint height, VGfloat value)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid handle
+    RI_IF_ERROR(value < 0.0f || value > 1.0f, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Surface* layer = (Surface*)maskLayer;
+    RI_IF_ERROR(width <= 0 || height <= 0 || x < 0 || y < 0 || x > layer->getWidth()-width || y > layer->getHeight()-height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    layer->clear(Color(1,1,1,value,Color::sRGBA), x, y, width, height);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgCopyMask(VGMaskLayer maskLayer, VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid handle
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable || !drawable->getMaskBuffer())
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment or context has no mask buffer
+    }
+    Surface* layer = (Surface*)maskLayer;
+    RI_IF_ERROR(width <= 0 || height <= 0 || drawable->getNumSamples() != layer->getNumSamples(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {   //copy drawing surface mask to mask layer
+        // \note Removed support for msaa
+        layer->m_image->blit(context, drawable->getMaskBuffer()->getImage(), sx, sy, dx, dy, width, height);
+        //layer->blit(drawable->getMaskBuffer(), sx, sy, dx, dy, width, height);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgClear(VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+
+    try
+    {
+        if(context->m_scissoring)
+            drawable->getColorBuffer()->clear(context->m_clearColor, x, y, width, height, &context->m_scissor);	//throws bad_alloc
+        else
+            drawable->getColorBuffer()->clear(context->m_clearColor, x, y, width, height);
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGPath RI_APIENTRY vgCreatePath(VGint pathFormat, VGPathDatatype datatype, VGfloat scale, VGfloat bias, VGint segmentCapacityHint, VGint coordCapacityHint, VGbitfield capabilities)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(pathFormat != VG_PATH_FORMAT_STANDARD, VG_UNSUPPORTED_PATH_FORMAT_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(datatype < VG_PATH_DATATYPE_S_8 || datatype > VG_PATH_DATATYPE_F, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    RIfloat s = inputFloat(scale);
+    RIfloat b = inputFloat(bias);
+    RI_IF_ERROR(s == 0.0f, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    capabilities &= VG_PATH_CAPABILITY_ALL;	//undefined bits are ignored
+
+    Path* path = NULL;
+    try
+    {
+        path = RI_NEW(Path, (pathFormat, datatype, s, b, segmentCapacityHint, coordCapacityHint, capabilities));	//throws bad_alloc
+        RI_ASSERT(path);
+        context->m_pathManager->addResource(path, context);	//throws bad_alloc
+        RI_RETURN((VGPath)path);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(path);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgClearPath(VGPath path, VGbitfield capabilities)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    capabilities &= VG_PATH_CAPABILITY_ALL;	//undefined bits are ignored
+    ((Path*)path)->clear(capabilities);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyPath(VGPath path)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+
+    context->m_pathManager->removeResource((Path*)path);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgRemovePathCapabilities(VGPath path, VGbitfield capabilities)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    capabilities &= VG_PATH_CAPABILITY_ALL;	//undefined bits are ignored
+
+    VGbitfield caps = ((Path*)path)->getCapabilities();
+    caps &= ~capabilities;
+    ((Path*)path)->setCapabilities(caps);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGbitfield RI_APIENTRY vgGetPathCapabilities(VGPath path)
+{
+    RI_GET_CONTEXT(0);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, 0);	//invalid path handle
+    VGbitfield ret = ((Path*)path)->getCapabilities();
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgAppendPathData(VGPath dstPath, VGint numSegments, const VGubyte * pathSegments, const void * pathData)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(dstPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    Path* p = (Path*)dstPath;
+    RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_APPEND_TO), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//no append cap
+    RI_IF_ERROR(numSegments <= 0 || !pathSegments || !pathData, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//no segments or data
+    RI_IF_ERROR((p->getDatatype() == VG_PATH_DATATYPE_S_16 && !isAligned(pathData,2)) ||
+                ((p->getDatatype() == VG_PATH_DATATYPE_S_32 || p->getDatatype() == VG_PATH_DATATYPE_F) && !isAligned(pathData,4)),
+                VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid alignment
+    for(int i=0;i<numSegments;i++)
+    {
+        VGPathSegment c = (VGPathSegment)(pathSegments[i] & 0x1e);
+        RI_IF_ERROR(c < VG_CLOSE_PATH || c > VG_LCWARC_TO, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid segment
+        RI_IF_ERROR(c & ~0x1f, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//reserved bits are nonzero
+    }
+
+    try
+    {
+        p->appendData((const RIuint8*)pathSegments, numSegments, (const RIuint8*)pathData);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgModifyPathCoords(VGPath dstPath, VGint startIndex, VGint numSegments, const void * pathData)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(dstPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    Path* p = (Path*)dstPath;
+    RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_MODIFY), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//no modify cap
+    RI_IF_ERROR(!pathData || startIndex < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startIndex, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//no segments
+    RI_IF_ERROR((p->getDatatype() == VG_PATH_DATATYPE_S_16 && !isAligned(pathData,2)) ||
+                ((p->getDatatype() == VG_PATH_DATATYPE_S_32 || p->getDatatype() == VG_PATH_DATATYPE_F) && !isAligned(pathData,4)),
+                VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid alignment
+    p->modifyCoords(startIndex, numSegments, (const RIuint8*)pathData);
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgAppendPath(VGPath dstPath, VGPath srcPath)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(srcPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_APPEND_TO) ||
+                !(((Path*)srcPath)->getCapabilities() & VG_PATH_CAPABILITY_APPEND_FROM), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+
+    try
+    {
+        ((Path*)dstPath)->append((Path*)srcPath);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgTransformPath(VGPath dstPath, VGPath srcPath)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(srcPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_TRANSFORM_TO) ||
+                !(((Path*)srcPath)->getCapabilities() & VG_PATH_CAPABILITY_TRANSFORM_FROM), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+    try
+    {
+        ((Path*)dstPath)->transform((Path*)srcPath, context->m_pathUserToSurface);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static bool drawPath(VGContext* context, VGPath path, const Matrix3x3& userToSurfaceMatrix, VGbitfield paintModes)
+{
+    Path* iPath = (Path*)path;
+    //set up rendering surface and mask buffer
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+        return false;   //no EGL surface is current at the moment
+
+    Rasterizer& rasterizer = context->m_rasterizer;
+    rasterizer.clear();
+
+    if(context->m_scissoring)
+    {
+        rasterizer.setScissor(context->m_scissor);	//throws bad_alloc
+    }
+    rasterizer.setScissoring(context->m_scissoring ? true : false);
+
+    PixelPipe& pixelPipe = context->m_pixelPipe;
+    pixelPipe.setRenderToMask(false);
+    pixelPipe.setDrawable(drawable);
+    pixelPipe.setImage(NULL, VG_DRAW_IMAGE_NORMAL);
+    pixelPipe.setMask(context->m_masking ? true : false);
+    pixelPipe.setBlendMode(context->m_blendMode);
+    pixelPipe.setTileFillColor(context->m_tileFillColor);
+    pixelPipe.setImageQuality(context->m_imageQuality);
+    pixelPipe.setColorTransform(context->m_colorTransform ? true : false, context->m_colorTransformValues);
+    bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true;
+    rasterizer.setAntiAliasing(aa);
+
+    Matrix3x3 userToSurface = userToSurfaceMatrix;
+    userToSurface[2].set(0,0,1);	//force affinity
+
+    if(paintModes & VG_FILL_PATH)
+    {
+        // \todo Reorganize so that pipe.setpaint handles/requires the matrix setup?
+        pixelPipe.setPaint((Paint*)context->m_fillPaint);
+
+        Matrix3x3 paintToSurfaceMatrix = userToSurface * context->m_fillPaintToUser;
+        Matrix3x3 surfaceToPaintMatrix = paintToSurfaceMatrix; 
+        if(surfaceToPaintMatrix.invert())
+        {
+            surfaceToPaintMatrix[2].set(0,0,1);		//force affinity
+            pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+            pixelPipe.prepareSpanUniforms(aa);
+
+            rasterizer.clear();
+            rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), context->m_fillRule, &pixelPipe);
+            iPath->fill(userToSurface, rasterizer);	//throws bad_alloc
+            rasterizer.fill();	//throws bad_alloc
+        }
+    }
+
+    if(paintModes & VG_STROKE_PATH && context->m_strokeLineWidth > 0.0f)
+    {
+        pixelPipe.setPaint((Paint*)context->m_strokePaint);
+
+        Matrix3x3 paintToSurfaceMatrix = userToSurface * context->m_strokePaintToUser;
+        Matrix3x3 surfaceToPaintMatrix = paintToSurfaceMatrix; 
+        if(surfaceToPaintMatrix.invert())
+        {
+            surfaceToPaintMatrix[2].set(0,0,1);		//force affinity
+            pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+            pixelPipe.prepareSpanUniforms(aa);
+
+            rasterizer.clear();
+            rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_NON_ZERO, &pixelPipe);
+            iPath->stroke(userToSurface, rasterizer, context->m_strokeDashPattern, context->m_strokeDashPhase, context->m_strokeDashPhaseReset ? true : false,
+                 context->m_strokeLineWidth, context->m_strokeCapStyle, context->m_strokeJoinStyle, RI_MAX(context->m_strokeMiterLimit, 1.0f));	//throws bad_alloc
+            rasterizer.fill();	//throws bad_alloc
+
+        }
+    }
+    return true;
+}
+
+void RI_APIENTRY vgDrawPath(VGPath path, VGbitfield paintModes)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!paintModes || (paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+
+    try
+    {
+		eglvgLockSurface(0, 1);
+        if(!drawPath(context, path, context->m_pathUserToSurface, paintModes))
+        {
+			eglvgUnlockSurface();
+            RI_RETURN(RI_NO_RETVAL);
+        }
+		eglvgUnlockSurface();
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGfloat RI_APIENTRY vgPathLength(VGPath path, VGint startSegment, VGint numSegments)
+{
+    RI_GET_CONTEXT(-1.0f);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, -1.0f);	//invalid path handle
+    Path* p = (Path*)path;
+    RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_PATH_LENGTH), VG_PATH_CAPABILITY_ERROR, -1.0f);	//invalid caps
+    RI_IF_ERROR(startSegment < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startSegment, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, -1.0f);
+    RIfloat pathLength = -1.0f;
+    try
+    {
+        pathLength = p->getPathLength(startSegment, numSegments);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(pathLength);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgPointAlongPath(VGPath path, VGint startSegment, VGint numSegments, VGfloat distance, VGfloat * x, VGfloat * y, VGfloat * tangentX, VGfloat * tangentY)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    Path* p = (Path*)path;
+    RI_IF_ERROR((x && y && !(p->getCapabilities() & VG_PATH_CAPABILITY_POINT_ALONG_PATH)) ||
+                (tangentX && tangentY && !(p->getCapabilities() & VG_PATH_CAPABILITY_TANGENT_ALONG_PATH)), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+    RI_IF_ERROR(startSegment < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startSegment, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isAligned(x,4) || !isAligned(y,4) || !isAligned(tangentX,4) || !isAligned(tangentY,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {
+        Vector2 point, tangent;
+        p->getPointAlong(startSegment, numSegments, distance, point, tangent);	//throws bad_alloc
+        if(x && y)
+        {
+            *x = point.x;
+            *y = point.y;
+        }
+        if(tangentX && tangentY)
+        {
+            tangent.normalize();
+            *tangentX = tangent.x;
+            *tangentY = tangent.y;
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgPathBounds(VGPath path, VGfloat * minx, VGfloat * miny, VGfloat * width, VGfloat * height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)path)->getCapabilities() & VG_PATH_CAPABILITY_PATH_BOUNDS), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+    RI_IF_ERROR(!minx || !miny || !width || !height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isAligned(minx,4) || !isAligned(miny,4) || !isAligned(width,4) || !isAligned(height,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {
+        RIfloat pminx,pminy,pmaxx,pmaxy;
+        ((Path*)path)->getPathBounds(pminx, pminy, pmaxx, pmaxy);	//throws bad_alloc
+        *minx = pminx;
+        *miny = pminy;
+        *width = pmaxx - pminx;
+        *height = pmaxy - pminy;
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgPathTransformedBounds(VGPath path, VGfloat * minx, VGfloat * miny, VGfloat * width, VGfloat * height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)path)->getCapabilities() & VG_PATH_CAPABILITY_PATH_TRANSFORMED_BOUNDS), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL);	//invalid caps
+    RI_IF_ERROR(!minx || !miny || !width || !height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isAligned(minx,4) || !isAligned(miny,4) || !isAligned(width,4) || !isAligned(height,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {
+        RIfloat pminx, pminy, pmaxx, pmaxy;
+        ((Path*)path)->getPathTransformedBounds(context->m_pathUserToSurface, pminx, pminy, pmaxx, pmaxy);	//throws bad_alloc
+        *minx = pminx;
+        *miny = pminy;
+        *width = pmaxx - pminx;
+        *height = pmaxy - pminy;
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGboolean RI_APIENTRY vgInterpolatePath(VGPath dstPath, VGPath startPath, VGPath endPath, VGfloat amount)
+{
+    RI_GET_CONTEXT(VG_FALSE);
+    RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(startPath) || !context->isValidPath(endPath), VG_BAD_HANDLE_ERROR, VG_FALSE);	//invalid path handle
+    RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_TO) ||
+                !(((Path*)startPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_FROM) ||
+                !(((Path*)endPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_FROM), VG_PATH_CAPABILITY_ERROR, VG_FALSE);	//invalid caps
+    VGboolean ret = VG_FALSE;
+    try
+    {
+        if(((Path*)dstPath)->interpolate((const Path*)startPath, (const Path*)endPath, inputFloat(amount)))	//throws bad_alloc
+            ret = VG_TRUE;
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGPaint RI_APIENTRY vgCreatePaint(void)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    Paint* paint = NULL;
+    RI_TRACE("\n***** vgCreatePaint\n");
+    try
+    {
+        paint = RI_NEW(Paint, ());	//throws bad_alloc
+        RI_ASSERT(paint);
+        context->m_paintManager->addResource(paint, context);	//throws bad_alloc
+        RI_TRACE("===== vgCreatePaint: Created paint obj: %x\n", (int)paint);
+        RI_RETURN((VGPaint)paint);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(paint);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyPaint(VGPaint paint)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid paint handle
+
+    context->m_paintManager->removeResource((Paint*)paint);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetPaint(VGPaint paint, VGbitfield paintModes)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_TRACE("\n***** vgSetPaint: %x mode: %d\n", (int)paint, (int)paintModes);
+    RI_IF_ERROR(paint && !context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid paint handle
+    RI_IF_ERROR(!paintModes || paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+
+    context->releasePaint(paintModes);
+
+    if(paintModes & VG_FILL_PATH)
+    {
+        if(paint)
+            ((Paint*)paint)->addReference();
+        context->m_fillPaint = paint;
+    }
+    if(paintModes & VG_STROKE_PATH)
+    {
+        if(paint)
+            ((Paint*)paint)->addReference();
+        context->m_strokePaint = paint;
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetColor(VGPaint paint, VGuint rgba)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_TRACE("\n***** vgSetColor: %x, rgba: %x\n", paint, rgba);
+    RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid paint handle
+    Paint* p = (Paint*)paint;
+    p->m_inputPaintColor.unpack(rgba, Color::formatToDescriptor(VG_sRGBA_8888));
+    p->setColor(inputColor(p->m_inputPaintColor));
+    RI_TRACE("** -> [%.3f %.3f %.3f %.3f]\n", p->m_paintColor.r, p->m_paintColor.g, p->m_paintColor.b, p->m_paintColor.a);
+//    p->m_paintColor = inputColor(p->m_inputPaintColor);
+//    p->m_paintColor.clamp();
+//    p->m_paintColor.premultiply();
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGuint RI_APIENTRY vgGetColor(VGPaint paint)
+{
+    RI_GET_CONTEXT(0);
+    RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, 0);	//invalid paint handle
+    Color tempColor = ((Paint*)paint)->m_inputPaintColor;
+    tempColor.clamp();
+    unsigned int ret = tempColor.pack(Color::formatToDescriptor(VG_sRGBA_8888));
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGPaint RI_APIENTRY vgGetPaint(VGPaintMode paintMode)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(paintMode != VG_FILL_PATH && paintMode != VG_STROKE_PATH, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);	//invalid paint mode
+
+    if(paintMode == VG_FILL_PATH)
+    {
+        RI_RETURN(context->m_fillPaint);
+    }
+    RI_RETURN(context->m_strokePaint);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgPaintPattern(VGPaint paint, VGImage image)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidPaint(paint) || (image != VG_INVALID_HANDLE && !context->isValidImage(image)), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid handle
+    Image* img = (Image*)image;
+    Paint* pnt = (Paint*)paint;
+    RI_IF_ERROR(image != VG_INVALID_HANDLE && eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    Image* pattern = pnt->m_pattern;
+    if(pattern)
+    {
+        pattern->removeInUse();
+        if(!pattern->removeReference())
+            RI_DELETE(pattern);
+    }
+    pnt->m_pattern = img;
+
+    if(img)
+    {
+        img->addReference();
+        img->addInUse();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGImage RI_APIENTRY vgCreateImage(VGImageFormat format, VGint width, VGint height, VGbitfield allowedQuality)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(!isValidImageFormat(format), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(width <= 0 || height <= 0 || !allowedQuality ||
+                (allowedQuality & ~(VG_IMAGE_QUALITY_NONANTIALIASED | VG_IMAGE_QUALITY_FASTER | VG_IMAGE_QUALITY_BETTER)), VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(width > RI_MAX_IMAGE_WIDTH || height > RI_MAX_IMAGE_HEIGHT || width*height > RI_MAX_IMAGE_PIXELS ||
+                ((width*Color::formatToDescriptor(format).bitsPerPixel+7)/8)*height > RI_MAX_IMAGE_BYTES, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+
+    Image* image = NULL;
+    try
+    {
+        image = RI_NEW(Image, (Color::formatToDescriptor(format), width, height, allowedQuality));	//throws bad_alloc
+        RI_ASSERT(image);
+        context->m_imageManager->addResource(image, context);	//throws bad_alloc
+        RI_RETURN((VGImage)image);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(image);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyImage(VGImage image)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid image handle
+
+    context->m_imageManager->removeResource((Image*)image);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgClearImage(VGImage image, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* img = (Image*)image;
+    RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+	eglvgLockSurface(0, 1);
+    img->clear(context->m_clearColor, x, y, width, height);
+	eglvgUnlockSurface();
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgImageSubData(VGImage image, const void * data, VGint dataStride, VGImageFormat dataFormat, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* img = (Image*)image;
+    RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    {
+        Image input(Color::formatToDescriptor(dataFormat), width, height, dataStride, const_cast<RIuint8*>((const RIuint8*)data));
+        input.addReference();
+        try
+        {
+            img->blit(context, &input, 0, 0, x, y, width, height);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+        }
+        input.removeReference();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetImageSubData(VGImage image, void * data, VGint dataStride, VGImageFormat dataFormat, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* img = (Image*)image;
+    RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    {
+        Image output(Color::formatToDescriptor(dataFormat), width, height, dataStride, (RIuint8*)data);
+        output.addReference();
+        try
+        {
+            output.blit(context, img, x, y, 0, 0, width, height);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+        }
+        output.removeReference();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGImage RI_APIENTRY vgChildImage(VGImage parent, VGint x, VGint y, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(!context->isValidImage(parent), VG_BAD_HANDLE_ERROR, VG_INVALID_HANDLE);
+    Image* p = (Image*)parent;
+    RI_IF_ERROR(eglvgIsInUse((Image*)parent), VG_IMAGE_IN_USE_ERROR, VG_INVALID_HANDLE);
+    RI_IF_ERROR(x < 0 || x >= p->getWidth() || y < 0 || y >= p->getHeight() ||
+                width <= 0 || height <= 0 || RI_INT_ADDSATURATE(x, width) > p->getWidth() || RI_INT_ADDSATURATE(y, height) > p->getHeight(), VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+
+    Image* child = NULL;
+    try
+    {
+        child = RI_NEW(Image, (p, x, y, width, height));	//throws bad_alloc
+        RI_ASSERT(child);
+        context->m_imageManager->addResource(child, context);	//throws bad_alloc
+        RI_RETURN((VGImage)child);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(child);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGImage RI_APIENTRY vgGetParent(VGImage image)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, VG_INVALID_HANDLE);
+    VGImage ret = image;	//if image has no ancestors, image is returned.
+
+    //The vgGetParent function returns the closest valid ancestor (i.e., one that has not been the target of a vgDestroyImage call)
+    // of the given image.
+    Image* im = ((Image*)image)->getParent();
+    for(;im;im = im->getParent())
+    {
+        if(context->isValidImage((VGImage)im))
+        {	//the parent is valid and alive
+            ret = (VGImage)im;
+            break;
+        }
+    }
+    RI_RETURN(ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgCopyImage(VGImage dst, VGint dx, VGint dy, VGImage src, VGint sx, VGint sy, VGint width, VGint height, VGboolean dither)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(eglvgIsInUse((Image*)dst) || eglvgIsInUse((Image*)src), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    try
+    {
+        ((Image*)dst)->blit(context, (Image*)src, sx, sy, dx, dy, width, height, NULL, dither ? true : false);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+ 
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static bool drawImage(VGContext* context, VGImage image, const Matrix3x3& userToSurfaceMatrix)
+{
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+        return false;   //no EGL surface is current at the moment
+
+    Image* img = (Image*)image;
+    //transform image corners into the surface space
+    Vector3 p0(0, 0, 1);
+    Vector3 p1(0, (RIfloat)img->getHeight(), 1);
+    Vector3 p2((RIfloat)img->getWidth(), (RIfloat)img->getHeight(), 1);
+    Vector3 p3((RIfloat)img->getWidth(), 0, 1);
+    p0 = userToSurfaceMatrix * p0;
+    p1 = userToSurfaceMatrix * p1;
+    p2 = userToSurfaceMatrix * p2;
+    p3 = userToSurfaceMatrix * p3;
+    if(p0.z <= 0.0f || p1.z <= 0.0f || p2.z <= 0.0f || p3.z <= 0.0f)
+        return false;
+
+    //projection
+    p0 *= 1.0f/p0.z;
+    p1 *= 1.0f/p1.z;
+    p2 *= 1.0f/p2.z;
+    p3 *= 1.0f/p3.z;
+
+    Rasterizer& rasterizer = context->m_rasterizer;
+    rasterizer.clear();
+
+    rasterizer.setScissoring(context->m_scissoring ? true : false);
+    if(context->m_scissoring)
+        rasterizer.setScissor(context->m_scissor);	//throws bad_alloc
+
+    PixelPipe& pixelPipe = context->m_pixelPipe;
+    pixelPipe.setTileFillColor(context->m_tileFillColor);
+    pixelPipe.setPaint((Paint*)context->m_fillPaint);
+    pixelPipe.setImageQuality(context->m_imageQuality);
+    pixelPipe.setBlendMode(context->m_blendMode);
+    pixelPipe.setRenderToMask(false);
+    pixelPipe.setDrawable(drawable);
+    pixelPipe.setMask(context->m_masking ? true : false);
+    pixelPipe.setColorTransform(context->m_colorTransform ? true : false, context->m_colorTransformValues);
+    const bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true;
+    rasterizer.setAntiAliasing(aa);
+
+    Matrix3x3 surfaceToImageMatrix = userToSurfaceMatrix;
+    Matrix3x3 surfaceToPaintMatrix = userToSurfaceMatrix * context->m_fillPaintToUser;
+    if(surfaceToImageMatrix.invert() && surfaceToPaintMatrix.invert())
+    {
+        VGImageMode imode = context->m_imageMode;
+        if(!surfaceToPaintMatrix.isAffine())
+            imode = VG_DRAW_IMAGE_NORMAL;	//if paint matrix is not affine, always use normal image mode
+        surfaceToPaintMatrix[2].set(0,0,1);	//force affine
+
+        pixelPipe.setImage(img, imode);
+        pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+        pixelPipe.setSurfaceToImageMatrix(surfaceToImageMatrix);
+        pixelPipe.prepareSpanUniforms(aa);
+        rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_EVEN_ODD, &pixelPipe);
+
+        rasterizer.addEdge(Vector2(p0.x,p0.y), Vector2(p1.x,p1.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p1.x,p1.y), Vector2(p2.x,p2.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p2.x,p2.y), Vector2(p3.x,p3.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p3.x,p3.y), Vector2(p0.x,p0.y));	//throws bad_alloc
+
+        rasterizer.fill();	//throws bad_alloc
+    }
+    return true;
+}
+
+void RI_APIENTRY vgDrawImage(VGImage image)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* img = (Image*)image;
+    RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+
+    try
+    {
+        if(!drawImage(context, image, context->m_imageUserToSurface))
+        {
+            RI_RETURN(RI_NO_RETVAL);
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetPixels(VGint dx, VGint dy, VGImage src, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(eglvgIsInUse((Image*)src), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+
+    Drawable* drawable = context->getCurrentDrawable();
+    Array<OpenVGRI::Rectangle>* scissors = !context->m_scissoring ? NULL : &context->m_scissor;
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    try
+    {
+        drawable->getColorBuffer()->m_image->blit(context, (Image*)src, sx, sy, dx, dy, width, height, scissors, false);	//throws bad_alloc
+        //drawable->getColorBuffer()->blit(*(Image*)src, sx, sy, dx, dy, width, height);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgWritePixels(const void * data, VGint dataStride, VGImageFormat dataFormat, VGint dx, VGint dy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    {
+        Array<OpenVGRI::Rectangle>* scissors = !context->m_scissoring ? NULL : &context->m_scissor;
+        Image input(Color::formatToDescriptor(dataFormat), width, height, dataStride, const_cast<RIuint8*>((const RIuint8*)data));
+        input.addReference();
+        try
+        {
+            drawable->getColorBuffer()->m_image->blit(context, &input, 0, 0, dx, dy, width, height, scissors, false);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+            // TEROP: out-of-mem?
+        }
+        input.removeReference();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGetPixels(VGImage dst, VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(eglvgIsInUse((Image*)dst), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    try
+    {
+        ((Image*)dst)->blit(context, drawable->getColorBuffer()->m_image, sx, sy, dx, dy, width, height);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgReadPixels(void* data, VGint dataStride, VGImageFormat dataFormat, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    {
+        Image output(Color::formatToDescriptor(dataFormat), width, height, dataStride, (RIuint8*)data);
+        output.addReference();
+        try
+        {
+            output.blit(context, drawable->getColorBuffer()->m_image, sx, sy, 0, 0, width, height);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+        }
+        output.removeReference();
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgCopyPixels(VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Drawable* drawable = context->getCurrentDrawable();
+    Array<OpenVGRI::Rectangle>* scissors = !context->m_scissoring ? NULL : &context->m_scissor;
+    if(!drawable)
+    {
+        RI_RETURN(RI_NO_RETVAL);	//no EGL surface is current at the moment
+    }
+    try
+    {
+        drawable->getColorBuffer()->m_image->blit(context, drawable->getColorBuffer()->m_image, sx, sy, dx, dy, width, height, scissors, false);	//throws bad_alloc
+        //drawable->getColorBuffer()->blit(drawable->getColorBuffer(), sx, sy, dx, dy, width, height);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgColorMatrix(VGImage dst, VGImage src, const VGfloat * matrix)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!matrix || !isAligned(matrix,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+
+    RIfloat m[20];
+    for(int i=0;i<20;i++)
+    {
+        m[i] = inputFloat(matrix[i]);
+    }
+    try
+    {
+        d->colorMatrix(*s, m, context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgConvolve(VGImage dst, VGImage src, VGint kernelWidth, VGint kernelHeight, VGint shiftX, VGint shiftY, const VGshort * kernel, VGfloat scale, VGfloat bias, VGTilingMode tilingMode)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!kernel || !isAligned(kernel,2) || kernelWidth <= 0 || kernelHeight <= 0 || kernelWidth > RI_MAX_KERNEL_SIZE || kernelHeight > RI_MAX_KERNEL_SIZE, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->convolve(*s, kernelWidth, kernelHeight, shiftX, shiftY, (const RIint16*)kernel, inputFloat(scale), inputFloat(bias), tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSeparableConvolve(VGImage dst, VGImage src, VGint kernelWidth, VGint kernelHeight, VGint shiftX, VGint shiftY, const VGshort * kernelX, const VGshort * kernelY, VGfloat scale, VGfloat bias, VGTilingMode tilingMode)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!kernelX || !kernelY || !isAligned(kernelX,2) || !isAligned(kernelY,2) || kernelWidth <= 0 || kernelHeight <= 0 || kernelWidth > RI_MAX_SEPARABLE_KERNEL_SIZE || kernelHeight > RI_MAX_SEPARABLE_KERNEL_SIZE, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->separableConvolve(*s, kernelWidth, kernelHeight, shiftX, shiftY, (const RIint16*)kernelX, (const RIint16*)kernelY,
+                                         inputFloat(scale), inputFloat(bias), tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false,
+                                         context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgGaussianBlur(VGImage dst, VGImage src, VGfloat stdDeviationX, VGfloat stdDeviationY, VGTilingMode tilingMode)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RIfloat sx = inputFloat(stdDeviationX);
+    RIfloat sy = inputFloat(stdDeviationY);
+    RI_IF_ERROR(sx <= 0.0f || sy <= 0.0f || sx > (RIfloat)RI_MAX_GAUSSIAN_STD_DEVIATION || sy > (RIfloat)RI_MAX_GAUSSIAN_STD_DEVIATION, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->gaussianBlur(*s, sx, sy, tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false,
+                        context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgLookup(VGImage dst, VGImage src, const VGubyte * redLUT, const VGubyte * greenLUT, const VGubyte * blueLUT, const VGubyte * alphaLUT, VGboolean outputLinear, VGboolean outputPremultiplied)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!redLUT || !greenLUT || !blueLUT || !alphaLUT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->lookup(*s, (const RIuint8*)redLUT, (const RIuint8*)greenLUT, (const RIuint8*)blueLUT, (const RIuint8*)alphaLUT,
+                  outputLinear ? true : false, outputPremultiplied ? true : false, context->m_filterFormatLinear ? true : false,
+                  context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgLookupSingle(VGImage dst, VGImage src, const VGuint * lookupTable, VGImageChannel sourceChannel, VGboolean outputLinear, VGboolean outputPremultiplied)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);
+    Image* d = (Image*)dst;
+    Image* s = (Image*)src;
+    RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(!lookupTable || !isAligned(lookupTable,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    const Color::Descriptor& desc = s->getDescriptor();
+    RI_ASSERT(Color::isValidDescriptor(desc));
+    //give an error if src is in rgb format and the source channel is not valid
+    RI_IF_ERROR((!desc.isLuminance() && !desc.isAlphaOnly()) && (sourceChannel != VG_RED && sourceChannel != VG_GREEN && sourceChannel != VG_BLUE && sourceChannel != VG_ALPHA), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA);	//undefined bits are ignored
+    try
+    {
+        d->lookupSingle(*s, (const RIuint32*)lookupTable, sourceChannel, outputLinear ? true : false, outputPremultiplied ? true : false,
+                        context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask);
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGHardwareQueryResult RI_APIENTRY vgHardwareQuery(VGHardwareQueryType key, VGint setting)
+{
+    RI_GET_CONTEXT(VG_HARDWARE_UNACCELERATED);
+    RI_IF_ERROR(key != VG_IMAGE_FORMAT_QUERY && key != VG_PATH_DATATYPE_QUERY, VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED);
+    RI_IF_ERROR(key == VG_IMAGE_FORMAT_QUERY && !isValidImageFormat(setting), VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED);
+    RI_IF_ERROR(key == VG_PATH_DATATYPE_QUERY && (setting < VG_PATH_DATATYPE_S_8 || setting > VG_PATH_DATATYPE_F), VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED);
+    RI_RETURN(VG_HARDWARE_UNACCELERATED);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+     
+const VGubyte * RI_APIENTRY vgGetString(VGStringID name)
+{
+    static const VGubyte vendor[] = "Nokia";
+    static const VGubyte renderer[] = {"OpenVG 1.1 Faster Reference Implementation May 13 2008"};
+    static const VGubyte version[] = "1.1";
+    static const VGubyte extensions[] = "";
+    const VGubyte* r = NULL;
+    RI_GET_CONTEXT(NULL);
+    switch(name)
+    {
+    case VG_VENDOR:
+        r = vendor;
+        break;
+    case VG_RENDERER:
+        r = renderer;
+        break;
+    case VG_VERSION:
+        r = version;
+        break;
+    case VG_EXTENSIONS:
+        r = extensions;
+        break;
+    default:
+        break;
+    }
+    RI_RETURN(r);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGFont RI_APIENTRY vgCreateFont(VGint glyphCapacityHint)
+{
+    RI_GET_CONTEXT(VG_INVALID_HANDLE);
+    RI_IF_ERROR(glyphCapacityHint < 0, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE);
+
+    Font* font = NULL;
+    try
+    {
+        font = RI_NEW(Font, (glyphCapacityHint));	//throws bad_alloc
+        RI_ASSERT(font);
+        context->m_fontManager->addResource(font, context);	//throws bad_alloc
+        RI_RETURN((VGFont)font);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(font);
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+        RI_RETURN(VG_INVALID_HANDLE);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDestroyFont(VGFont font)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+
+    context->m_fontManager->removeResource((Font*)font);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetGlyphToPath(VGFont font, VGuint glyphIndex, VGPath path, VGboolean isHinted, const VGfloat glyphOrigin[2], const VGfloat escapement[2])
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    RI_IF_ERROR(path != VG_INVALID_HANDLE && !context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid path handle
+    RI_IF_ERROR(!glyphOrigin || !escapement || !isAligned(glyphOrigin,sizeof(VGfloat)) || !isAligned(escapement,sizeof(VGfloat)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Font* f = (Font*)font;
+
+    try
+    {
+        f->setGlyphToPath(glyphIndex, path, isHinted ? true : false, Vector2(inputFloat(glyphOrigin[0]), inputFloat(glyphOrigin[1])), Vector2(inputFloat(escapement[0]), inputFloat(escapement[1])));
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgSetGlyphToImage(VGFont font, VGuint glyphIndex, VGImage image, const VGfloat glyphOrigin[2], const VGfloat escapement[2])
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    if(image != VG_INVALID_HANDLE)
+    {
+        RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid image handle
+        RI_IF_ERROR(eglvgIsInUse((Image*)image), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); //image in use
+    }
+    RI_IF_ERROR(!glyphOrigin || !escapement || !isAligned(glyphOrigin,sizeof(VGfloat)) || !isAligned(escapement,sizeof(VGfloat)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    Font* f = (Font*)font;
+
+    try
+    {
+        f->setGlyphToImage(glyphIndex, image, Vector2(inputFloat(glyphOrigin[0]), inputFloat(glyphOrigin[1])), Vector2(inputFloat(escapement[0]), inputFloat(escapement[1])));
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgClearGlyph(VGFont font, VGuint glyphIndex)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    Font* f = (Font*)font;
+    Font::Glyph* g = f->findGlyph(glyphIndex);
+    RI_IF_ERROR(!g, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);   //glyphIndex not defined
+
+    f->clearGlyph(g);
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDrawGlyph(VGFont font, VGuint glyphIndex, VGbitfield paintModes, VGboolean allowAutoHinting)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    RI_IF_ERROR(paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+    Font* f = (Font*)font;
+    Font::Glyph* g = f->findGlyph(glyphIndex);
+    RI_IF_ERROR(!g, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);   //glyphIndex not defined
+    RI_UNREF(allowAutoHinting); //RI doesn't implement autohinting
+
+    try
+    {
+        if(paintModes)
+        {
+            Matrix3x3 userToSurfaceMatrix = context->m_glyphUserToSurface;
+            Vector2 t = context->m_glyphOrigin - g->m_origin;
+            Matrix3x3 n(1, 0, t.x,
+                        0, 1, t.y,
+                        0, 0, 1 );
+            userToSurfaceMatrix *= n;
+            userToSurfaceMatrix[2].set(0,0,1);		//force affinity
+
+            bool ret = true;
+			eglvgLockSurface(0, 1);
+            if(g->m_image != VG_INVALID_HANDLE)
+                ret = drawImage(context, g->m_image, userToSurfaceMatrix);
+            else if(g->m_path != VG_INVALID_HANDLE)
+                ret = drawPath(context, g->m_path, userToSurfaceMatrix, paintModes);
+			eglvgUnlockSurface();
+            if(!ret)
+            {
+                RI_RETURN(RI_NO_RETVAL);
+            }
+        }
+
+        context->m_glyphOrigin += g->m_escapement;
+        context->m_inputGlyphOrigin = context->m_glyphOrigin;
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+
+    RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void RI_APIENTRY vgDrawGlyphs(VGFont font, VGint glyphCount, const VGuint *glyphIndices, const VGfloat *adjustments_x, const VGfloat *adjustments_y, VGbitfield paintModes, VGboolean allowAutoHinting)
+{
+    RI_GET_CONTEXT(RI_NO_RETVAL);
+    RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL);	//invalid font handle
+    RI_IF_ERROR(!glyphIndices || !isAligned(glyphIndices, sizeof(VGuint)) || glyphCount <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR((adjustments_x && !isAligned(adjustments_x, sizeof(VGfloat))) || (adjustments_y && !isAligned(adjustments_y, sizeof(VGfloat))), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);
+    RI_IF_ERROR(paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);	//invalid paint mode
+    Font* f = (Font*)font;
+    for(int i=0;i<glyphCount;i++)
+    {
+        Font::Glyph* g = f->findGlyph(glyphIndices[i]);
+        RI_IF_ERROR(!g, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL);   //glyphIndex not defined
+    }
+    RI_UNREF(allowAutoHinting); //RI doesn't implement autohinting
+
+    try
+    {
+        for(int i=0;i<glyphCount;i++)
+        {
+            Font::Glyph* g = f->findGlyph(glyphIndices[i]);
+
+            if(paintModes)
+            {
+                Matrix3x3 userToSurfaceMatrix = context->m_glyphUserToSurface;
+                Vector2 t = context->m_glyphOrigin - g->m_origin;
+                Matrix3x3 n(1, 0, t.x,
+                            0, 1, t.y,
+                            0, 0, 1 );
+                userToSurfaceMatrix *= n;
+                userToSurfaceMatrix[2].set(0,0,1);		//force affinity
+
+                bool ret = true;
+                if(g->m_image != VG_INVALID_HANDLE)
+                    ret = drawImage(context, g->m_image, userToSurfaceMatrix);
+                else if(g->m_path != VG_INVALID_HANDLE)
+                    ret = drawPath(context, g->m_path, userToSurfaceMatrix, paintModes);
+                if(!ret)
+                {
+                    RI_RETURN(RI_NO_RETVAL);
+                }
+            }
+
+            context->m_glyphOrigin += g->m_escapement;
+            if(adjustments_x)
+                context->m_glyphOrigin.x += inputFloat(adjustments_x[i]);
+            if(adjustments_y)
+                context->m_glyphOrigin.y += inputFloat(adjustments_y[i]);
+            context->m_inputGlyphOrigin = context->m_glyphOrigin;
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        context->setError(VG_OUT_OF_MEMORY_ERROR);
+    }
+	RI_RETURN(RI_NO_RETVAL);
+}
+
+VGint vgePathCoordsSizeInBytes(VGPath path, VGint startIndex, VGint numSegments)
+{
+    RI_GET_CONTEXT( 0 );
+    RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, 0);
+    VGint ret = ((OpenVGRI::Path*)path)->coordsSizeInBytes( startIndex, numSegments );
+    RI_RETURN(ret);
+}
+
+
+VGImage vgCreateEGLImageTargetKHR(VGeglImageKHR image)
+{
+#if defined(USE_FULL_EGL)
+    RI_GET_CONTEXT( 0 );
+    VGImage ret;
+    OpenVGRI::Color::Descriptor desc;
+    OpenVGRI::RIuint8* data;
+    // Get data for VGImage
+    int width;
+    int height;
+    int stride;
+
+    eglvgGetImageDescriptor( image, desc, width, height, stride );
+    // There is some error.
+    // EGLImage is null or EGLImage target is EGL_VG_PARENT_IMAGE_KHR.
+    RI_IF_ERROR(!width || !height || !stride, VG_ILLEGAL_ARGUMENT_ERROR, NULL);
+    // Data is created in EGLImage class.
+    data = (OpenVGRI::RIuint8*)eglvgGetImageData( image );    
+    // Create VGImage
+    // allowedQuality = VG_IMAGE_QUALITY_NONANTIALIASED | VG_IMAGE_QUALITY_FASTER | VG_IMAGE_QUALITY_BETTER
+    ret = vgCreateImage( desc.vgFormat, width, height, VG_IMAGE_QUALITY_NONANTIALIASED );
+    // If VGImage is not created raise error and return null
+    RI_IF_ERROR(!ret, VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, NULL);
+    // Set data for VGImage.
+    // This will copy that data-object.
+    vgImageSubData( ret, 
+                    data, 
+                    stride, 
+                    desc.vgFormat, 
+                    0, 
+                    0,
+                    width, 
+                    height);
+    // Return VGImage
+    RI_RETURN(ret);
+#else
+    (void)image;
+    return VG_INVALID_HANDLE;
+#endif //USE_FULL_EGL
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riArray.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,242 @@
+#ifndef __RIARRAY_H
+#define __RIARRAY_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Array class.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIDEFS_H
+#include "riDefs.h"
+#endif
+
+#include <string.h>	//for memcpy
+
+namespace OpenVGRI
+{
+
+//=======================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \brief	An array class similar to std::vector.
+* \param
+* \return
+* \note		Follows std::vector's naming convention (except resizeAndReallocate).
+*//*-------------------------------------------------------------------*/
+
+template <class Item> class Array
+{
+public:
+    friend class Rasterizer;
+
+    Array() : m_array(NULL), m_size(0), m_allocated(0) {}	//throws bad_alloc
+    ~Array()
+    {
+        RI_DELETE_ARRAY(m_array);
+    }
+
+    void		swap(Array& s)
+    {
+        Item* tarray = m_array;
+        m_array = s.m_array;
+        s.m_array = tarray;
+
+        int tsize = m_size;
+        m_size = s.m_size;
+        s.m_size = tsize;
+
+        int tallocated = m_allocated;
+        m_allocated = s.m_allocated;
+        s.m_allocated = tallocated;
+    }
+
+    //if more room is needed, reallocate, otherwise return
+    void		reserve( int items )	//throws bad_alloc
+    {
+        RI_ASSERT( items >= 0 );
+        if( items <= m_allocated )
+            return;	//if there is room already, return
+
+        RI_ASSERT( items > m_allocated );
+
+        Item* newa = RI_NEW_ARRAY(Item, items);	//throws bad_alloc if runs out of memory
+        for(int i=0;i<m_size;i++)
+            newa[i] = m_array[i];
+        RI_DELETE_ARRAY(m_array);
+        m_array = newa;
+        m_allocated = items;
+        //doesn't change size
+    }
+
+    //reserve and change size
+    void		resize( int items )	//throws bad_alloc
+    {
+        reserve( items );	//throws bad_alloc if runs out of memory
+        m_size = items;
+    }
+
+    //resize and allocate exactly the correct amount of memory
+    void		resizeAndReallocate( int items )	//throws bad_alloc
+    {
+        RI_ASSERT( items >= 0 );
+        if( items == m_allocated )
+        {
+            m_size = items;
+            return;
+        }
+
+        if( items == 0 )
+        {
+            RI_DELETE_ARRAY(m_array);
+            m_size = 0;
+            m_allocated = 0;
+            return;
+        }
+
+        Item* newa = RI_NEW_ARRAY(Item, items);	//throws bad_alloc if runs out of memory
+        int copySize = (m_size < items) ? m_size : items;	//min(m_size,items)
+        for(int i=0;i<copySize;i++)
+            newa[i] = m_array[i];
+        RI_DELETE_ARRAY(m_array);
+        m_array = newa;
+        m_allocated = items;
+        m_size = items;		//changes also size
+    }
+    void		clear()
+    {
+        m_size = 0;
+    }
+
+    //sort array (needs operator< defined for Item. Define it with < for increasing order and > for decreasing.)
+    void		sort()
+    {
+        if(m_size <= 1)
+            return;
+        quicksort(0, m_size - 1);
+    }
+
+    void sort(int first, int last)
+    {
+        RI_ASSERT(first <= last);
+        RI_ASSERT((first >= 0) && (last < m_size));
+
+        if (m_size <= 1)
+            return;
+
+        if ((last - first) < 1)
+            return;
+
+        quicksort(first, last);
+#if defined(RI_DEBUG)
+        for (int i = first+1; i <= last; i++)
+        {
+            RI_ASSERT(m_array[i-1] <= m_array[i]);
+        }
+#endif
+    }
+
+    int     findIndex(const Item& item)
+    {
+        for(int i = 0; i < m_size; i++)
+            if (m_array[i] == item)
+                return i;
+        return -1;
+    }
+
+    //remove the first occurrence of an item from the array
+    bool        remove(const Item& item)
+    {
+        int i=0;
+        for(;i<m_size;i++)
+        {
+            if(m_array[i] == item)
+                break;
+        }
+        if(i >= m_size)
+            return false;   //not found
+        for(;i<m_size-1;i++)
+        {
+            m_array[i] = m_array[i+1];
+        }
+        m_size--;
+        return true;
+    }
+
+    RI_INLINE void			push_back( const Item& item )	//throws bad_alloc
+    {
+        if( m_size >= m_allocated )
+            reserve( (!m_allocated) ? 8 : m_allocated * 2 );	//by default, reserve 8. throws bad_alloc if runs out of memory
+        m_array[m_size++] = item;
+    }
+    RI_INLINE int			size() const				{ return m_size; }
+    RI_INLINE Item&			operator[](int i)			{ RI_ASSERT(i >= 0 && i < m_size); return m_array[i]; }
+    RI_INLINE const Item&	operator[](int i) const		{ RI_ASSERT(i >= 0 && i < m_size); return m_array[i]; }
+
+private:
+    Array(const Array& s);				//!< Not allowed.
+    void operator=(const Array& s);		//!< Not allowed.
+
+    void quicksort(int left, int right)
+    {
+        int i = left, j = right;
+        Item x = m_array[(left+right)>>1];
+
+        do
+        {
+            while (m_array[i] < x)
+                i++;
+            while (x < m_array[j])
+                j--;
+            if (i<=j)
+            {
+                Item tmp = m_array[i];
+                m_array[i] = m_array[j];
+                m_array[j] = tmp;
+                i++;
+                j--;
+            }
+        } while (i<=j);
+
+        if(left < j) quicksort(left, j);
+        if(i < right) quicksort(i, right);
+    }
+
+
+    Item*		m_array;
+    int			m_size;
+    int			m_allocated;
+};
+
+//=======================================================================
+
+}	//namespace OpenVGRI
+
+#endif /* __RIARRAY_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riContext.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,332 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of VGContext functions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "riContext.h"
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	VGContext constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGContext::VGContext(VGContext* shareContext) :
+    // Mode settings
+    m_matrixMode(VG_MATRIX_PATH_USER_TO_SURFACE),
+    m_fillRule(VG_EVEN_ODD),
+    m_imageQuality(VG_IMAGE_QUALITY_FASTER),
+    m_renderingQuality(VG_RENDERING_QUALITY_BETTER),
+    m_blendMode(VG_BLEND_SRC_OVER),
+    m_imageMode(VG_DRAW_IMAGE_NORMAL),
+
+    // Scissor rectangles
+    m_scissor(),
+
+    // Stroke parameters
+    m_strokeLineWidth(1.0f),
+    m_inputStrokeLineWidth(1.0f),
+    m_strokeCapStyle(VG_CAP_BUTT),
+    m_strokeJoinStyle(VG_JOIN_MITER),
+    m_strokeMiterLimit(4.0f),
+    m_inputStrokeMiterLimit(4.0f),
+    m_strokeDashPattern(),
+    m_inputStrokeDashPattern(),
+    m_strokeDashPhase(0.0f),
+    m_inputStrokeDashPhase(0.0f),
+    m_strokeDashPhaseReset(VG_FALSE),
+
+    // Edge fill color for vgConvolve and pattern paint
+    m_tileFillColor(0,0,0,0, Color::sRGBA),
+    m_inputTileFillColor(0,0,0,0, Color::sRGBA),
+
+    // Color for vgClear
+    m_clearColor(0,0,0,0, Color::sRGBA),
+    m_inputClearColor(0,0,0,0, Color::sRGBA),
+
+    m_glyphOrigin(0.0f, 0.0f),
+    m_inputGlyphOrigin(0.0f, 0.0f),
+
+    m_masking(VG_FALSE),
+    m_scissoring(VG_FALSE),
+
+    m_pixelLayout(VG_PIXEL_LAYOUT_UNKNOWN),
+
+    m_filterFormatLinear(VG_FALSE),
+    m_filterFormatPremultiplied(VG_FALSE),
+    m_filterChannelMask(VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA),
+
+    // Matrices
+    m_pathUserToSurface(),
+    m_imageUserToSurface(),
+    m_glyphUserToSurface(),
+    m_fillPaintToUser(),
+    m_strokePaintToUser(),
+
+    m_fillPaint(VG_INVALID_HANDLE),
+    m_strokePaint(VG_INVALID_HANDLE),
+
+    m_colorTransform(VG_FALSE),
+    m_colorTransformValues(),
+    m_inputColorTransformValues(),
+
+    m_error(VG_NO_ERROR),
+
+    m_imageManager(NULL),
+    m_pathManager(NULL),
+    m_paintManager(NULL),
+    m_fontManager(NULL),
+    m_maskLayerManager(NULL),
+
+    m_eglDrawable(NULL)
+{
+    if(shareContext)
+    {
+        m_imageManager = shareContext->m_imageManager;
+        m_pathManager = shareContext->m_pathManager;
+        m_paintManager = shareContext->m_paintManager;
+        m_fontManager = shareContext->m_fontManager;
+        m_maskLayerManager = shareContext->m_maskLayerManager;
+    }
+    else
+    {
+        try
+        {
+            m_imageManager = RI_NEW(OpenVGRI::ResourceManager<Image>, ());	//throws bad_alloc
+            m_pathManager = RI_NEW(OpenVGRI::ResourceManager<Path>, ());	//throws bad_alloc
+            m_paintManager = RI_NEW(OpenVGRI::ResourceManager<Paint>, ());	//throws bad_alloc
+            m_fontManager = RI_NEW(OpenVGRI::ResourceManager<Font>, ());	//throws bad_alloc
+            m_maskLayerManager = RI_NEW(OpenVGRI::ResourceManager<Surface>, ());	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+            RI_DELETE(m_imageManager);
+            RI_DELETE(m_pathManager);
+            RI_DELETE(m_paintManager);
+            RI_DELETE(m_fontManager);
+            RI_DELETE(m_maskLayerManager);
+
+            throw;
+        }
+    }
+    RI_ASSERT(m_imageManager);
+    RI_ASSERT(m_pathManager);
+    RI_ASSERT(m_paintManager);
+    RI_ASSERT(m_fontManager);
+    RI_ASSERT(m_maskLayerManager);
+
+    m_imageManager->addReference();
+    m_pathManager->addReference();
+    m_paintManager->addReference();
+    m_fontManager->addReference();
+    m_maskLayerManager->addReference();
+
+    m_inputColorTransformValues[0] = 1.0f;
+    m_inputColorTransformValues[1] = 1.0f;
+    m_inputColorTransformValues[2] = 1.0f;
+    m_inputColorTransformValues[3] = 1.0f;
+    m_inputColorTransformValues[4] = 0.0f;
+    m_inputColorTransformValues[5] = 0.0f;
+    m_inputColorTransformValues[6] = 0.0f;
+    m_inputColorTransformValues[7] = 0.0f;
+    m_colorTransformValues[0] = 1.0f;
+    m_colorTransformValues[1] = 1.0f;
+    m_colorTransformValues[2] = 1.0f;
+    m_colorTransformValues[3] = 1.0f;
+    m_colorTransformValues[4] = 0.0f;
+    m_colorTransformValues[5] = 0.0f;
+    m_colorTransformValues[6] = 0.0f;
+    m_colorTransformValues[7] = 0.0f;
+
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	VGContext destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+VGContext::~VGContext()
+{
+    releasePaint(VG_FILL_PATH | VG_STROKE_PATH);
+    setDefaultDrawable(NULL);
+
+    //destroy own images, paths and paints
+    while(Image* i = m_imageManager->getFirstResource(this))
+        m_imageManager->removeResource(i);
+    while(Path* p = m_pathManager->getFirstResource(this))
+        m_pathManager->removeResource(p);
+    while(Paint* t = m_paintManager->getFirstResource(this))
+        m_paintManager->removeResource(t);
+    while(Font* t = m_fontManager->getFirstResource(this))
+        m_fontManager->removeResource(t);
+    while(Surface* t = m_maskLayerManager->getFirstResource(this))
+        m_maskLayerManager->removeResource(t);
+
+    //decrease the reference count of resource managers
+    if(!m_imageManager->removeReference())
+        RI_DELETE(m_imageManager);
+    if(!m_pathManager->removeReference())
+        RI_DELETE(m_pathManager);
+    if(!m_paintManager->removeReference())
+        RI_DELETE(m_paintManager);
+    if(!m_fontManager->removeReference())
+        RI_DELETE(m_fontManager);
+    if(!m_maskLayerManager->removeReference())
+        RI_DELETE(m_maskLayerManager);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Sets new default drawable.
+* \param	drawable New drawable or NULL when context is unbound
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void VGContext::setDefaultDrawable(Drawable* drawable)
+{
+    if(m_eglDrawable)
+    {
+        if(!m_eglDrawable->removeReference())
+            RI_DELETE(m_eglDrawable);
+    }
+    m_eglDrawable = drawable;
+    if(m_eglDrawable)
+    {
+        m_eglDrawable->addReference();
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given image is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidImage(VGImage image)
+{
+    return m_imageManager->isValid((Image*)image);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given path is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidPath(VGPath path)
+{
+    return m_pathManager->isValid((Path*)path);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given paint is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidPaint(VGPaint paint)
+{
+    return m_paintManager->isValid((Paint*)paint);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given font is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidFont(VGFont font)
+{
+    return m_fontManager->isValid((Font*)font);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the given mask layer is generated through any
+*			context that is shared with this one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool VGContext::isValidMaskLayer(VGMaskLayer layer)
+{
+    return m_maskLayerManager->isValid((Surface*)layer);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Releases the given paint objects of the context.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void VGContext::releasePaint(VGbitfield paintModes)
+{
+    if(paintModes & VG_FILL_PATH)
+    {
+        //release previous paint
+        Paint* prev = (Paint*)m_fillPaint;
+        if(prev)
+        {
+            if(!prev->removeReference())
+                RI_DELETE(prev);
+        }
+        m_fillPaint = VG_INVALID_HANDLE;
+    }
+    if(paintModes & VG_STROKE_PATH)
+    {
+        //release previous paint
+        Paint* prev = (Paint*)m_strokePaint;
+        if(prev)
+        {
+            if(!prev->removeReference())
+                RI_DELETE(prev);
+        }
+        m_strokePaint = VG_INVALID_HANDLE;
+    }
+}
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riContext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,290 @@
+#ifndef __RICONTEXT_H
+#define __RICONTEXT_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	VGContext class. Used for storing OpenVG state.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef OPENVG_H
+#include "openvg.h"
+#endif
+
+#ifndef __RIDEFS_H
+#include "riDefs.h"
+#endif
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#include "riImage.h"
+#endif
+
+#ifndef __RIPATH_H
+#include "riPath.h"
+#endif
+
+#ifndef __RIFONT_H
+#include "riFont.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#ifndef __SFDYNAMICBLITTER_H
+#   include "sfDynamicBlitter.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+class VGContext;
+
+/*-------------------------------------------------------------------*//*!
+* \brief	A list of resources (Images, Paths, or Paints) shared by a
+*			set of contexts.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+template <class Resource> class ResourceManager
+{
+public:
+    ResourceManager() :
+        m_referenceCount(0),
+        m_resources()
+    {
+    }
+
+    ~ResourceManager()
+    {
+        RI_ASSERT(m_referenceCount == 0);
+        RI_ASSERT(m_resources.size() == 0);
+    }
+
+    void			addReference()
+    {
+        m_referenceCount++;
+    }
+
+    int				removeReference()
+    {
+        m_referenceCount--;
+        RI_ASSERT(m_referenceCount >= 0);
+        return m_referenceCount;
+    }
+
+    void			addResource(Resource* resource, VGContext* context)
+    {
+        Entry r;
+        r.resource = resource;
+        r.context = context;
+        m_resources.push_back(r);	//throws bad_alloc
+        resource->addReference();
+    }
+
+    void			removeResource(Resource* resource)
+    {
+        if(!resource->removeReference())
+            RI_DELETE(resource);
+
+        int i=0;
+        bool found = false;
+        for(;i<m_resources.size();i++)
+        {
+            if(m_resources[i].resource == resource)
+            {
+                found = true;
+                break;
+            }
+        }
+        RI_ASSERT(found);
+
+        for(;i<m_resources.size()-1;i++)
+        {
+            m_resources[i] = m_resources[i+1];
+        }
+        m_resources.resize(m_resources.size()-1);
+    }
+
+    bool			isValid(Resource* resource)
+    {
+        for(int i=0;i<m_resources.size();i++)
+        {
+            if(m_resources[i].resource == resource)
+                return true;
+        }
+        return false;
+    }
+
+    Resource*		getFirstResource(VGContext* context)
+    {
+        for(int i=0;i<m_resources.size();i++)
+        {
+            if(m_resources[i].context == context)
+                return m_resources[i].resource;
+        }
+        return NULL;
+    }
+
+private:
+    ResourceManager(const ResourceManager&);
+    ResourceManager operator=(const ResourceManager&);
+
+    struct Entry
+    {
+        Resource*	resource;
+        VGContext*	context;
+    };
+
+    int				m_referenceCount;
+    Array<Entry>	m_resources;
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class VGContext
+{
+public:
+    VGContext(VGContext* shareContext);	//throws bad_alloc
+    ~VGContext();
+
+    void            setDefaultDrawable(Drawable* drawable); //called from EGL
+    Drawable*       getCurrentDrawable()        { return m_eglDrawable; }
+    DynamicBlitter& getBlitter() { return m_blitter; }
+
+    bool			isValidImage(VGImage image);
+    bool			isValidPath(VGPath path);
+    bool			isValidPaint(VGPaint paint);
+    bool			isValidFont(VGFont font);
+    bool			isValidMaskLayer(VGMaskLayer layer);
+
+    void			releasePaint(VGbitfield paintModes);
+
+    void			setError(VGErrorCode error)		{ if(m_error == VG_NO_ERROR) m_error = error; }
+
+    // Mode settings
+    VGMatrixMode					m_matrixMode;
+    VGFillRule						m_fillRule;
+    VGImageQuality					m_imageQuality;
+    VGRenderingQuality				m_renderingQuality;
+    VGBlendMode						m_blendMode;
+    VGImageMode						m_imageMode;
+
+    // Scissor rectangles
+    Array<Rectangle>				m_scissor;
+
+    // Stroke parameters
+    RIfloat							m_strokeLineWidth;
+    RIfloat							m_inputStrokeLineWidth;
+    VGCapStyle						m_strokeCapStyle;
+    VGJoinStyle						m_strokeJoinStyle;
+    RIfloat							m_strokeMiterLimit;
+    RIfloat							m_inputStrokeMiterLimit;
+    Array<RIfloat>					m_strokeDashPattern;
+    Array<RIfloat>					m_inputStrokeDashPattern;
+    RIfloat							m_strokeDashPhase;
+    RIfloat							m_inputStrokeDashPhase;
+    VGboolean						m_strokeDashPhaseReset;
+
+    // Edge fill color for vgConvolve and pattern paint
+    Color							m_tileFillColor;
+    Color							m_inputTileFillColor;
+
+    // Color for vgClear
+    Color							m_clearColor;
+    Color							m_inputClearColor;
+
+    Vector2                         m_glyphOrigin;
+    Vector2                         m_inputGlyphOrigin;
+
+    VGboolean						m_masking;
+    VGboolean						m_scissoring;
+
+    VGPixelLayout					m_pixelLayout;
+
+    VGboolean						m_filterFormatLinear;
+    VGboolean						m_filterFormatPremultiplied;
+    VGbitfield						m_filterChannelMask;
+
+    // Matrices
+    Matrix3x3						m_pathUserToSurface;
+    Matrix3x3						m_imageUserToSurface;
+    Matrix3x3						m_glyphUserToSurface;
+    Matrix3x3						m_fillPaintToUser;
+    Matrix3x3						m_strokePaintToUser;
+
+    VGPaint							m_fillPaint;
+    VGPaint							m_strokePaint;
+
+    VGboolean                       m_colorTransform;
+    RIfloat                         m_colorTransformValues[8];
+    RIuint32                        m_iColorTransformValues[8];
+    RIfloat                         m_inputColorTransformValues[8];
+
+    VGErrorCode						m_error;
+
+    ResourceManager<Image>*			m_imageManager;
+    ResourceManager<Path>*			m_pathManager;
+    ResourceManager<Paint>*			m_paintManager;
+    ResourceManager<Font>*			m_fontManager;
+    ResourceManager<Surface>*		m_maskLayerManager;
+
+    Rasterizer                      m_rasterizer;
+
+    PixelPipe                       m_pixelPipe;
+    DynamicBlitter                  m_blitter;
+
+private:
+    Drawable*                       m_eglDrawable;
+
+    VGContext(const VGContext&);			//!< Not allowed.
+    void operator=(const VGContext&);		//!< Not allowed.
+};
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+//==============================================================================================
+
+#endif /* __RICONTEXT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riDefs.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,206 @@
+#ifndef __RIDEFS_H
+#define __RIDEFS_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Platform- and compiler-dependent type and macro definitions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include <float.h>
+#include <math.h>
+#include <assert.h>
+#include <new>	//for bad_alloc
+
+#if defined(_WIN32) && defined(_DEBUG)
+#   define WIN32_LEAN_AND_MEAN
+#   include <windows.h>
+#endif
+
+//make for-clause scope c++ standard compliant on msvc
+#if defined (_MSC_VER)
+#	if !defined (for)
+        __forceinline bool getFalse (void) { return false; }
+#		define for if(getFalse()); else for
+#	endif // for
+
+#pragma warning(disable:4710)	//disable function not inlined warning
+#pragma warning(disable:4714)	//disable function not __forceinlined warning
+#endif  // _MSC_VER
+
+namespace OpenVGRI
+{
+
+//=======================================================================
+
+typedef long long       RIint64;
+typedef unsigned long long RIuint64;
+typedef int				RIint32;
+typedef unsigned int	RIuint32;
+typedef short			RIint16;
+typedef unsigned short	RIuint16;
+typedef signed char		RIint8;
+typedef unsigned char	RIuint8;
+typedef float			RIfloat32;
+//TODO add compile-time assertions to guarantee the sizes
+
+#if defined (_MSC_VER) // MSVC WIN32
+#	define RI_INLINE __forceinline
+#elif defined __APPLE__ || defined (__GNUC__) || defined (__GCC32__)
+#	define RI_INLINE inline
+#endif
+
+/*!< Unsigned int that can hold a pointer to any type */
+/*!< Signed int that can hold a pointer to any type */
+#if defined (_MSC_VER) && (_MSC_VER >= 1300)
+typedef uintptr_t		RIuintptr;
+typedef intptr_t		RIintptr;
+#else
+typedef unsigned long   RIuintptr;
+typedef signed long     RIintptr;
+#endif
+
+#define RI_UINT32_MAX (0xffffffffu)
+#define RI_INT32_MAX  (0x7fffffff)
+#define RI_INT32_MIN  (-0x7fffffff-1)
+
+/* maximum mantissa is 23 */
+#define RI_MANTISSA_BITS 23
+
+/* maximum exponent is 8 */
+#define RI_EXPONENT_BITS 8
+
+typedef union
+{
+    RIfloat32	f;
+    RIuint32	i;
+} RIfloatInt;
+
+RI_INLINE float	getFloatMax()
+{
+    RIfloatInt v;
+    v.i = (((1<<(RI_EXPONENT_BITS-1))-1+127) << 23) | (((1<<RI_MANTISSA_BITS)-1) << (23-RI_MANTISSA_BITS));
+    return v.f;
+}
+#define RI_FLOAT_MAX  getFloatMax()
+
+#define RI_MAX_IMAGE_WIDTH					16384
+#define RI_MAX_IMAGE_HEIGHT					16384
+#define RI_MAX_IMAGE_PIXELS					(RI_MAX_IMAGE_WIDTH*RI_MAX_IMAGE_HEIGHT)
+#define RI_MAX_IMAGE_BYTES					(4*RI_MAX_IMAGE_WIDTH*RI_MAX_IMAGE_HEIGHT)
+#define RI_MAX_DASH_COUNT					256
+#define RI_MAX_COLOR_RAMP_STOPS				256
+#define RI_MAX_KERNEL_SIZE					256
+#define RI_MAX_SEPARABLE_KERNEL_SIZE		256
+#define RI_MAX_GAUSSIAN_STD_DEVIATION		16.0f
+#define RI_MAX_SCISSOR_RECTANGLES			256
+#define RI_MAX_EDGES						262144
+#define RI_MAX_SAMPLES						1
+//#define RI_NUM_TESSELLATED_SEGMENTS_QUAD	256
+//#define RI_NUM_TESSELLATED_SEGMENTS_CUBIC	256
+//#define RI_NUM_TESSELLATED_SEGMENTS_ARC		256
+#define RI_NUM_TESSELLATED_SEGMENTS_QUAD	8
+#define RI_NUM_TESSELLATED_SEGMENTS_CUBIC	8
+#define RI_NUM_TESSELLATED_SEGMENTS_ARC		8
+
+#if !defined(_WIN32) && !defined(SF_PROFILE)
+#	ifndef NDEBUG
+#	define _DEBUG 1
+#	endif
+#endif
+
+#if _DEBUG
+    #define RI_DEBUG
+#endif
+
+#ifdef RI_DEBUG
+#	define RI_ASSERT(X) assert(X)
+#else
+#	define RI_ASSERT(X) (void(0))
+#endif
+
+#if defined(RI_DEBUG)
+#   define RI_PRINTF(...) printf(__VA_ARGS__)
+#else
+#   define RI_PRINTF(...)
+#endif
+
+#if defined(RI_DEBUG)
+#   if defined(_WIN32)
+#       define RI_TRACE(...) do { \
+        char buf[512]; \
+        snprintf(buf, sizeof(buf), __VA_ARGS__); \
+        OutputDebugString(buf); \
+    } while(false)
+#   else
+#       define RI_TRACE(...) printf(__VA_ARGS__)
+#   endif
+#else
+#   define RI_TRACE(...)
+#endif
+
+#define RI_UNREF(X) ((void)(X))
+#if defined(_WIN32)
+#   define RI_APIENTRY VG_API_ENTRY
+#else
+#	define RI_APIENTRY
+#endif
+
+#if defined(_WIN32)
+#   define snprintf sprintf_s 
+#endif 
+
+#define RI_API_CALL VG_API_CALL
+
+#define RI_NEW(TYPE, PARAMS)           (new TYPE PARAMS)
+#define RI_NEW_ARRAY(TYPE, ITEMS)      (new TYPE[ITEMS])
+#define RI_DELETE(PARAMS)              (delete (PARAMS))
+#define RI_DELETE_ARRAY(PARAMS)        (delete[] (PARAMS))
+
+bool			isValidImageFormat(int format);
+
+// \todo Move these to utility functions, etc.
+RI_INLINE void RI_MEM_ZERO(void *dst, size_t n)
+{
+    RI_ASSERT(n > 0);
+    RI_ASSERT((n & 0x3) == 0);
+
+    RIuint32 *ptr = (RIuint32*)dst;
+    for(size_t i = 0; i < (n>>2); i++)
+    {
+        *ptr++ = 0;
+    }
+}
+
+//=======================================================================
+
+}	//namespace OpenVGRI
+
+#endif /* __RIDEFS_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riEGLOS.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,58 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef _RIEGLOS_H
+#define _RIEGLOS_H
+
+#include "EGL/egl.h"
+#include "riImage.h"
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+    struct OSWindowContext
+    {
+        int                 window;
+        unsigned int*       tmp;
+        int                 tmpWidth;
+        int                 tmpHeight;
+    };
+
+    void* OSGetCurrentThreadID(void);
+    void OSDeinitMutex(void);
+    void OSAcquireMutex(void);
+    void OSReleaseMutex(void);
+    OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window);
+    void OSDestroyWindowContext(OSWindowContext* ctx);
+    bool OSIsWindow(const OSWindowContext* context);
+    void OSGetWindowSize(const OSWindowContext* ctx, int& width, int& height);
+    void OSBlitToWindow(OSWindowContext* ctx, const Drawable* drawable);
+    EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id);
+}   //namespace OpenVGRI
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riFont.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,203 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of Font class.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "riFont.h"
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Font constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Font::Font(int capacityHint) :
+    m_referenceCount(0),
+    m_glyphs()
+{
+    RI_ASSERT(capacityHint >= 0);
+    m_glyphs.reserve(capacityHint);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Font destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Font::~Font()
+{
+    //remove references to paths and images
+    for(int i=0;i<m_glyphs.size();i++)
+        clearGlyph(&m_glyphs[i]);
+    RI_ASSERT(m_referenceCount == 0);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Find a glyph based on glyphIndex.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Font::Glyph* Font::findGlyph(unsigned int index)
+{
+    for(int i=0;i<m_glyphs.size();i++)
+    {
+        if(m_glyphs[i].m_state != Glyph::GLYPH_UNINITIALIZED && m_glyphs[i].m_index == index)
+            return &m_glyphs[i];
+    }
+    return NULL;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Find a free glyph or allocate a new one.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Font::Glyph* Font::newGlyph()
+{
+    for(int i=0;i<m_glyphs.size();i++)
+    {
+        if(m_glyphs[i].m_state == Glyph::GLYPH_UNINITIALIZED)
+            return &m_glyphs[i];
+    }
+    m_glyphs.resize(m_glyphs.size()+1);
+    return &m_glyphs[m_glyphs.size()-1];
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Free glyph and its data.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Font::clearGlyph(Glyph* g)
+{
+    RI_ASSERT(g);
+    if(g->m_path != VG_INVALID_HANDLE)
+    {
+        Path* p = (Path*)g->m_path;
+        if(!p->removeReference())
+            RI_DELETE(p);
+    }
+    if(g->m_image != VG_INVALID_HANDLE)
+    {
+        Image* p = (Image*)g->m_image;
+        p->removeInUse();
+        if(!p->removeReference())
+            RI_DELETE(p);
+    }
+    Glyph a;
+    *g = a;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Font::setGlyphToPath(unsigned int index, VGPath path, bool isHinted, const Vector2& origin, const Vector2& escapement)
+{
+    Glyph* g = findGlyph(index);
+    if(g)
+    {   //glyph exists, replace
+        clearGlyph(g);
+    }
+    else
+    {   //glyph doesn't exist, allocate a new one
+        g = newGlyph();
+    }
+
+    g->m_index = index;
+    g->m_state = Glyph::GLYPH_PATH;
+    g->m_path = path;
+    g->m_image = VG_INVALID_HANDLE;
+    g->m_isHinted = isHinted;
+    g->m_origin = origin;
+    g->m_escapement = escapement;
+
+    if(path != VG_INVALID_HANDLE)
+    {
+        Path* p = (Path*)path;
+        p->addReference();
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Font::setGlyphToImage(unsigned int index, VGImage image, const Vector2& origin, const Vector2& escapement)
+{
+    Glyph* g = findGlyph(index);
+    if(g)
+    {   //glyph exists, replace
+        clearGlyph(g);
+    }
+    else
+    {   //glyph doesn't exist, allocate a new one
+        g = newGlyph();
+    }
+
+    g->m_index = index;
+    g->m_state = Glyph::GLYPH_IMAGE;
+    g->m_path = VG_INVALID_HANDLE;
+    g->m_image = image;
+    g->m_isHinted = false;
+    g->m_origin = origin;
+    g->m_escapement = escapement;
+
+    if(image != VG_INVALID_HANDLE)
+    {
+        Image* p = (Image*)image;
+        p->addReference();
+        p->addInUse();
+    }
+}
+
+//=======================================================================
+
+}	//namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riFont.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,116 @@
+#ifndef __RIFONT_H
+#define __RIFONT_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 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.
+ *
+ *//**
+ * \file
+ * \brief	VGContext class. Used for storing OpenVG state.
+ * \note	
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _OPENVG_H
+#include "openvg.h"
+#endif
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#ifndef __RIPATH_H
+#include "riPath.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#include "riImage.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Storage and operations for VGFont.
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+class Font
+{
+public:
+	struct Glyph
+	{
+        enum State
+        {
+            GLYPH_UNINITIALIZED     = 0,
+            GLYPH_PATH              = 1,
+            GLYPH_IMAGE             = 2
+        };
+		Glyph()				{ m_state = GLYPH_UNINITIALIZED; m_path = m_image = VG_INVALID_HANDLE; m_isHinted = false; m_origin.set(0.0f, 0.0f); m_escapement.set(0.0f, 0.0f); }
+        unsigned int m_index;
+        State        m_state;
+		VGPath		 m_path;
+		VGImage		 m_image;
+		bool		 m_isHinted;
+		Vector2		 m_origin;
+		Vector2		 m_escapement;
+	};
+
+	Font(int capacityHint);	//throws bad_alloc
+	~Font();
+
+	int				getNumGlyphs() const					{ int n=0; for(int i=0;i<m_glyphs.size();i++) { if(m_glyphs[i].m_state != Glyph::GLYPH_UNINITIALIZED) n++; } return n; }
+	void			addReference()							{ m_referenceCount++; }
+	int				removeReference()						{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+	void			setGlyphToPath(unsigned int index, VGPath path, bool isHinted, const Vector2& origin, const Vector2& escapement);    //throws bad_alloc
+	void			setGlyphToImage(unsigned int index, VGImage image, const Vector2& origin, const Vector2& escapement);    //throws bad_alloc
+    Glyph*          findGlyph(unsigned int index);
+    void            clearGlyph(Glyph* g);
+private:
+	Font(const Font&);						//!< Not allowed.
+	void operator=(const Font&);			//!< Not allowed.
+
+    Glyph*          newGlyph();    //throws bad_alloc
+
+	int				m_referenceCount;
+	Array<Glyph>	m_glyphs;
+};
+
+//=======================================================================
+
+}	//namespace OpenVGRI
+
+//=======================================================================
+
+#endif /* __RIFONT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riImage.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2835 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of Color and Image functions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "riImage.h"
+#include "riRasterizer.h"
+#include "riContext.h"
+
+#ifndef __SFDYNAMICBLITTER_H
+#   include "sfDynamicBlitter.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from numBits into a shifted mask
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static RI_INLINE unsigned int bitsToMask(unsigned int bits, unsigned int shift)
+{
+    return ((1<<bits)-1) << shift;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from color (RIfloat) to an int with 1.0f mapped to the
+*			given maximum with round-to-nearest semantics.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RI_INLINE int ffloor(RIfloat x)
+{
+    return (x >= 0) ? (int)x : (int)(x-1);
+}
+
+//static const float FLOAT_0	 = 0.0f;
+static const float FLOAT_0_5 = 0.5f;
+
+/* \note Rewrite this if time. */
+static unsigned int colorToInt(RIfloat c, int maxc)
+{
+#if defined RI_USE_SSE
+    /*
+        Registers mapping:
+        c		<->	xmm0,
+        maxc	<-> xmm1
+        0		<-> xmm2
+    */
+    _asm
+    {
+        xorps		xmm2, xmm2					; xmm2 = 0
+
+        ;---------------------------------------------
+        ; Computing: xmm0 = (c * (RIfloat)maxc + 0.5f)
+        ;---------------------------------------------
+        movss		xmm0, dword ptr [c]			; xmm0 = c
+        cvtsi2ss	xmm1, dword ptr [maxc]		; xmm1 = (float)maxc
+        mulss		xmm0, xmm1					; xmm0 = xmm0 * xmm1 = c * (float)maxc
+        addss		xmm0, FLOAT_0_5				; xmm0 = xmm0 + 0.5f = c * (float)maxc + 0.5f
+
+        ;---------------------------------------------
+        ; Computing: xmm0 = floor(xmm0) = floor(c * (RIfloat)maxc + 0.5f)
+        ;---------------------------------------------
+        cvttss2si   ebx, xmm0					; ebx = (int)xmm0
+        mov         eax, ebx					; eax = ebx = (int)xmm0
+        shr         eax, 31						; eax = sign(eax) = sign((int)xmm0)
+        sub         ebx, eax					; ebx = ebx - sign((int)xmm0) = (int)xmm0 - sign((int)xmm0) = (int)floor((int)xmm0)
+        cvtsi2ss    xmm0, ebx					; xmm0 = floor(xmm0)
+
+        pmaxsw		xmm0, xmm2;					; xmm0 = MAX(xmm0, 0)
+        pminsw		xmm0, xmm1					; xmm0 = MIN(xmm0, maxc)
+        cvttss2si   eax, xmm0					; return value = eax = (int)xmm0
+    }
+#else
+    return RI_INT_MIN(RI_INT_MAX((int)ffloor(c * (RIfloat)maxc + 0.5f), 0), maxc);
+#endif
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from int to color (RIfloat) with the given maximum
+*			mapped to 1.0f.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static RI_INLINE RIfloat intToColor(unsigned int i, unsigned int maxi)
+{
+    return (RIfloat)(i & maxi) / (RIfloat)maxi;
+}
+
+void Color::Descriptor::toSmallDescriptor(Color::SmallDescriptor& smallDesc) const
+{
+    switch (bitsPerPixel)
+    {
+    case 32:
+        smallDesc.size = SIZE_32;
+        break;
+    case 24:
+        smallDesc.size = SIZE_24;
+        break;
+    case 16:
+        smallDesc.size = SIZE_16;
+        break;
+    case 8:
+        smallDesc.size = SIZE_8;
+        break;
+    case 4:
+        smallDesc.size = SIZE_4;
+        break;
+    default:
+        RI_ASSERT(bitsPerPixel == 1);
+        smallDesc.size = SIZE_1;
+        break;
+    }
+    smallDesc.shape = shape;
+    smallDesc.internalFormat = internalFormat;
+}
+
+Color::Descriptor Color::Descriptor::getDummyDescriptor()
+{
+    static const Descriptor dummy = Color::Descriptor(8,0,8,8,8,16,8,24,0,0,sRGBA,32,SHAPE_ABGR);
+    return dummy;
+}
+
+/**
+ * \brief   Determine the shape of the color format from other data.
+ * \todo    The naming is poor because it may be interpreted as returning the member
+ *          "shape".
+ */
+Color::Shape Color::Descriptor::getShape() const
+{
+    // \todo There should be some easier way to define the shape so that it does
+    // not need to be determined with so many conditions.
+
+    if (isAlphaOnly())
+    {
+        return SHAPE_A;
+    }
+    else if (isLuminance())
+    {
+        if (alphaBits)
+        {
+            if (alphaShift == 0)
+                return SHAPE_LA;
+            return SHAPE_AL;
+        }
+        return SHAPE_L;
+    } 
+    else if (!alphaBits)
+    {
+        if (bitsPerPixel == 32)
+        {
+            switch(redShift)
+            {
+            case 0:
+                return SHAPE_XBGR;
+            case 8:
+                return SHAPE_BGRX;
+            case 16:
+                return SHAPE_XRGB;
+            default:
+                RI_ASSERT(redShift == 24);
+                return SHAPE_RGBX;
+            }
+        } else if (bitsPerPixel == 24)
+        {
+            if (!redShift)
+                return SHAPE_BGR;
+            else
+            {
+                RI_ASSERT(redShift == 16);
+                return SHAPE_RGB;
+            }
+        } else
+        {
+            RI_ASSERT(redBits == 5 && greenBits == 6 && blueBits == 5);
+            if(redShift)
+                return SHAPE_RGB;
+            else
+                return SHAPE_BGR;
+        }
+    }
+    else
+    {
+        if (bitsPerPixel == 32)
+        {
+            switch(redShift)
+            {
+            case 0:
+                return SHAPE_ABGR;
+            case 8:
+                return SHAPE_BGRA;
+            case 16:
+                return SHAPE_ARGB;
+            default:
+                RI_ASSERT(redShift == 24);
+                return SHAPE_RGBA;
+            }
+        } else
+        {
+            RI_ASSERT(bitsPerPixel == 16);
+            if (redBits == 5)
+            {
+                RI_ASSERT(greenBits == 5 && blueBits == 5 && alphaBits == 1);
+                switch(redShift)
+                {
+                case 0:
+                    return SHAPE_ABGR;
+                case 1:
+                    return SHAPE_BGRA;
+                case 10:
+                    return SHAPE_ARGB;
+                default:
+                    RI_ASSERT(redShift == 11);
+                    return SHAPE_RGBA;
+                }
+            } else
+            {
+                RI_ASSERT(redBits == 4 && greenBits == 4 && alphaBits == 4);
+                switch(redShift)
+                {
+                case 0:
+                    return SHAPE_ABGR;
+                case 4:
+                    return SHAPE_BGRA;
+                case 8:
+                    return SHAPE_ARGB;
+                default:
+                    RI_ASSERT(redShift == 12);
+                    return SHAPE_RGBA;
+                }
+            }
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from packed integer in a given format to a Color.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Color::unpack(unsigned int inputData, const Color::Descriptor& inputDesc)
+{
+    int rb = inputDesc.redBits;
+    int gb = inputDesc.greenBits;
+    int bb = inputDesc.blueBits;
+    int ab = inputDesc.alphaBits;
+    int lb = inputDesc.luminanceBits;
+    int rs = inputDesc.redShift;
+    int gs = inputDesc.greenShift;
+    int bs = inputDesc.blueShift;
+    int as = inputDesc.alphaShift;
+    int ls = inputDesc.luminanceShift;
+
+    m_format = inputDesc.internalFormat;
+    if(lb)
+    {	//luminance
+        r = g = b = intToColor(inputData >> ls, (1<<lb)-1);
+        a = 1.0f;
+    }
+    else
+    {	//rgba
+        r = rb ? intToColor(inputData >> rs, (1<<rb)-1) : (RIfloat)1.0f;
+        g = gb ? intToColor(inputData >> gs, (1<<gb)-1) : (RIfloat)1.0f;
+        b = bb ? intToColor(inputData >> bs, (1<<bb)-1) : (RIfloat)1.0f;
+        a = ab ? intToColor(inputData >> as, (1<<ab)-1) : (RIfloat)1.0f;
+
+        if(isPremultiplied())
+        {	//clamp premultiplied color to alpha to enforce consistency
+            r = RI_MIN(r, a);
+            g = RI_MIN(g, a);
+            b = RI_MIN(b, a);
+        }
+    }
+
+    assertConsistency();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from Color to a packed integer in a given format.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+unsigned int Color::pack(const Color::Descriptor& outputDesc) const
+{
+    assertConsistency();
+
+    int rb = outputDesc.redBits;
+    int gb = outputDesc.greenBits;
+    int bb = outputDesc.blueBits;
+    int ab = outputDesc.alphaBits;
+    int lb = outputDesc.luminanceBits;
+    int rs = outputDesc.redShift;
+    int gs = outputDesc.greenShift;
+    int bs = outputDesc.blueShift;
+    int as = outputDesc.alphaShift;
+    int ls = outputDesc.luminanceShift;
+
+    if(lb)
+    {	//luminance
+        RI_ASSERT(isLuminance());
+        return colorToInt(r, (1<<lb)-1) << ls;
+    }
+    else
+    {	//rgb
+        RI_ASSERT(!isLuminance());
+        unsigned int cr = rb ? colorToInt(r, (1<<rb)-1) : 0;
+        unsigned int cg = gb ? colorToInt(g, (1<<gb)-1) : 0;
+        unsigned int cb = bb ? colorToInt(b, (1<<bb)-1) : 0;
+        unsigned int ca = ab ? colorToInt(a, (1<<ab)-1) : 0;
+        return packRGBAInteger(cr, rs, cg, gs, cb, bs, ca, as);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from the current internal format to another.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+/* \todo Integer & lookup versions */
+
+static RIfloat gamma(RIfloat c)
+{
+    if( c <= 0.00304f )
+        c *= 12.92f;
+    else
+        c = 1.0556f * (RIfloat)pow(c, 1.0f/2.4f) - 0.0556f;
+    return c;
+}
+
+static RIfloat invgamma(RIfloat c)
+{
+    if( c <= 0.03928f )
+        c /= 12.92f;
+    else
+        c = (RIfloat)pow((c + 0.0556f)/1.0556f, 2.4f);
+    return c;
+}
+
+static RIfloat lRGBtoL(RIfloat r, RIfloat g, RIfloat b)
+{
+    return 0.2126f*r + 0.7152f*g + 0.0722f*b;
+}
+
+void Color::convert(InternalFormat outputFormat)
+{
+    /* \todo This should probably be converted to integer code. */
+
+    assertConsistency();
+
+    if( m_format == outputFormat )
+        return;
+
+    if(isPremultiplied())
+    {	//unpremultiply
+        RIfloat ooa = (a != 0.0f) ? 1.0f / a : (RIfloat)0.0f;
+        r *= ooa;
+        g *= ooa;
+        b *= ooa;
+    }
+
+    //From Section 3.4.2 of OpenVG spec
+    //1: sRGB = gamma(lRGB)
+    //2: lRGB = invgamma(sRGB)
+    //3: lL = 0.2126 lR + 0.7152 lG + 0.0722 lB
+    //4: lRGB = lL
+    //5: sL = gamma(lL)
+    //6: lL = invgamma(sL)
+    //7: sRGB = sL
+
+    //Source/Dest lRGB sRGB   lL   sL
+    //lRGB          -    1    3    3,5
+    //sRGB          2    -    2,3  2,3,5
+    //lL            4    4,1  -    5
+    //sL            7,2  7    6    -
+
+    const unsigned int shift = 3;
+    unsigned int conversion = (m_format & (NONLINEAR | LUMINANCE)) | ((outputFormat & (NONLINEAR | LUMINANCE)) << shift);
+
+    switch(conversion)
+    {
+    case lRGBA | (sRGBA << shift): r = gamma(r); g = gamma(g); b = gamma(b); break;							//1
+    case lRGBA | (lLA << shift)  : r = g = b = lRGBtoL(r, g, b); break;										//3
+    case lRGBA | (sLA << shift)  : r = g = b = gamma(lRGBtoL(r, g, b)); break;								//3,5
+    case sRGBA | (lRGBA << shift): r = invgamma(r); g = invgamma(g); b = invgamma(b); break;				//2
+    case sRGBA | (lLA << shift)  : r = g = b = lRGBtoL(invgamma(r), invgamma(g), invgamma(b)); break;		//2,3
+    case sRGBA | (sLA << shift)  : r = g = b = gamma(lRGBtoL(invgamma(r), invgamma(g), invgamma(b))); break;//2,3,5
+    case lLA   | (lRGBA << shift): break;																	//4
+    case lLA   | (sRGBA << shift): r = g = b = gamma(r); break;												//4,1
+    case lLA   | (sLA << shift)  : r = g = b = gamma(r); break;												//5
+    case sLA   | (lRGBA << shift): r = g = b = invgamma(r); break;											//7,2
+    case sLA   | (sRGBA << shift): break;																	//7
+    case sLA   | (lLA << shift)  : r = g = b = invgamma(r); break;											//6
+    default: RI_ASSERT((m_format & (LUMINANCE | NONLINEAR)) == (outputFormat & (LUMINANCE | NONLINEAR))); break;	//nop
+    }
+
+    if(outputFormat & PREMULTIPLIED)
+    {	//premultiply
+        r *= a;
+        g *= a;
+        b *= a;
+    }
+    m_format = outputFormat;
+
+    assertConsistency();
+}
+
+/*------------------------------------------------------------------------*//*!
+* \brief	Creates a pixel format descriptor out of VGImageFormat
+* \param
+* \return
+* \note     Remove this function and use the "const" version for consistency.
+*//*------------------------------------------------------------------------*/
+Color::Descriptor Color::formatToDescriptor(VGImageFormat format)
+{
+    Descriptor desc;
+    memset(&desc, 0, sizeof(Descriptor));
+    RI_ASSERT(isValidImageFormat(format));
+
+    int baseFormat = (int)format & 15;
+    const int numBaseFormats = 15;
+    RI_ASSERT(baseFormat >= 0 && baseFormat < numBaseFormats);
+    int swizzleBits = ((int)format >> 6) & 3;
+
+    /* base formats
+    VG_sRGBX_8888                               =  0,
+    VG_sRGBA_8888                               =  1,
+    VG_sRGBA_8888_PRE                           =  2,
+    VG_sRGB_565                                 =  3,
+    VG_sRGBA_5551                               =  4,
+    VG_sRGBA_4444                               =  5,
+    VG_sL_8                                     =  6,
+    VG_lRGBX_8888                               =  7,
+    VG_lRGBA_8888                               =  8,
+    VG_lRGBA_8888_PRE                           =  9,
+    VG_lL_8                                     = 10,
+    VG_A_8                                      = 11,
+    VG_BW_1                                     = 12,
+    VG_A_1                                      = 13,
+    VG_A_4                                      = 14,
+    */
+
+    static const int redBits[numBaseFormats] =       {8, 8, 8, 5, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0};
+    static const int greenBits[numBaseFormats] =     {8, 8, 8, 6, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0};
+    static const int blueBits[numBaseFormats] =      {8, 8, 8, 5, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0};
+    static const int alphaBits[numBaseFormats] =     {0, 8, 8, 0, 1, 4, 0, 0, 8, 8, 0, 8, 0, 1, 4};
+    static const int luminanceBits[numBaseFormats] = {0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 1, 0, 0};
+
+    static const int redShifts[4*numBaseFormats] = {24, 24, 24, 11, 11, 12, 0, 24, 24, 24, 0, 0, 0, 0, 0,	//RGBA
+                                                    16, 16, 16, 11, 10, 8,  0, 16, 16, 16, 0, 0, 0, 0, 0,	//ARGB
+                                                    8,  8,  8,  0,  1,  4,  0, 8,  8,  8,  0, 0, 0, 0, 0,	//BGRA
+                                                    0,  0,  0,  0,  0,  0,  0, 0,  0,  0,  0, 0, 0, 0, 0};	//ABGR
+
+    static const int greenShifts[4*numBaseFormats] = {16, 16, 16, 5,  6,  8,  0, 16, 16, 16, 0, 0, 0, 0, 0,	//RGBA
+                                                      8,  8,  8,  5,  5,  4,  0, 8,  8,  8,  0, 0, 0, 0, 0,	//ARGB
+                                                      16, 16, 16, 5,  6,  8,  0, 16, 16, 16, 0, 0, 0, 0, 0,	//BGRA
+                                                      8,  8,  8,  5,  5,  4,  0, 8,  8,  8,  0, 0, 0, 0, 0};//ABGR
+
+    static const int blueShifts[4*numBaseFormats] =  {8,  8,  8,  0,  1,  4,  0, 8,  8,  8,  0, 0, 0, 0, 0,	//RGBA
+                                                      0,  0,  0,  0,  0,  0,  0, 0,  0,  0,  0, 0, 0, 0, 0,	//ARGB
+                                                      24, 24, 24, 11, 11, 12, 0, 24, 24, 24, 0, 0, 0, 0, 0,	//BGRA
+                                                      16, 16, 16, 11, 10, 8,  0, 16, 16, 16, 0, 0, 0, 0, 0};//ABGR
+
+    static const int alphaShifts[4*numBaseFormats] = {0,  0,  0,  0,  0,  0,  0, 0,  0,  0,  0, 0, 0, 0, 0,	//RGBA
+                                                      0,  24, 24, 0,  15, 12, 0, 0,  24, 24, 0, 0, 0, 0, 0,	//ARGB
+                                                      0,  0,  0,  0,  0,  0,  0, 0,  0,  0,  0, 0, 0, 0, 0,	//BGRA
+                                                      0,  24, 24, 0,  15, 12, 0, 0,  24, 24, 0, 0, 0, 0, 0};//ABGR
+
+    static const int bpps[numBaseFormats] = {32, 32, 32, 16, 16, 16, 8, 32, 32, 32, 8, 8, 1, 1, 4};
+
+    static const InternalFormat internalFormats[numBaseFormats] = {sRGBA, sRGBA, sRGBA_PRE, sRGBA, sRGBA, sRGBA, sLA, lRGBA, lRGBA, lRGBA_PRE, lLA, lRGBA, lLA, lRGBA, lRGBA};
+
+    desc.redBits = redBits[baseFormat];
+    desc.greenBits = greenBits[baseFormat];
+    desc.blueBits = blueBits[baseFormat];
+    desc.alphaBits = alphaBits[baseFormat];
+    desc.luminanceBits = luminanceBits[baseFormat];
+
+    desc.redShift = redShifts[swizzleBits * numBaseFormats + baseFormat];
+    desc.greenShift = greenShifts[swizzleBits * numBaseFormats + baseFormat];
+    desc.blueShift = blueShifts[swizzleBits * numBaseFormats + baseFormat];
+    desc.alphaShift = alphaShifts[swizzleBits * numBaseFormats + baseFormat];
+    desc.luminanceShift = 0;	//always zero
+
+    desc.vgFormat = format;
+    desc.bitsPerPixel = bpps[baseFormat];
+    desc.bytesPerPixel = desc.bitsPerPixel / 8;
+    desc.internalFormat = internalFormats[baseFormat];
+    desc.shape = desc.getShape();
+
+    if (desc.alphaBits)
+    {
+        desc.maskBits = desc.alphaBits;
+        desc.maskShift = desc.alphaShift;
+    } 
+    else if (!desc.isLuminance())
+    {
+        desc.maskBits = desc.redBits;
+        desc.maskShift = desc.redShift;
+    } 
+    else
+    {
+        desc.maskBits = desc.luminanceBits;
+        desc.maskShift = desc.luminanceShift;
+    }
+
+    return desc;
+}
+
+
+struct DescToFormatMapping
+{
+    Color::Descriptor desc;
+    VGImageFormat format;
+};
+
+RI_INLINE static bool isDescEqualToMapping(const Color::Descriptor& desc, const DescToFormatMapping &mapping)
+{
+    if ((desc.redBits == mapping.desc.redBits) &&
+        (desc.redShift == mapping.desc.redShift) &&
+        (desc.greenBits == mapping.desc.greenBits) &&
+        (desc.greenShift == mapping.desc.greenShift) &&
+        (desc.blueBits == mapping.desc.blueBits) &&
+        (desc.blueShift == mapping.desc.blueShift) &&
+        (desc.alphaBits == mapping.desc.alphaBits) &&
+        (desc.alphaShift == mapping.desc.alphaShift) &&
+        (desc.luminanceBits == mapping.desc.luminanceBits) &&
+        (desc.luminanceShift == mapping.desc.luminanceShift) &&
+        (desc.internalFormat == mapping.desc.internalFormat) &&
+        (desc.bitsPerPixel == mapping.desc.bitsPerPixel))
+        return true;
+
+    return false;
+}
+
+VGImageFormat Color::descriptorToVGImageFormat(const Descriptor& desc)
+{
+//Color::Descriptor::Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp) :
+    // \todo These are hardcoded here only to allow constant initialization, they should be generated
+    // using formatToDescriptor!
+    static const DescToFormatMapping map[] = {
+    /* RGB{A,X} channel ordering */
+        { formatToDescriptorConst(VG_sRGBX_8888), VG_sRGBX_8888 },
+        { formatToDescriptorConst(VG_sRGBA_8888), VG_sRGBA_8888 },
+        { formatToDescriptorConst(VG_sRGBA_8888_PRE), VG_sRGBA_8888_PRE },
+        { formatToDescriptorConst(VG_sRGB_565), VG_sRGB_565 },
+        { formatToDescriptorConst(VG_sRGBA_5551), VG_sRGBA_5551 },
+        { formatToDescriptorConst(VG_sRGBA_4444), VG_sRGBA_4444 },
+        { formatToDescriptorConst(VG_sL_8), VG_sL_8 },
+        { formatToDescriptorConst(VG_lRGBX_8888), VG_lRGBX_8888 },
+        { formatToDescriptorConst(VG_lRGBA_8888), VG_lRGBA_8888 },
+        { formatToDescriptorConst(VG_lRGBA_8888_PRE), VG_lRGBA_8888_PRE },
+        { formatToDescriptorConst(VG_lL_8), VG_lL_8 },
+        { formatToDescriptorConst(VG_A_8), VG_A_8 },
+        { formatToDescriptorConst(VG_BW_1), VG_BW_1 },
+        { formatToDescriptorConst(VG_A_1), VG_A_1 },
+        { formatToDescriptorConst(VG_A_4), VG_A_4 },
+
+  /* {A,X}RGB channel ordering */
+        { formatToDescriptorConst(VG_sXRGB_8888), VG_sXRGB_8888 },
+        { formatToDescriptorConst(VG_sARGB_8888), VG_sARGB_8888 },
+        { formatToDescriptorConst(VG_sARGB_8888_PRE), VG_sARGB_8888_PRE },
+        { formatToDescriptorConst(VG_sARGB_1555), VG_sARGB_1555 },
+        { formatToDescriptorConst(VG_sARGB_4444), VG_sARGB_4444 },
+        { formatToDescriptorConst(VG_lXRGB_8888), VG_lXRGB_8888 },
+        { formatToDescriptorConst(VG_lARGB_8888), VG_lARGB_8888 },
+        { formatToDescriptorConst(VG_lARGB_8888_PRE), VG_lARGB_8888_PRE },
+
+  /* BGR{A,X} channel ordering */
+        { formatToDescriptorConst(VG_sBGRX_8888), VG_sBGRX_8888 },
+        { formatToDescriptorConst(VG_sBGRA_8888), VG_sBGRA_8888 },
+        { formatToDescriptorConst(VG_sBGRA_8888_PRE), VG_sBGRA_8888_PRE },
+        { formatToDescriptorConst(VG_sBGR_565), VG_sBGR_565 },
+        { formatToDescriptorConst(VG_sBGRA_5551), VG_sBGRA_5551 },
+        { formatToDescriptorConst(VG_sBGRA_4444), VG_sBGRA_4444 },
+        { formatToDescriptorConst(VG_lBGRX_8888), VG_lBGRX_8888 },
+        { formatToDescriptorConst(VG_lBGRA_8888), VG_lBGRA_8888 },
+        { formatToDescriptorConst(VG_lBGRA_8888_PRE), VG_lBGRA_8888_PRE },
+
+  /* {A,X}BGR channel ordering */
+        { formatToDescriptorConst(VG_sXBGR_8888), VG_sXBGR_8888 },
+        { formatToDescriptorConst(VG_sABGR_8888), VG_sABGR_8888 },
+        { formatToDescriptorConst(VG_sABGR_8888_PRE), VG_sABGR_8888_PRE },
+        { formatToDescriptorConst(VG_sABGR_1555), VG_sABGR_1555 },
+        { formatToDescriptorConst(VG_sABGR_4444), VG_sABGR_4444 },
+        { formatToDescriptorConst(VG_lXBGR_8888), VG_lXBGR_8888 },
+        { formatToDescriptorConst(VG_lABGR_8888), VG_lABGR_8888 },
+        { formatToDescriptorConst(VG_lABGR_8888_PRE), VG_lABGR_8888_PRE },
+    };
+
+    for (size_t i = 0; i < sizeof(map)/sizeof(map[0]); i++)
+    {
+        if (isDescEqualToMapping(desc, map[i]))
+            return map[i].format;
+    }
+    RI_ASSERT(false);
+    return (VGImageFormat)-1;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Checks if the pixel format descriptor is valid (i.e. all the
+*           values are supported by the RI)
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool Color::isValidDescriptor(const Color::Descriptor& desc)
+{
+    //A valid descriptor has 1, 2, 4, 8, 16, or 32 bits per pixel, and either luminance or rgba channels, but not both.
+    //Any of the rgba channels can be missing, and not all bits need to be used. Maximum channel bit depth is 8.
+    int rb = desc.redBits;
+    int gb = desc.greenBits;
+    int bb = desc.blueBits;
+    int ab = desc.alphaBits;
+    int lb = desc.luminanceBits;
+    int rs = desc.redShift;
+    int gs = desc.greenShift;
+    int bs = desc.blueShift;
+    int as = desc.alphaShift;
+    int ls = desc.luminanceShift;
+    int bpp = desc.bitsPerPixel;
+
+    int rgbaBits = rb + gb + bb + ab;
+    if(rb < 0 || rb > 8 || rs < 0 || rs + rb > bpp || !(rb || !rs))
+        return false;	//invalid channel description
+    if(gb < 0 || gb > 8 || gs < 0 || gs + gb > bpp || !(gb || !gs))
+        return false;	//invalid channel description
+    if(bb < 0 || bb > 8 || bs < 0 || bs + bb > bpp || !(bb || !bs))
+        return false;	//invalid channel description
+    if(ab < 0 || ab > 8 || as < 0 || as + ab > bpp || !(ab || !as))
+        return false;	//invalid channel description
+    if(lb < 0 || lb > 8 || ls < 0 || ls + lb > bpp || !(lb || !ls))
+        return false;	//invalid channel description
+
+#if 0
+    if(rgbaBits && lb)
+        return false;	//can't have both rgba and luminance
+#endif
+    if(!rgbaBits && !lb)
+        return false;	//must have either rgba or luminance
+    if(rgbaBits)
+    {	//rgba
+        if(rb+gb+bb == 0)
+        {	//alpha only
+            if(rs || gs || bs || as || ls)
+                return false;	//wrong shifts (even alpha shift must be zero)
+            if((ab != 1 && ab != 2  && ab != 4 && ab != 8) || bpp != ab)
+                return false;	//alpha size must be 1, 2, 4, or, 8, bpp must match
+        }
+        else
+        {	//rgba
+            if(rgbaBits > bpp)
+                return false;	//bpp must be greater than or equal to the sum of rgba bits
+            if(!(bpp == 32 || bpp == 16 || bpp == 8))
+                return false;	//only 1, 2, and 4 byte formats are supported for rgba
+
+            unsigned int rm = bitsToMask((unsigned int)rb, (unsigned int)rs);
+            unsigned int gm = bitsToMask((unsigned int)gb, (unsigned int)gs);
+            unsigned int bm = bitsToMask((unsigned int)bb, (unsigned int)bs);
+            unsigned int am = bitsToMask((unsigned int)ab, (unsigned int)as);
+            if((rm & gm) || (rm & bm) || (rm & am) || (gm & bm) || (gm & am) || (bm & am))
+                return false;	//channels overlap
+        }
+    }
+    else
+    {	//luminance
+        if(rs || gs || bs || as || ls)
+            return false;	//wrong shifts (even luminance shift must be zero)
+        if(!(lb == 1 || lb == 8) || bpp != lb)
+            return false;	//luminance size must be either 1 or 8, bpp must match
+    }
+
+    if(desc.vgFormat != -1)
+    {
+        if(!isValidImageFormat(desc.vgFormat))
+            return false;	//invalid image format
+
+        Descriptor d = formatToDescriptor(desc.vgFormat);
+        if(d.redBits != rb || d.greenBits != gb || d.blueBits != bb || d.alphaBits != ab || d.luminanceBits != lb ||
+           d.redShift != rs || d.greenShift != gs || d.blueShift != bs || d.alphaShift != as || d.luminanceShift != ls ||
+           d.bitsPerPixel != bpp)
+           return false;	//if the descriptor has a VGImageFormat, it must match the bits, shifts, and bpp
+    } 
+
+    if((unsigned int)desc.internalFormat & ~(Color::PREMULTIPLIED | Color::NONLINEAR | Color::LUMINANCE))
+        return false;	//invalid internal format
+
+    return true;
+}
+
+//==============================================================================================
+
+//==============================================================================================
+
+IntegerColor::IntegerColor(const Color& color)
+{
+    r = (RIuint32)(color.r * 255.0f + 0.5f);
+    g = (RIuint32)(color.g * 255.0f + 0.5f);
+    b = (RIuint32)(color.b * 255.0f + 0.5f);
+    a = (RIuint32)(color.a * 255.0f + 0.5f);
+}
+
+//==============================================================================================
+
+//==============================================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Constructs a blank image.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Image::Image(const Color::Descriptor& desc, int width, int height, VGbitfield allowedQuality) :
+    m_desc(desc),
+    m_width(width),
+    m_height(height),
+    m_allowedQuality(allowedQuality),
+    m_inUse(0),
+    m_stride(0),
+    m_data(NULL),
+    m_referenceCount(0),
+    m_ownsData(true),
+    m_parent(NULL),
+    m_storageOffsetX(0),
+    m_storageOffsetY(0),
+    m_unsafeData(false)
+{
+    RI_ASSERT(Color::isValidDescriptor(m_desc));
+    RI_ASSERT(width > 0 && height > 0);
+
+    m_stride = (m_width*m_desc.bitsPerPixel+7)/8;
+
+    m_data = RI_NEW_ARRAY(RIuint8, m_stride*m_height);	//throws bad_alloc
+    memset(m_data, 0, m_stride*m_height);	//clear image
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Constructs an image that uses an external array for its data
+*			storage.
+* \param
+* \return
+* \note		This is meant for internal use to make blitting easier
+* \note     Now this is "tagged" into m_unsafeData if necessary.
+*           Using this constructor may then affect performance.
+*//*-------------------------------------------------------------------*/
+
+Image::Image(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data) :
+    m_desc(desc),
+    m_width(width),
+    m_height(height),
+    m_allowedQuality(0),
+    m_inUse(0),
+    m_stride(stride),
+    m_data(data),
+    m_referenceCount(0),
+    m_ownsData(false),
+    m_parent(NULL),
+    m_storageOffsetX(0),
+    m_storageOffsetY(0),
+    m_unsafeData(false)
+{
+    RI_ASSERT(Color::isValidDescriptor(m_desc));
+    RI_ASSERT(width > 0 && height > 0);
+    RI_ASSERT(data);
+    setUnsafe(true); // External data always potentially unsafe, see note above.
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Construcs a child image.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Image::Image(Image* parent, int x, int y, int width, int height) :
+    m_desc(Color::formatToDescriptor(VG_sRGBA_8888)),	//dummy initialization, will be overwritten below (can't read from parent->m_desc before knowing the pointer is valid)
+    m_width(width),
+    m_height(height),
+    m_allowedQuality(0),
+    m_inUse(0),
+    m_stride(0),
+    m_data(NULL),
+    m_referenceCount(0),
+    m_ownsData(false),
+    m_parent(parent),
+    m_storageOffsetX(0),
+    m_storageOffsetY(0),
+    m_unsafeData(false)
+{
+    RI_ASSERT(parent);
+    RI_ASSERT(x >= 0 && y >= 0 && width > 0 && height > 0);
+    RI_ASSERT(RI_INT_ADDSATURATE(x,width) <= parent->m_width && RI_INT_ADDSATURATE(y,height) <= parent->m_height);	//child image must be contained in parent
+
+    m_desc = parent->m_desc;
+    RI_ASSERT(Color::isValidDescriptor(m_desc));
+    m_allowedQuality = parent->m_allowedQuality;
+    m_stride = parent->m_stride;
+    m_data = parent->m_data;
+    m_storageOffsetX = parent->m_storageOffsetX + x;
+    m_storageOffsetY = parent->m_storageOffsetY + y;
+
+    //increase the reference and use count of the parent
+    addInUse();
+    parent->addInUse();
+    parent->addReference();
+    m_unsafeData = parent->m_unsafeData;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Image destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Image::~Image()
+{
+    RI_ASSERT(m_referenceCount == 0);
+
+    if(m_parent)
+    {
+        //decrease the reference and use count of the parent
+        removeInUse();
+        m_parent->removeInUse();
+        if(!m_parent->removeReference())
+            RI_DELETE(m_parent);
+    }
+    RI_ASSERT(m_inUse == 0);
+
+
+    if(m_ownsData)
+    {
+        RI_ASSERT(!m_parent);		//can't have parent if owns the data
+        RI_DELETE_ARRAY(m_data);	//delete image data if we own it
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns true if the two images share pixels.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool Image::overlaps(const Image* src) const
+{
+    RI_ASSERT(src);
+
+    if(m_data != src->m_data)
+        return false;	//images don't share data
+
+    //check if the image storage regions overlap
+    Rectangle r(m_storageOffsetX, m_storageOffsetY, m_width, m_height);
+    r.intersect(Rectangle(src->m_storageOffsetX, src->m_storageOffsetY, src->m_width, src->m_height));
+    if(!r.width || !r.height)
+        return false;	//intersection is empty, images don't overlap
+
+    return true;
+}
+
+/**
+ * \brief   Expand log2 bpp packed pixel (single value) to 8 bits. This will
+ *          Result in 8, 4, or 2 same pixel values to be packed into the return value.
+ */
+RI_INLINE static RIuint32 logExpand8(RIuint32 packedColor, int srcBits)
+{
+    RI_ASSERT(srcBits == 4 || srcBits == 2 || srcBits == 1);
+    RIuint32 ret = packedColor;
+    int n = srcBits;
+    while (n < 8)
+    {
+        ret |= ret << n;
+        n += n;
+    }
+    return ret;
+}
+
+RI_INLINE void Image::fillPacked(RIuint32 packedColor)
+{
+    RIuint32 pc = packedColor;
+    int Bpp = m_desc.bitsPerPixel / 8;
+    int nSetsPerScanline = m_width;
+
+    RI_ASSERT(nSetsPerScanline);
+    // \todo 1bpp and 4bpp mask formats must be supported. fillPackedPixels should
+    // automatically work, but riMemSet32 path needs a bit more logic.
+    // \note < 8bpp formats are always rounded to 8-bit boundaries at scanline end.
+    // It is assumed that the "padding bits" may be filled.
+        
+    if (m_desc.bitsPerPixel < 8)
+    {
+        pc = logExpand8(packedColor, m_desc.bitsPerPixel);
+        Bpp = 1;
+        nSetsPerScanline = (m_width * m_desc.bitsPerPixel + 7) / 8;
+        //nSetsPerScanline /= (8/m_desc.bitsPerPixel);
+    }
+
+    RI_ASSERT(Bpp <= 4 && Bpp >= 1);
+
+    if (m_stride == ((m_desc.bitsPerPixel*m_width+7)/8))
+    {
+        const int nPixels = nSetsPerScanline * m_height;
+        riMemSet32(m_data, pc, nPixels, Bpp);
+    } else
+    {
+        RIuint8 *ptr = (RIuint8*)m_data;
+        // set per-scanline
+        for (int y = 0; y < m_height; y++)
+        {
+            riMemSet32(ptr, pc, nSetsPerScanline, Bpp); 
+            ptr += m_stride;
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Clears a rectangular portion of an image with the given clear color.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::clear(const Color& clearColor, int x, int y, int w, int h)
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(m_referenceCount > 0);
+
+
+    //intersect clear region with image bounds
+    Rectangle r(0,0,m_width,m_height);
+    r.intersect(Rectangle(x,y,w,h));
+    if(!r.width || !r.height)
+        return;		//intersection is empty or one of the rectangles is invalid
+
+    Color col = clearColor;
+    col.clamp();
+    col.convert(getDescriptor().internalFormat);
+
+    IntegerColor ic = IntegerColor(col);
+    ic.truncateColor(getDescriptor());
+    const RIuint32 c = ic.getPackedColor(getDescriptor());
+
+    if (r.width == getWidth() && r.height == getHeight() && !m_parent)
+        fillPacked(c);
+    else
+    {
+        fillPackedRectangle(r.x, r.y, r.width, r.height, c);
+    }
+}
+
+#if 0
+static RIfloat ditherChannel(RIfloat c, int bits, RIfloat m)
+{
+    RIfloat fc = c * (RIfloat)((1<<bits)-1);
+    RIfloat ic = (RIfloat)floor(fc);
+    if(fc - ic > m) ic += 1.0f;
+    return RI_MIN(ic / (RIfloat)((1<<bits)-1), 1.0f);
+}
+#endif
+
+static void computeBlitRegion(int& sx, int& sy, int& dx, int& dy, int& w, int& h, int srcWidth, int srcHeight, int dstWidth, int dstHeight)
+{
+    RI_ASSERT(w > 0 && h > 0);
+    sx = RI_INT_MIN(RI_INT_MAX(sx, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2));
+    sy = RI_INT_MIN(RI_INT_MAX(sy, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2));
+    dx = RI_INT_MIN(RI_INT_MAX(dx, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2));
+    dy = RI_INT_MIN(RI_INT_MAX(dy, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2));
+    w = RI_INT_MIN(w, (int)(RI_INT32_MAX>>2));
+    h = RI_INT_MIN(h, (int)(RI_INT32_MAX>>2));
+    int srcsx = sx, srcex = sx + w, dstsx = dx, dstex = dx + w;
+    if(srcsx < 0)
+    {
+        dstsx -= srcsx;
+        srcsx = 0;
+    }
+    if(srcex > srcWidth)
+    {
+        dstex -= srcex - srcWidth;
+        srcex = srcWidth;
+    }
+    if(dstsx < 0)
+    {
+        srcsx -= dstsx;
+        dstsx = 0;
+    }
+    if(dstex > dstWidth)
+    {
+        srcex -= dstex - dstWidth;
+        dstex = dstWidth;
+    }
+    RI_ASSERT(srcsx >= 0 && dstsx >= 0 && srcex <= srcWidth && dstex <= dstWidth);
+    w = srcex - srcsx;
+    RI_ASSERT(w == dstex - dstsx);
+
+    int srcsy = sy, srcey = sy + h, dstsy = dy, dstey = dy + h;
+    if(srcsy < 0)
+    {
+        dstsy -= srcsy;
+        srcsy = 0;
+    }
+    if(srcey > srcHeight)
+    {
+        dstey -= srcey - srcHeight;
+        srcey = srcHeight;
+    }
+    if(dstsy < 0)
+    {
+        srcsy -= dstsy;
+        dstsy = 0;
+    }
+    if(dstey > dstHeight)
+    {
+        srcey -= dstey - dstHeight;
+        dstey = dstHeight;
+    }
+    RI_ASSERT(srcsy >= 0 && dstsy >= 0 && srcey <= srcHeight && dstey <= dstHeight);
+    h = srcey - srcsy;
+    RI_ASSERT(h == dstey - dstsy);
+    sx = srcsx;
+    sy = srcsy;
+    dx = dstsx;
+    dy = dstsy;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Blits a source region to destination. Source and destination
+*			can overlap.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+// \todo Extract dithering kernel and put it into the blitter
+#if 0
+void Image::blit(VGContext* context, const Image* src, int sx, int sy, int dx, int dy, int w, int h, bool dither)
+{
+    //img=>img: vgCopyImage
+    //img=>user: vgGetImageSubData
+    //user=>img: vgImageSubData
+    
+    // \todo Implement dither to blitter.
+    this->blit(context, src, sx, sy, dx, dy, w, h, NULL, dither);
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    computeBlitRegion(sx, sy, dx, dy, w, h, src.m_width, src.m_height, m_width, m_height);
+    if(w <= 0 || h <= 0)
+        return;	//zero area
+
+    Array<Color> tmp;
+    tmp.resize(w*h);	//throws bad_alloc
+
+    //copy source region to tmp
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color c = src.readPixel(sx + i, sy + j);
+            c.convert(m_desc.internalFormat);
+            tmp[j*w+i] = c;
+        }
+    }
+
+    int rbits = m_desc.redBits, gbits = m_desc.greenBits, bbits = m_desc.blueBits, abits = m_desc.alphaBits;
+    if(m_desc.isLuminance())
+    {
+        rbits = gbits = bbits = m_desc.luminanceBits;
+        abits = 0;
+    }
+
+    //write tmp to destination region
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color col = tmp[j*w+i];
+
+            if(dither)
+            {
+                static const int matrix[16] = {
+                    0,  8,  2,  10,
+                    12, 4,  14, 6,
+                    3,  11, 1,  9,
+                    15, 7,  13, 5};
+                int x = i & 3;
+                int y = j & 3;
+                RIfloat m = matrix[y*4+x] / 16.0f;
+
+                if(rbits) col.r = ditherChannel(col.r, rbits, m);
+                if(gbits) col.g = ditherChannel(col.g, gbits, m);
+                if(bbits) col.b = ditherChannel(col.b, bbits, m);
+                if(abits) col.a = ditherChannel(col.a, abits, m);
+            }
+
+            writePixel(dx + i, dy + j, col);
+        }
+    }
+}
+#endif
+
+/**
+ * \brief   Common body for drawImage-functions (one is the actual drawImage, and the
+ *          other one is used for scissored image-set operations.
+ * \todo    Reorganize all image draw operations to use this function. 
+ */
+static bool drawImageBody(VGContext* context, Image* image, const Matrix3x3& userToSurfaceMatrix,
+    VGImageQuality imageQuality,
+    VGBlendMode blendMode,
+    bool hasMasking,
+    bool hasColorTransform,
+    VGImageMode imageMode)
+{
+    Drawable* drawable = context->getCurrentDrawable();
+    if(!drawable)
+        return false;   //no EGL surface is current at the moment
+
+    Image* img = (Image*)image;
+    //transform image corners into the surface space
+    Vector3 p0(0, 0, 1);
+    Vector3 p1(0, (RIfloat)img->getHeight(), 1);
+    Vector3 p2((RIfloat)img->getWidth(), (RIfloat)img->getHeight(), 1);
+    Vector3 p3((RIfloat)img->getWidth(), 0, 1);
+
+    p0 = userToSurfaceMatrix * p0;
+    p1 = userToSurfaceMatrix * p1;
+    p2 = userToSurfaceMatrix * p2;
+    p3 = userToSurfaceMatrix * p3;
+    if(p0.z <= 0.0f || p1.z <= 0.0f || p2.z <= 0.0f || p3.z <= 0.0f)
+        return false;
+
+    //projection
+    p0 *= 1.0f/p0.z;
+    p1 *= 1.0f/p1.z;
+    p2 *= 1.0f/p2.z;
+    p3 *= 1.0f/p3.z;
+
+    Rasterizer& rasterizer = context->m_rasterizer;
+    rasterizer.clear();
+
+    if(context->m_scissoring)
+        rasterizer.setScissor(context->m_scissor);	//throws bad_alloc
+
+    PixelPipe& pixelPipe = context->m_pixelPipe;
+    pixelPipe.setTileFillColor(context->m_tileFillColor);
+    pixelPipe.setPaint((Paint*)context->m_fillPaint);
+    const bool aa = imageQuality == VG_IMAGE_QUALITY_NONANTIALIASED ? false : true;
+    rasterizer.setAntiAliasing(aa);
+    pixelPipe.setImageQuality(imageQuality);
+    pixelPipe.setBlendMode(blendMode);
+    pixelPipe.setRenderToMask(false);
+    pixelPipe.setDrawable(drawable);
+    pixelPipe.setMask(hasMasking);
+    pixelPipe.setColorTransform(hasColorTransform, context->m_colorTransformValues);
+
+    Matrix3x3 surfaceToImageMatrix = userToSurfaceMatrix;
+    Matrix3x3 surfaceToPaintMatrix = userToSurfaceMatrix * context->m_fillPaintToUser;
+    if(surfaceToImageMatrix.invert() && surfaceToPaintMatrix.invert())
+    {
+        VGImageMode imode = imageMode;
+
+        if(!surfaceToPaintMatrix.isAffine())
+            imode = VG_DRAW_IMAGE_NORMAL;	//if paint matrix is not affine, always use normal image mode
+
+        surfaceToPaintMatrix[2].set(0,0,1);	//force affine
+
+        pixelPipe.setImage(img, imode);
+        pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+        pixelPipe.setSurfaceToImageMatrix(surfaceToImageMatrix);
+        pixelPipe.prepareSpanUniforms(aa);
+        rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_EVEN_ODD, &pixelPipe);
+
+        rasterizer.addEdge(Vector2(p0.x,p0.y), Vector2(p1.x,p1.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p1.x,p1.y), Vector2(p2.x,p2.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p2.x,p2.y), Vector2(p3.x,p3.y));	//throws bad_alloc
+        rasterizer.addEdge(Vector2(p3.x,p3.y), Vector2(p0.x,p0.y));	//throws bad_alloc
+
+        rasterizer.fill();	//throws bad_alloc
+    }
+
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Converts from multisampled format to display format.
+* \param    unsafeInput     Data may contain incorrect values (user data)     
+* \return
+* \note     May throw std::bad_alloc on cases where blitting within the
+*           same buffer and overlapping regions (this may change in the
+*           future).
+*//*-------------------------------------------------------------------*/
+
+void Image::blit(VGContext* context, const Image* src, 
+    int sx, int sy, int dx, int dy, int w, int h, 
+    Array<Rectangle>* scissors,
+    bool dither)
+{
+    bool overlap = false;
+    (void)dither;
+    DynamicBlitter& blitter = context->getBlitter();
+
+    //RI_ASSERT(!src->isInUse(this));
+    //int isx = sx, isy = sy, idx = dx, idy = dy, iw = w, ih = h;
+
+    computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), m_width, m_height);
+
+    if(w <= 0 || h <= 0)
+        return;	//zero area
+
+    if (this->m_data == src->m_data)
+    {
+        // The images may overlap.
+        int minsx = RI_INT_MIN(sx, dx);
+        int minsy = RI_INT_MIN(sy, dy);
+        int maxsx = RI_INT_MAX(sx, dx);
+        int maxsy = RI_INT_MAX(sy, dy);
+
+        if ((maxsx < (minsx + w)) && (maxsy < (minsy + h)))
+        {
+            overlap = true;
+        }
+    }
+
+    if (!scissors)
+    {
+        // Currently the blitter does not support scissors
+        if (!overlap)
+        {
+            blitter.prepareBlit(this, src, sx+src->m_storageOffsetX, sy+src->m_storageOffsetY, 
+                dx+m_storageOffsetX, dy+m_storageOffsetY, w, h);
+            blitter.blit();
+        } else
+        {
+            Image temp(src->getDescriptor(), w, h, VG_IMAGE_QUALITY_NONANTIALIASED);
+            blitter.prepareBlit(&temp, src, sx+src->m_storageOffsetX, sy+src->m_storageOffsetY, 0, 0, w, h);
+            blitter.blit();
+            blitter.prepareBlit(this, &temp, 0, 0, dx+m_storageOffsetX, dy+m_storageOffsetY, w, h);
+            blitter.blit();
+        }
+    } else
+    {
+        // For the moment, use the generic poly-rasterizer for scissored images.
+        if (!overlap)
+        {
+            // Create a child image
+            Image blitImage((Image*)src, sx, sy, w, h);
+            Matrix3x3 tx;
+            tx.set(1, 0, dx, 0, 1, dy, 0, 0, 1);
+
+            drawImageBody(context, &blitImage, tx,
+                        VG_IMAGE_QUALITY_NONANTIALIASED,
+                        VG_BLEND_SRC,
+                        false,
+                        false,
+                        VG_DRAW_IMAGE_NORMAL);
+        } else
+        {
+            // Create a copy of the source region
+            Image temp(src->getDescriptor(), w, h, VG_IMAGE_QUALITY_NONANTIALIASED);
+            blitter.prepareBlit(&temp, src, sx, sy, 0, 0, w, h);
+            blitter.blit();
+
+            Image blitImage((Image*)src, sx, sy, w, h);
+            Matrix3x3 tx;
+            tx.set(1, 0, dx, 0, 1, dy, 0, 0, 1);
+
+            drawImageBody(context, &blitImage, tx,
+                        VG_IMAGE_QUALITY_NONANTIALIASED,
+                        VG_BLEND_SRC,
+                        false,
+                        false,
+                        VG_DRAW_IMAGE_NORMAL);
+        }
+    }
+
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns the color at pixel (x,y).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Image::readPixel(int x, int y) const
+{
+    const RIuint32 p = readPackedPixel(x, y);
+
+    Color c;
+    c.unpack(p, m_desc);
+    return c;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Writes the color to pixel (x,y). Internal color formats must
+*			match.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::writePixel(int x, int y, const Color& c)
+{
+    RI_ASSERT(c.getInternalFormat() == m_desc.internalFormat);
+
+    RIuint32 p = c.pack(m_desc);
+    writePackedPixel(x, y, p);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Writes a filtered color to destination surface
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::writeFilteredPixel(int i, int j, const Color& color, VGbitfield channelMask)
+{
+    //section 3.4.4: before color space conversion, premultiplied colors are
+    //clamped to alpha, and the color is converted to nonpremultiplied format
+    //section 11.2: how to deal with channel mask
+    //step 1
+    Color f = color;
+    f.clamp();			//vgColorMatrix and vgLookups can produce colors that exceed alpha or [0,1] range
+
+    //step 2: color space conversion
+    f.convert((Color::InternalFormat)(m_desc.internalFormat & (Color::NONLINEAR | Color::LUMINANCE)));
+
+    //step 3: read the destination color and convert it to nonpremultiplied
+    Color d = readPixel(i,j);
+    d.unpremultiply();
+    RI_ASSERT(d.getInternalFormat() == f.getInternalFormat());
+
+    //step 4: replace the destination channels specified by the channelMask (channelmask is ignored for luminance formats)
+    if(!m_desc.isLuminance())
+    {   //rgba format => use channelmask
+        if(channelMask & VG_RED)
+            d.r = f.r;
+        if(channelMask & VG_GREEN)
+            d.g = f.g;
+        if(channelMask & VG_BLUE)
+            d.b = f.b;
+        if(channelMask & VG_ALPHA)
+            d.a = f.a;
+    }
+    else d = f;
+
+    //step 5: if destination is premultiplied, convert to premultiplied format
+    if(m_desc.isPremultiplied())
+        d.premultiply();
+    //write the color to destination
+    writePixel(i,j,d);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Reads the pixel (x,y) and converts it into an alpha mask value.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RIfloat Image::readMaskPixel(int x, int y) const
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(x >= 0 && x < m_width);
+    RI_ASSERT(y >= 0 && y < m_height);
+    RI_ASSERT(m_referenceCount > 0);
+
+    Color c = readPixel(x,y);
+    if(m_desc.isLuminance())
+    {
+        return c.r;
+    }
+    else
+    {	//rgba
+        if(m_desc.alphaBits)
+            return c.a;
+        return c.r;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Writes the alpha mask to pixel (x,y).
+* \param
+* \return
+* \note		Overwrites color.
+*//*-------------------------------------------------------------------*/
+
+void Image::writeMaskPixel(int x, int y, RIfloat m)
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(x >= 0 && x < m_width);
+    RI_ASSERT(y >= 0 && y < m_height);
+    RI_ASSERT(m_referenceCount > 0);
+
+    //if luminance or no alpha, red channel will be used, otherwise alpha channel will be used
+    writePixel(x, y, Color(m,m,m,m,m_desc.internalFormat));
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Reads a texel (u,v) at the given mipmap level. Tiling modes and
+*			color space conversion are applied. Outputs color in premultiplied
+*			format.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Image::readTexel(int u, int v, int level, VGTilingMode tilingMode, const Color& tileFillColor) const
+{
+    const Image* image = this;
+    if( level > 0 )
+    {
+        RI_ASSERT(false);
+    }
+    RI_ASSERT(image);
+
+    Color p;
+    if(tilingMode == VG_TILE_FILL)
+    {
+        if(u < 0 || v < 0 || u >= image->m_width || v >= image->m_height)
+            p = tileFillColor;
+        else
+            p = image->readPixel(u, v);
+    }
+    else if(tilingMode == VG_TILE_PAD)
+    {
+        u = RI_INT_MIN(RI_INT_MAX(u,0),image->m_width-1);
+        v = RI_INT_MIN(RI_INT_MAX(v,0),image->m_height-1);
+        p = image->readPixel(u, v);
+    }
+    else if(tilingMode == VG_TILE_REPEAT)
+    {
+        u = RI_INT_MOD(u, image->m_width);
+        v = RI_INT_MOD(v, image->m_height);
+        p = image->readPixel(u, v);
+    }
+    else
+    {
+        RI_ASSERT(tilingMode == VG_TILE_REFLECT);
+
+        u = RI_INT_MOD(u, image->m_width*2);
+        v = RI_INT_MOD(v, image->m_height*2);
+        if( u >= image->m_width ) u = image->m_width*2-1 - u;
+        if( v >= image->m_height ) v = image->m_height*2-1 - v;
+        p = image->readPixel(u, v);
+    }
+
+    p.premultiply();    //interpolate in premultiplied format
+    return p;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Maps point (x,y) to an image and returns a filtered,
+*			premultiplied color value.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Image::resample(RIfloat x, RIfloat y, const Matrix3x3& surfaceToImage, VGImageQuality quality, VGTilingMode tilingMode, const Color& tileFillColor)	//throws bad_alloc
+{
+    RI_ASSERT(m_referenceCount > 0);
+
+    VGbitfield aq = getAllowedQuality();
+    aq &= (VGbitfield)quality;
+
+    Vector3 uvw(x,y,1.0f);
+    uvw = surfaceToImage * uvw;
+    RIfloat oow = 1.0f / uvw.z;
+    uvw *= oow;
+
+#if 0
+    if(aq & VG_IMAGE_QUALITY_BETTER)
+    {	//EWA on mipmaps
+        makeMipMaps();	//throws bad_alloc
+
+        Color::InternalFormat procFormat = (Color::InternalFormat)(m_desc.internalFormat | Color::PREMULTIPLIED);
+
+        RIfloat m_pixelFilterRadius = 1.25f;
+        RIfloat m_resamplingFilterRadius = 1.25f;
+
+        RIfloat Ux = (surfaceToImage[0][0] - uvw.x * surfaceToImage[2][0]) * oow * m_pixelFilterRadius;
+        RIfloat Vx = (surfaceToImage[1][0] - uvw.y * surfaceToImage[2][0]) * oow * m_pixelFilterRadius;
+        RIfloat Uy = (surfaceToImage[0][1] - uvw.x * surfaceToImage[2][1]) * oow * m_pixelFilterRadius;
+        RIfloat Vy = (surfaceToImage[1][1] - uvw.y * surfaceToImage[2][1]) * oow * m_pixelFilterRadius;
+        RIfloat U0 = uvw.x;
+        RIfloat V0 = uvw.y;
+
+        //calculate mip level
+        int level = 0;
+        RIfloat axis1sq = Ux*Ux + Vx*Vx;
+        RIfloat axis2sq = Uy*Uy + Vy*Vy;
+        RIfloat minorAxissq = RI_MIN(axis1sq,axis2sq);
+        while(minorAxissq > 9.0f && level < m_mipmaps.size())	//half the minor axis must be at least three texels
+        {
+            level++;
+            minorAxissq *= 0.25f;
+        }
+
+        RIfloat sx = 1.0f;
+        RIfloat sy = 1.0f;
+        if(level > 0)
+        {
+            sx = (RIfloat)m_mipmaps[level-1]->m_width / (RIfloat)m_width;
+            sy = (RIfloat)m_mipmaps[level-1]->m_height / (RIfloat)m_height;
+        }
+        Ux *= sx;
+        Vx *= sx;
+        U0 *= sx;
+        Uy *= sy;
+        Vy *= sy;
+        V0 *= sy;
+
+        //clamp filter size so that filtering doesn't take excessive amount of time (clamping results in aliasing)
+        RIfloat lim = 100.0f;
+        axis1sq = Ux*Ux + Vx*Vx;
+        axis2sq = Uy*Uy + Vy*Vy;
+        if( axis1sq > lim*lim )
+        {
+            RIfloat s = lim / (RIfloat)sqrt(axis1sq);
+            Ux *= s;
+            Vx *= s;
+        }
+        if( axis2sq > lim*lim )
+        {
+            RIfloat s = lim / (RIfloat)sqrt(axis2sq);
+            Uy *= s;
+            Vy *= s;
+        }
+
+
+        //form elliptic filter by combining texel and pixel filters
+        RIfloat A = Vx*Vx + Vy*Vy + 1.0f;
+        RIfloat B = -2.0f*(Ux*Vx + Uy*Vy);
+        RIfloat C = Ux*Ux + Uy*Uy + 1.0f;
+        //scale by the user-defined size of the kernel
+        A *= m_resamplingFilterRadius;
+        B *= m_resamplingFilterRadius;
+        C *= m_resamplingFilterRadius;
+
+        //calculate bounding box in texture space
+        RIfloat usize = (RIfloat)sqrt(C);
+        RIfloat vsize = (RIfloat)sqrt(A);
+        int u1 = (int)floor(U0 - usize + 0.5f);
+        int u2 = (int)floor(U0 + usize + 0.5f);
+        int v1 = (int)floor(V0 - vsize + 0.5f);
+        int v2 = (int)floor(V0 + vsize + 0.5f);
+        if( u1 == u2 || v1 == v2 )
+            return Color(0,0,0,0,procFormat);
+
+        //scale the filter so that Q = 1 at the cutoff radius
+        RIfloat F = A*C - 0.25f * B*B;
+        if( F <= 0.0f )
+            return Color(0,0,0,0,procFormat);	//invalid filter shape due to numerical inaccuracies => return black
+        RIfloat ooF = 1.0f / F;
+        A *= ooF;
+        B *= ooF;
+        C *= ooF;
+
+        //evaluate filter by using forward differences to calculate Q = A*U^2 + B*U*V + C*V^2
+        Color color(0,0,0,0,procFormat);
+        RIfloat sumweight = 0.0f;
+        RIfloat DDQ = 2.0f * A;
+        RIfloat U = (RIfloat)u1 - U0 + 0.5f;
+        for(int v=v1;v<v2;v++)
+        {
+            RIfloat V = (RIfloat)v - V0 + 0.5f;
+            RIfloat DQ = A*(2.0f*U+1.0f) + B*V;
+            RIfloat Q = (C*V+B*U)*V + A*U*U;
+            for(int u=u1;u<u2;u++)
+            {
+                if( Q >= 0.0f && Q < 1.0f )
+                {	//Q = r^2, fit gaussian to the range [0,1]
+                    RIfloat weight = (RIfloat)exp(-0.5f * 10.0f * Q);	//gaussian at radius 10 equals 0.0067
+                    color += weight * readTexel(u, v, level, tilingMode, tileFillColor);
+                    sumweight += weight;
+                }
+                Q += DQ;
+                DQ += DDQ;
+            }
+        }
+        if( sumweight == 0.0f )
+            return Color(0,0,0,0,procFormat);
+        RI_ASSERT(sumweight > 0.0f);
+        sumweight = 1.0f / sumweight;
+        return color * sumweight;
+    }
+    else
+#endif
+        //if(aq & VG_IMAGE_QUALITY_FASTER)
+    if(aq & VG_IMAGE_QUALITY_BETTER)
+    {	//bilinear
+        uvw.x -= 0.5f;
+        uvw.y -= 0.5f;
+        int u = (int)floor(uvw.x);
+        int v = (int)floor(uvw.y);
+        Color c00 = readTexel(u,v, 0, tilingMode, tileFillColor);
+        Color c10 = readTexel(u+1,v, 0, tilingMode, tileFillColor);
+        Color c01 = readTexel(u,v+1, 0, tilingMode, tileFillColor);
+        Color c11 = readTexel(u+1,v+1, 0, tilingMode, tileFillColor);
+        RIfloat fu = uvw.x - (RIfloat)u;
+        RIfloat fv = uvw.y - (RIfloat)v;
+        Color c0 = c00 * (1.0f - fu) + c10 * fu;
+        Color c1 = c01 * (1.0f - fu) + c11 * fu;
+        return c0 * (1.0f - fv) + c1 * fv;
+    }
+    else //VG_IMAGE_QUALITY_FASTER and VG_IMAGE_QUALITY_NONANTIALIASED
+    {	//point sampling
+        return readTexel((int)floor(uvw.x), (int)floor(uvw.y), 0, tilingMode, tileFillColor);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies color matrix filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::colorMatrix(const Image& src, const RIfloat* matrix, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(matrix);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat srcFormat = src.m_desc.internalFormat;
+    Color::InternalFormat procFormat = (Color::InternalFormat)(srcFormat & ~Color::LUMINANCE);	//process in RGB, not luminance
+    if(filterFormatLinear)
+        procFormat = (Color::InternalFormat)(procFormat & ~Color::NONLINEAR);
+    else
+        procFormat = (Color::InternalFormat)(procFormat | Color::NONLINEAR);
+
+    if(filterFormatPremultiplied)
+        procFormat = (Color::InternalFormat)(procFormat | Color::PREMULTIPLIED);
+    else
+        procFormat = (Color::InternalFormat)(procFormat & ~Color::PREMULTIPLIED);
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color s = src.readPixel(i,j);	//convert to RGBA [0,1]
+            s.convert(procFormat);
+
+            Color d(0,0,0,0,procFormat);
+            d.r = matrix[0+4*0] * s.r + matrix[0+4*1] * s.g + matrix[0+4*2] * s.b + matrix[0+4*3] * s.a + matrix[0+4*4];
+            d.g = matrix[1+4*0] * s.r + matrix[1+4*1] * s.g + matrix[1+4*2] * s.b + matrix[1+4*3] * s.a + matrix[1+4*4];
+            d.b = matrix[2+4*0] * s.r + matrix[2+4*1] * s.g + matrix[2+4*2] * s.b + matrix[2+4*3] * s.a + matrix[2+4*4];
+            d.a = matrix[3+4*0] * s.r + matrix[3+4*1] * s.g + matrix[3+4*2] * s.b + matrix[3+4*3] * s.a + matrix[3+4*4];
+
+            writeFilteredPixel(i, j, d, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Reads a pixel from image with tiling mode applied.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static Color readTiledPixel(int x, int y, int w, int h, VGTilingMode tilingMode, const Array<Color>& image, const Color& edge)
+{
+    Color s;
+    if(x < 0 || x >= w || y < 0 || y >= h)
+    {	//apply tiling mode
+        switch(tilingMode)
+        {
+        case VG_TILE_FILL:
+            s = edge;
+            break;
+        case VG_TILE_PAD:
+            x = RI_INT_MIN(RI_INT_MAX(x, 0), w-1);
+            y = RI_INT_MIN(RI_INT_MAX(y, 0), h-1);
+            RI_ASSERT(x >= 0 && x < w && y >= 0 && y < h);
+            s = image[y*w+x];
+            break;
+        case VG_TILE_REPEAT:
+            x = RI_INT_MOD(x, w);
+            y = RI_INT_MOD(y, h);
+            RI_ASSERT(x >= 0 && x < w && y >= 0 && y < h);
+            s = image[y*w+x];
+            break;
+        default:
+            RI_ASSERT(tilingMode == VG_TILE_REFLECT);
+            x = RI_INT_MOD(x, w*2);
+            y = RI_INT_MOD(y, h*2);
+            if(x >= w) x = w*2-1-x;
+            if(y >= h) y = h*2-1-y;
+            RI_ASSERT(x >= 0 && x < w && y >= 0 && y < h);
+            s = image[y*w+x];
+            break;
+        }
+    }
+    else
+    {
+        RI_ASSERT(x >= 0 && x < w && y >= 0 && y < h);
+        s = image[y*w+x];
+    }
+    return s;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns processing format for filtering.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static Color::InternalFormat getProcessingFormat(Color::InternalFormat srcFormat, bool filterFormatLinear, bool filterFormatPremultiplied)
+{
+    Color::InternalFormat procFormat = (Color::InternalFormat)(srcFormat & ~Color::LUMINANCE);	//process in RGB, not luminance
+    if(filterFormatLinear)
+        procFormat = (Color::InternalFormat)(procFormat & ~Color::NONLINEAR);
+    else
+        procFormat = (Color::InternalFormat)(procFormat | Color::NONLINEAR);
+
+    if(filterFormatPremultiplied)
+        procFormat = (Color::InternalFormat)(procFormat | Color::PREMULTIPLIED);
+    else
+        procFormat = (Color::InternalFormat)(procFormat & ~Color::PREMULTIPLIED);
+    return procFormat;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies convolution filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::convolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernel, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(kernel && kernelWidth > 0 && kernelHeight > 0);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+
+    Color edge = edgeFillColor;
+    edge.clamp();
+    edge.convert(procFormat);
+
+    Array<Color> tmp;
+    tmp.resize(src.m_width*src.m_height);	//throws bad_alloc
+
+    //copy source region to tmp and do conversion
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<src.m_width;i++)
+        {
+            Color s = src.readPixel(i, j);
+            s.convert(procFormat);
+            tmp[j*src.m_width+i] = s;
+        }
+    }
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+
+            for(int kj=0;kj<kernelHeight;kj++)
+            {
+                for(int ki=0;ki<kernelWidth;ki++)
+                {
+                    int x = i+ki-shiftX;
+                    int y = j+kj-shiftY;
+                    Color s = readTiledPixel(x, y, src.m_width, src.m_height, tilingMode, tmp, edge);
+
+                    int kx = kernelWidth-ki-1;
+                    int ky = kernelHeight-kj-1;
+                    RI_ASSERT(kx >= 0 && kx < kernelWidth && ky >= 0 && ky < kernelHeight);
+
+                    sum += (RIfloat)kernel[kx*kernelHeight+ky] * s;
+                }
+            }
+
+            sum *= scale;
+            sum.r += bias;
+            sum.g += bias;
+            sum.b += bias;
+            sum.a += bias;
+
+            writeFilteredPixel(i, j, sum, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies separable convolution filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::separableConvolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernelX, const RIint16* kernelY, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(kernelX && kernelY && kernelWidth > 0 && kernelHeight > 0);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+
+    Color edge = edgeFillColor;
+    edge.clamp();
+    edge.convert(procFormat);
+
+    Array<Color> tmp;
+    tmp.resize(src.m_width*src.m_height);	//throws bad_alloc
+
+    //copy source region to tmp and do conversion
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<src.m_width;i++)
+        {
+            Color s = src.readPixel(i, j);
+            s.convert(procFormat);
+            tmp[j*src.m_width+i] = s;
+        }
+    }
+
+    Array<Color> tmp2;
+    tmp2.resize(w*src.m_height);	//throws bad_alloc
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+            for(int ki=0;ki<kernelWidth;ki++)
+            {
+                int x = i+ki-shiftX;
+                Color s = readTiledPixel(x, j, src.m_width, src.m_height, tilingMode, tmp, edge);
+
+                int kx = kernelWidth-ki-1;
+                RI_ASSERT(kx >= 0 && kx < kernelWidth);
+
+                sum += (RIfloat)kernelX[kx] * s;
+            }
+            tmp2[j*w+i] = sum;
+        }
+    }
+
+    if(tilingMode == VG_TILE_FILL)
+    {	//convolve the edge color
+        Color sum(0,0,0,0,procFormat);
+        for(int ki=0;ki<kernelWidth;ki++)
+        {
+            sum += (RIfloat)kernelX[ki] * edge;
+        }
+        edge = sum;
+    }
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+            for(int kj=0;kj<kernelHeight;kj++)
+            {
+                int y = j+kj-shiftY;
+                Color s = readTiledPixel(i, y, w, src.m_height, tilingMode, tmp2, edge);
+
+                int ky = kernelHeight-kj-1;
+                RI_ASSERT(ky >= 0 && ky < kernelHeight);
+
+                sum += (RIfloat)kernelY[ky] * s;
+            }
+
+            sum *= scale;
+            sum.r += bias;
+            sum.g += bias;
+            sum.b += bias;
+            sum.a += bias;
+
+            writeFilteredPixel(i, j, sum, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies Gaussian blur filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::gaussianBlur(const Image& src, RIfloat stdDeviationX, RIfloat stdDeviationY, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(stdDeviationX > 0.0f && stdDeviationY > 0.0f);
+    RI_ASSERT(stdDeviationX <= RI_MAX_GAUSSIAN_STD_DEVIATION && stdDeviationY <= RI_MAX_GAUSSIAN_STD_DEVIATION);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+
+    Color edge = edgeFillColor;
+    edge.clamp();
+    edge.convert(procFormat);
+
+    Array<Color> tmp;
+    tmp.resize(src.m_width*src.m_height);	//throws bad_alloc
+
+    //copy source region to tmp and do conversion
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<src.m_width;i++)
+        {
+            Color s = src.readPixel(i, j);
+            s.convert(procFormat);
+            tmp[j*src.m_width+i] = s;
+        }
+    }
+
+    RIfloat expScaleX = -1.0f / (2.0f*stdDeviationX*stdDeviationX);
+    RIfloat expScaleY = -1.0f / (2.0f*stdDeviationY*stdDeviationY);
+
+    int kernelWidth = (int)(stdDeviationX * 4.0f + 1.0f);
+    int kernelHeight = (int)(stdDeviationY * 4.0f + 1.0f);
+
+    //make a separable kernel
+    Array<RIfloat> kernelX;
+    kernelX.resize(kernelWidth*2+1);
+    int shiftX = kernelWidth;
+    RIfloat scaleX = 0.0f;
+    for(int i=0;i<kernelX.size();i++)
+    {
+        int x = i-shiftX;
+        kernelX[i] = (RIfloat)exp((RIfloat)x*(RIfloat)x * expScaleX);
+        scaleX += kernelX[i];
+    }
+    scaleX = 1.0f / scaleX;	//NOTE: using the mathematical definition of the scaling term doesn't work since we cut the filter support early for performance
+
+    Array<RIfloat> kernelY;
+    kernelY.resize(kernelHeight*2+1);
+    int shiftY = kernelHeight;
+    RIfloat scaleY = 0.0f;
+    for(int i=0;i<kernelY.size();i++)
+    {
+        int y = i-shiftY;
+        kernelY[i] = (RIfloat)exp((RIfloat)y*(RIfloat)y * expScaleY);
+        scaleY += kernelY[i];
+    }
+    scaleY = 1.0f / scaleY;	//NOTE: using the mathematical definition of the scaling term doesn't work since we cut the filter support early for performance
+
+    Array<Color> tmp2;
+    tmp2.resize(w*src.m_height);	//throws bad_alloc
+    //horizontal pass
+    for(int j=0;j<src.m_height;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+            for(int ki=0;ki<kernelX.size();ki++)
+            {
+                int x = i+ki-shiftX;
+                sum += kernelX[ki] * readTiledPixel(x, j, src.m_width, src.m_height, tilingMode, tmp, edge);
+            }
+            tmp2[j*w+i] = sum * scaleX;
+        }
+    }
+    //vertical pass
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color sum(0,0,0,0,procFormat);
+            for(int kj=0;kj<kernelY.size();kj++)
+            {
+                int y = j+kj-shiftY;
+                sum += kernelY[kj] * readTiledPixel(i, y, w, src.m_height, tilingMode, tmp2, edge);
+            }
+            writeFilteredPixel(i, j, sum * scaleY, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns lookup table format for lookup filters.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static Color::InternalFormat getLUTFormat(bool outputLinear, bool outputPremultiplied)
+{
+    Color::InternalFormat lutFormat = Color::lRGBA;
+    if(outputLinear && outputPremultiplied)
+        lutFormat = Color::lRGBA_PRE;
+    else if(!outputLinear && !outputPremultiplied)
+        lutFormat = Color::sRGBA;
+    else if(!outputLinear && outputPremultiplied)
+        lutFormat = Color::sRGBA_PRE;
+    return lutFormat;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies multi-channel lookup table filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::lookup(const Image& src, const RIuint8 * redLUT, const RIuint8 * greenLUT, const RIuint8 * blueLUT, const RIuint8 * alphaLUT, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(redLUT && greenLUT && blueLUT && alphaLUT);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+    Color::InternalFormat lutFormat = getLUTFormat(outputLinear, outputPremultiplied);
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color s = src.readPixel(i,j);	//convert to RGBA [0,1]
+            s.convert(procFormat);
+
+            Color d(0,0,0,0,lutFormat);
+            d.r = intToColor(  redLUT[colorToInt(s.r, 255)], 255);
+            d.g = intToColor(greenLUT[colorToInt(s.g, 255)], 255);
+            d.b = intToColor( blueLUT[colorToInt(s.b, 255)], 255);
+            d.a = intToColor(alphaLUT[colorToInt(s.a, 255)], 255);
+
+            writeFilteredPixel(i, j, d, channelMask);
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Applies single channel lookup table filter.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::lookupSingle(const Image& src, const RIuint32 * lookupTable, VGImageChannel sourceChannel, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask)
+{
+    RI_ASSERT(src.m_data);	//source exists
+    RI_ASSERT(m_data);	//destination exists
+    RI_ASSERT(lookupTable);
+    RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0);
+
+    //the area to be written is an intersection of source and destination image areas.
+    //lower-left corners of the images are aligned.
+    int w = RI_INT_MIN(m_width, src.m_width);
+    int h = RI_INT_MIN(m_height, src.m_height);
+    RI_ASSERT(w > 0 && h > 0);
+
+    if(src.m_desc.isLuminance())
+        sourceChannel = VG_RED;
+    else if(src.m_desc.redBits + src.m_desc.greenBits + src.m_desc.blueBits == 0)
+    {
+        RI_ASSERT(src.m_desc.alphaBits);
+        sourceChannel = VG_ALPHA;
+    }
+
+    Color::InternalFormat procFormat = getProcessingFormat(src.m_desc.internalFormat, filterFormatLinear, filterFormatPremultiplied);
+    Color::InternalFormat lutFormat = getLUTFormat(outputLinear, outputPremultiplied);
+
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            Color s = src.readPixel(i,j);	//convert to RGBA [0,1]
+            s.convert(procFormat);
+            int e;
+            switch(sourceChannel)
+            {
+            case VG_RED:
+                e = colorToInt(s.r, 255);
+                break;
+            case VG_GREEN:
+                e = colorToInt(s.g, 255);
+                break;
+            case VG_BLUE:
+                e = colorToInt(s.b, 255);
+                break;
+            default:
+                RI_ASSERT(sourceChannel == VG_ALPHA);
+                e = colorToInt(s.a, 255);
+                break;
+            }
+
+            RIuint32 l = ((const RIuint32*)lookupTable)[e];
+            Color d(0,0,0,0,lutFormat);
+            d.r = intToColor((l>>24), 255);
+            d.g = intToColor((l>>16), 255);
+            d.b = intToColor((l>> 8), 255);
+            d.a = intToColor((l    ), 255);
+
+            writeFilteredPixel(i, j, d, channelMask);
+        }
+    }
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Surface::Surface(const Color::Descriptor& desc, int width, int height, int numSamples) :
+    m_width(width),
+    m_height(height),
+    m_numSamples(numSamples),
+    m_referenceCount(0),
+    m_image(NULL)
+{
+    RI_ASSERT(width > 0 && height > 0 && numSamples > 0 && numSamples <= 32);
+    m_image = RI_NEW(Image, (desc, width*numSamples, height, 0));	//throws bad_alloc
+    m_image->addReference();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Surface::Surface(Image* image) :
+    m_width(0),
+    m_height(0),
+    m_numSamples(1),
+    m_referenceCount(0),
+    m_image(image)
+{
+    RI_ASSERT(image);
+    m_width = image->getWidth();
+    m_height = image->getHeight();
+    m_image->addReference();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Surface::Surface(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data) :
+    m_width(width),
+    m_height(height),
+    m_numSamples(1),
+    m_referenceCount(0),
+    m_image(NULL)
+{
+    RI_ASSERT(width > 0 && height > 0);
+    m_image = RI_NEW(Image, (desc, width, height, stride, data));	//throws bad_alloc
+    m_image->addReference();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Surface::~Surface()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    if(!m_image->removeReference())
+        RI_DELETE(m_image);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Surface::clear(const Color& clearColor, int x, int y, int w, int h, const Array<Rectangle>* scissors)
+{
+    RI_ASSERT(m_numSamples == 1);
+
+    Image* image = m_image;
+
+    Color col = clearColor;
+    col.clamp();
+    col.convert(m_image->getDescriptor().internalFormat);
+
+    IntegerColor ic = IntegerColor(col);
+    ic.truncateColor(m_image->getDescriptor());
+    const RIuint32 c = ic.getPackedColor(m_image->getDescriptor());
+
+    if (x != 0 || y != 0 || w != image->getWidth() || h != image->getHeight() || scissors)
+    {
+        // Simple implementation: intersect with surface and clip rects -> may clear the
+        // same area several times. Best if scissors are non-overlapping
+        Rectangle r(0,0,getWidth(),getHeight());
+        r.intersect(Rectangle(x,y,w,h));
+
+        if (r.isEmpty() || (scissors && scissors->size() == 0))
+            return;
+
+        if (scissors && scissors->size())
+        {
+            for (int i = 0; i < scissors->size(); i++)
+            {
+                Rectangle s = (*scissors)[i];
+                s.intersect(r);
+
+                if (s.isEmpty())
+                    continue;
+
+                image->fillPackedRectangle(s.x, s.y, s.width, s.height, c);
+            }
+        }
+        else
+        {
+            image->fillPackedRectangle(r.x, r.y, r.width, r.height, c);
+        }
+    }
+    else
+    {
+        // Clear the whole buffer
+
+        m_image->fillPacked(c);
+   }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#if 0
+void Surface::blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h)
+{
+    Rectangle rect;
+    rect.x = 0;
+    rect.y = 0;
+    rect.width = getWidth();
+    rect.height = getHeight();
+    Array<Rectangle> scissors;
+    scissors.push_back(rect);
+    blit(src, sx, sy, dx, dy, w, h, scissors);
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note		no overlap is possible. Single sample to single or multisample (replicate)
+*//*-------------------------------------------------------------------*/
+
+#if 0
+void Surface::blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h, const Array<Rectangle>& scissors)
+{
+    //img=>fb: vgSetPixels
+    //user=>fb: vgWritePixels
+    computeBlitRegion(sx, sy, dx, dy, w, h, src.getWidth(), src.getHeight(), getWidth(), getHeight());
+    if(w <= 0 || h <= 0)
+        return;	//zero area
+
+    Array<ScissorEdge> scissorEdges;
+    for(int i=0;i<scissors.size();i++)
+    {
+        if(scissors[i].width > 0 && scissors[i].height > 0)
+        {
+            ScissorEdge e;
+            e.miny = scissors[i].y;
+            e.maxy = RI_INT_ADDSATURATE(scissors[i].y, scissors[i].height);
+
+            e.x = scissors[i].x;
+            e.direction = 1;
+            scissorEdges.push_back(e);	//throws bad_alloc
+            e.x = RI_INT_ADDSATURATE(scissors[i].x, scissors[i].width);
+            e.direction = -1;
+            scissorEdges.push_back(e);	//throws bad_alloc
+        }
+    }
+    if(!scissorEdges.size())
+        return;	//there are no scissor rectangles => nothing is visible
+
+    //sort scissor edges by edge x
+    scissorEdges.sort();
+
+    Array<ScissorEdge> scissorAet;
+    for(int j=0;j<h;j++)
+    {
+        //gather scissor edges intersecting this scanline
+        scissorAet.clear();
+        for(int e=0;e<scissorEdges.size();e++)
+        {
+            const ScissorEdge& se = scissorEdges[e];
+            if(dy + j >= se.miny && dy + j < se.maxy)
+                scissorAet.push_back(scissorEdges[e]);	//throws bad_alloc
+        }
+        if(!scissorAet.size())
+            continue;	//scissoring is on, but there are no scissor rectangles on this scanline
+
+        //blit a scanline
+        int scissorWinding = 0;
+        int scissorIndex = 0;
+        for(int i=0;i<w;i++)
+        {
+            while(scissorIndex < scissorAet.size() && scissorAet[scissorIndex].x <= dx + i)
+                scissorWinding += scissorAet[scissorIndex++].direction;
+            RI_ASSERT(scissorWinding >= 0);
+
+            if(scissorWinding)
+            {
+                Color c = src.readPixel(sx + i, sy + j);
+                c.convert(getDescriptor().internalFormat);
+                for(int s=0;s<m_numSamples;s++)
+                    writeSample(dx + i, dy + j, s, c);
+            }
+        }
+    }
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#if 0
+void Surface::blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h)
+{
+    Rectangle rect;
+    rect.x = 0;
+    rect.y = 0;
+    rect.width = getWidth();
+    rect.height = getHeight();
+    Array<Rectangle> scissors;
+    scissors.push_back(rect);
+    blit(src, sx, sy, dx, dy, w, h, scissors);
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#if 0
+void Surface::blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h, const Array<Rectangle>& scissors)
+{
+    RI_ASSERT(m_numSamples == src->m_numSamples);
+
+    //fb=>fb: vgCopyPixels
+    computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), getWidth(), getHeight());
+    if(w <= 0 || h <= 0)
+        return;	//zero area
+
+    Array<ScissorEdge> scissorEdges;
+    for(int i=0;i<scissors.size();i++)
+    {
+        if(scissors[i].width > 0 && scissors[i].height > 0)
+        {
+            ScissorEdge e;
+            e.miny = scissors[i].y;
+            e.maxy = RI_INT_ADDSATURATE(scissors[i].y, scissors[i].height);
+
+            e.x = scissors[i].x;
+            e.direction = 1;
+            scissorEdges.push_back(e);	//throws bad_alloc
+            e.x = RI_INT_ADDSATURATE(scissors[i].x, scissors[i].width);
+            e.direction = -1;
+            scissorEdges.push_back(e);	//throws bad_alloc
+        }
+    }
+    if(!scissorEdges.size())
+        return;	//there are no scissor rectangles => nothing is visible
+
+    //sort scissor edges by edge x
+    scissorEdges.sort();
+
+    Array<Color> tmp;
+    tmp.resize(w*m_numSamples*h);	//throws bad_alloc
+
+    //copy source region to tmp
+    for(int j=0;j<h;j++)
+    {
+        for(int i=0;i<w;i++)
+        {
+            int numSamples = m_numSamples;
+            for(int s=0;s<numSamples;s++)
+            {
+                Color c = src->m_image->readPixel((sx + i)*m_numSamples+s, sy + j);
+                c.convert(m_image->getDescriptor().internalFormat);
+                tmp[(j*w+i)*m_numSamples+s] = c;
+            }
+        }
+    }
+
+    Array<ScissorEdge> scissorAet;
+    for(int j=0;j<h;j++)
+    {
+        //gather scissor edges intersecting this scanline
+        scissorAet.clear();
+        for(int e=0;e<scissorEdges.size();e++)
+        {
+            const ScissorEdge& se = scissorEdges[e];
+            if(dy + j >= se.miny && dy + j < se.maxy)
+                scissorAet.push_back(scissorEdges[e]);	//throws bad_alloc
+        }
+        if(!scissorAet.size())
+            continue;	//scissoring is on, but there are no scissor rectangles on this scanline
+
+        //blit a scanline
+        int scissorWinding = 0;
+        int scissorIndex = 0;
+        for(int i=0;i<w;i++)
+        {
+            while(scissorIndex < scissorAet.size() && scissorAet[scissorIndex].x <= dx + i)
+                scissorWinding += scissorAet[scissorIndex++].direction;
+            RI_ASSERT(scissorWinding >= 0);
+
+            if(scissorWinding)
+            {
+                int numSamples = m_numSamples;
+                for(int s=0;s<numSamples;s++)
+                {
+                    m_image->writePixel((dx + i)*m_numSamples+s, dy + j, tmp[(j*w+i)*m_numSamples+s]);
+                }
+            }
+        }
+    }
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Surface::mask(DynamicBlitter& blitter, const Image* src, VGMaskOperation operation, int x, int y, int w, int h)
+{
+    RI_ASSERT(w > 0 && h > 0);
+    RI_ASSERT(m_numSamples == 1);
+
+    if(operation == VG_CLEAR_MASK || operation == VG_FILL_MASK)
+    {
+        //intersect clear region with image bounds
+        Rectangle r(0,0,getWidth(),getHeight());
+        r.intersect(Rectangle(x,y,w,h));
+
+        if(!r.width || !r.height)
+            return;		//intersection is empty or one of the rectangles is invalid
+
+        {
+            Color mcolor(1.0f, 1.0f, 1.0f, 1.0f, Color::sRGBA_PRE);
+            if (operation == VG_CLEAR_MASK)
+                mcolor = Color(0,0,0,0, Color::sRGBA_PRE);
+            IntegerColor ic = IntegerColor(mcolor);
+            RIuint32 p = ic.getPackedMaskColor(m_image->getDescriptor());
+            m_image->fillPackedRectangle(r.x, r.y, r.width, r.height, p);
+        }
+    }
+    else
+    {
+        int sx = 0, sy = 0, dx = x, dy = y;
+
+        computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), getWidth(), getHeight());
+
+        if(w <= 0 || h <= 0)
+            return;	//zero area
+
+        blitter.enableMaskOperation(true);
+        blitter.setMaskOperation(operation);
+        blitter.prepareBlit(this->m_image, src, sx, sy, dx, dy, w, h);
+        blitter.blit();
+        blitter.enableMaskOperation(false);
+#if 0
+        RI_ASSERT(src);
+
+        int sx = 0, sy = 0, dx = x, dy = y;
+        computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), getWidth(), getHeight());
+        if(w <= 0 || h <= 0)
+            return;	//zero area
+
+        {
+            for(int j=0;j<h;j++)
+            {
+                for(int i=0;i<w;i++)
+                {
+                    RIfloat amask = src->readMaskPixel(sx + i, sy + j);
+                    if(operation == VG_SET_MASK)
+                        writeMaskCoverage(dx + i, dy + j, amask);
+                    else
+                    {
+                        RIfloat aprev = readMaskCoverage(dx + i, dy + j);
+                        RIfloat anew = 0.0f;
+                        switch(operation)
+                        {
+                        case VG_UNION_MASK:		anew = 1.0f - (1.0f - amask)*(1.0f - aprev); break;
+                        case VG_INTERSECT_MASK:	anew = amask * aprev; break;
+                        default:				anew = aprev * (1.0f - amask); RI_ASSERT(operation == VG_SUBTRACT_MASK); break;
+                        }
+                        writeMaskCoverage(dx + i, dy + j, anew);
+                    }
+                }
+            }
+        }
+#endif
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RIfloat Surface::readMaskCoverage(int x, int y) const
+{
+    RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height);
+    RI_ASSERT(m_numSamples == 1);
+    return m_image->readMaskPixel(x, y);
+}
+
+void Surface::writeMaskCoverage(int x, int y, RIfloat m)
+{
+    RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height);
+    RI_ASSERT(m_numSamples == 1);
+    m_image->writeMaskPixel(x, y, m);    //TODO support other than alpha formats but don't write to color channels?
+}
+
+unsigned int Surface::readMaskMSAA(int x, int y) const
+{
+    RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height);
+    RI_ASSERT(m_numSamples > 1);
+    unsigned int m = 0;
+    for(int i=0;i<m_numSamples;i++)
+    {
+        if(m_image->readMaskPixel(x*m_numSamples+i, y) > 0.5f)   //TODO is this the right formula for converting alpha to bit mask? does it matter?
+            m |= 1<<i;
+    }
+    return m;
+}
+
+void Surface::writeMaskMSAA(int x, int y, unsigned int m)
+{
+    RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height);
+    RI_ASSERT(m_numSamples > 1);
+    for(int i=0;i<m_numSamples;i++)
+    {
+        RIfloat a = 0.0f;
+        if(m & (1<<i))
+            a = 1.0f;
+        m_image->writeMaskPixel(x*m_numSamples+i, y, a);    //TODO support other than alpha formats but don't write to color channels?
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Surface::FSAAResolve(int x, int y) const
+{
+    if(m_numSamples == 1)
+        return readSample(x, y, 0);
+
+    Color::InternalFormat aaFormat = getDescriptor().isLuminance() ? Color::lLA_PRE : Color::lRGBA_PRE;	//antialias in linear color space
+    Color r(0.0f, 0.0f, 0.0f, 0.0f, aaFormat);
+    for(int i=0;i<m_numSamples;i++)
+    {
+        Color d = readSample(x, y, i);
+        d.convert(aaFormat);
+        r += d;
+    }
+    r *= 1.0f/m_numSamples;
+    return r;
+}
+
+
+/**
+ *	\brief	Return a resolved sample in packed format.
+ *	\note	Further operations on color may require unpack.
+ */
+RI_INLINE RIuint32 Surface::FSAAResolvePacked(int x, int y) const
+{
+    if (m_numSamples == 1)
+        return readPackedSample(x, y, 0);
+
+    RI_ASSERT(false); /* Not implemented yet. */
+    return 0xffffffffu;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Drawable::Drawable(const Color::Descriptor& desc, int width, int height, int numSamples, int maskBits) :
+    m_referenceCount(0),
+    m_color(NULL),
+    m_mask(NULL)
+{
+    RI_ASSERT(width > 0 && height > 0 && numSamples > 0 && numSamples <= 32);
+    RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8);
+    m_color = RI_NEW(Surface, (desc, width, height, numSamples));	//throws bad_alloc
+    m_color->addReference();
+    if(maskBits)
+    {
+        VGImageFormat mf = VG_A_1;
+        if(maskBits == 4)
+            mf = VG_A_4;
+        else if(maskBits == 8)
+            mf = VG_A_8;
+        m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), width, height, numSamples));
+        m_mask->addReference();
+        m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Drawable::Drawable(Image* image, int maskBits) :
+    m_referenceCount(0),
+    m_color(NULL),
+    m_mask(NULL)
+{
+    RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8);
+    RI_ASSERT(image);
+    m_color = RI_NEW(Surface, (image));
+    m_color->addReference();
+    if(maskBits)
+    {
+        VGImageFormat mf = VG_A_1;
+        if(maskBits == 4)
+            mf = VG_A_4;
+        else if(maskBits == 8)
+            mf = VG_A_8;
+        m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), image->getWidth(), image->getHeight(), 1));
+        m_mask->addReference();
+        m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, image->getWidth(), image->getHeight());
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Drawable::Drawable(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data, int maskBits) :
+    m_referenceCount(0),
+    m_color(NULL),
+    m_mask(NULL)
+{
+    RI_ASSERT(width > 0 && height > 0);
+    RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8);
+    m_color = RI_NEW(Surface, (desc, width, height, stride, data));	//throws bad_alloc
+    m_color->addReference();
+    if(maskBits)
+    {
+        VGImageFormat mf = VG_A_1;
+        if(maskBits == 4)
+            mf = VG_A_4;
+        else if(maskBits == 8)
+            mf = VG_A_8;
+        m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), width, height, 1));
+        m_mask->addReference();
+        m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Drawable::~Drawable()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    if(!m_color->removeReference())
+        RI_DELETE(m_color);
+    if(m_mask)
+        if(!m_mask->removeReference())
+            RI_DELETE(m_mask);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Drawable::resize(VGContext* context, int newWidth, int newHeight)
+{
+    Surface* oldcolor = m_color;
+    Surface* oldmask = m_mask;
+    int oldWidth = m_color->getWidth();
+    int oldHeight = m_color->getHeight();
+
+    //TODO check that image is not a proxy
+    m_color = RI_NEW(Surface, (m_color->getDescriptor(), newWidth, newHeight, m_color->getNumSamples()));
+    m_color->addReference();
+    if(m_mask)
+    {
+        m_mask = RI_NEW(Surface, (m_mask->getDescriptor(), newWidth, newHeight, m_mask->getNumSamples()));
+        m_mask->addReference();
+    }
+
+    int wmin = RI_INT_MIN(newWidth,oldWidth);
+    int hmin = RI_INT_MIN(newHeight,oldHeight);
+    m_color->clear(Color(0.0f, 0.0f, 0.0f, 0.0f, getDescriptor().internalFormat), 0, 0, m_color->getWidth(), m_color->getHeight());
+    m_color->m_image->blit(context, oldcolor->m_image, 0, 0, 0, 0, wmin, hmin);
+    if(m_mask)
+    {
+        m_mask->clear(Color(1.0f, 1.0f, 1.0f, 1.0f, getDescriptor().internalFormat), 0, 0, m_mask->getWidth(), m_mask->getHeight());
+        m_mask->m_image->blit(context, oldmask->m_image, 0, 0, 0, 0, wmin, hmin);
+    }
+
+    if(!oldcolor->removeReference())
+        RI_DELETE(oldcolor);
+    if(oldmask)
+        if(!oldmask->removeReference())
+            RI_DELETE(oldmask);
+}
+
+#ifndef RI_COMPILE_LLVM_BYTECODE
+
+#endif /* RI_COMPILE_LLVM_BYTECODE */
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+//==============================================================================================
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riImage.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1593 @@
+#ifndef __RIIMAGE_H
+#define __RIIMAGE_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Color and Image classes.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _OPENVG_H
+#include "VG/openvg.h"
+#endif
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#include "sfAlphaRcp.h"
+#include "sfGammaLUT.h"
+#include "riUtils.h"
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+class VGContext;
+class DynamicBlitter;
+
+/*-------------------------------------------------------------------*//*!
+* \brief	A class representing rectangles.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Rectangle
+{
+public:
+    Rectangle() : x(0), y(0), width(0), height(0) {}
+    Rectangle(int rx, int ry, int rw, int rh) : x(rx), y(ry), width(rw), height(rh) {}
+    void		intersect(const Rectangle& r)
+    {
+        if(width >= 0 && r.width >= 0 && height >= 0 && r.height >= 0)
+        {
+            int x1 = RI_INT_MIN(RI_INT_ADDSATURATE(x, width), RI_INT_ADDSATURATE(r.x, r.width));
+            x = RI_INT_MAX(x, r.x);
+            width = RI_INT_MAX(x1 - x, 0);
+
+            int y1 = RI_INT_MIN(RI_INT_ADDSATURATE(y, height), RI_INT_ADDSATURATE(r.y, r.height));
+            y = RI_INT_MAX(y, r.y);
+            height = RI_INT_MAX(y1 - y, 0);
+        }
+        else
+        {
+            x = 0;
+            y = 0;
+            width = 0;
+            height = 0;
+        }
+    }
+    bool isEmpty() const { return width == 0 || height == 0; }
+
+    int			x;
+    int			y;
+    int			width;
+    int			height;
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief	A class representing color for processing and converting it
+*			to and from various surface formats.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Color
+{
+public:
+    enum FormatSize
+    {
+        SIZE_1      = 0,
+        SIZE_4      = 1,
+        SIZE_8      = 2,
+        SIZE_16     = 3,
+        SIZE_24     = 4,
+        SIZE_32     = 5
+    };
+
+    enum Shape
+    {
+        SHAPE_RGBA            = 0,
+        SHAPE_RGBX            = 1,
+        SHAPE_RGB             = 2,
+        SHAPE_LA              = 3,
+        SHAPE_L               = 4,
+        SHAPE_A               = 5,
+        SHAPE_ARGB            = 6,
+        SHAPE_XRGB            = 7,
+        SHAPE_AL              = 8,
+        SHAPE_BGRA            = 9,
+        SHAPE_BGRX            = 10,
+        SHAPE_BGR             = 11,
+        SHAPE_ABGR            = 12,
+        SHAPE_XBGR            = 13
+    };
+    enum InternalFormat
+    {
+        lRGBA			= 0,
+        sRGBA			= 1,
+        lRGBA_PRE		= 2,
+        sRGBA_PRE		= 3,
+        lLA				= 4,
+        sLA				= 5,
+        lLA_PRE			= 6,
+        sLA_PRE			= 7
+    };
+    enum FormatBits
+    {
+        NONLINEAR		= (1<<0),
+        PREMULTIPLIED	= (1<<1),
+        LUMINANCE		= (1<<2)
+    };
+    struct SmallDescriptor
+    {
+        RIuint32        toUint32()
+        {
+            RIuint32 ret = 0;
+            ret = (RIuint32)size;
+            ret |= (RIuint32)shape << 3;
+            ret |= (RIuint32)internalFormat << (3 + 4);
+            return ret;
+        }
+        FormatSize      size;
+        Shape           shape;
+        InternalFormat  internalFormat;
+    };
+    class Descriptor
+    {
+    public:
+        Descriptor() {};
+        RI_INLINE Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp, Shape shape);
+        RI_INLINE bool      isNonlinear() const                                 { return (internalFormat & NONLINEAR) ? true : false; }
+        RI_INLINE void      setNonlinear(bool nonlinear);
+        RI_INLINE bool      isPremultiplied() const                             { return (internalFormat & PREMULTIPLIED) ? true : false; }
+        RI_INLINE bool      isLuminance() const                                 { return (internalFormat & LUMINANCE) ? true : false; }
+        RI_INLINE bool      isAlphaOnly() const                                 { return (alphaBits && (redBits+greenBits+blueBits+luminanceBits) == 0) ? true : false; }
+        RI_INLINE bool      isBW() const { return isLuminance() && (luminanceBits == 1); }
+        RI_INLINE bool      hasAlpha() const { return alphaBits > 0; }
+        RI_INLINE bool      operator==(const Descriptor& rhs) const;
+        RI_INLINE bool      isShiftConversionToLower(const Descriptor& rhs) const;
+        RI_INLINE bool      isShiftConversion(const Descriptor& rhs) const;
+        RI_INLINE bool      isZeroConversion(const Descriptor& rhs) const;
+        RI_INLINE bool      maybeUnsafe() const { return internalFormat & PREMULTIPLIED ? true : false; };
+        static RI_INLINE RIuint32  crossConvertToLower(RIuint32 c, const Descriptor& src, const Descriptor& dst);
+        void                toSmallDescriptor(SmallDescriptor& smallDesc) const;
+        RI_INLINE RIuint32  toIndex() const;
+        static Descriptor   getDummyDescriptor();
+        Shape               getShape() const;
+
+        int				redBits;
+        int				redShift;
+        int				greenBits;
+        int				greenShift;
+        int				blueBits;
+        int				blueShift;
+        int				alphaBits;
+        int				alphaShift;
+        int				luminanceBits;
+        int				luminanceShift;
+        Shape           shape;
+        VGImageFormat   vgFormat; // \note Storage only
+        InternalFormat	internalFormat;
+        int				bitsPerPixel;
+        // Derived info:
+        int             bytesPerPixel;
+        int             maskBits;
+        int             maskShift;
+    };
+
+    RI_INLINE Color() : r(0.0f), g(0.0f), b(0.0f), a(0.0f), m_format(sRGBA_PRE)													{}
+    RI_INLINE Color(RIfloat cl, RIfloat ca, InternalFormat cs) : r(cl), g(cl), b(cl), a(ca), m_format(cs)							{ RI_ASSERT(cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); }
+    RI_INLINE Color(RIfloat cr, RIfloat cg, RIfloat cb, RIfloat ca, InternalFormat cs) : r(cr), g(cg), b(cb), a(ca), m_format(cs)	{ RI_ASSERT(cs == lRGBA || cs == sRGBA || cs == lRGBA_PRE || cs == sRGBA_PRE || cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); }
+    RI_INLINE Color(const Color& c) : r(c.r), g(c.g), b(c.b), a(c.a), m_format(c.m_format)									{}
+    RI_INLINE Color& operator=(const Color&c)										{ r = c.r; g = c.g; b = c.b; a = c.a; m_format = c.m_format; return *this; }
+    RI_INLINE void operator*=(RIfloat f)											{ r *= f; g *= f; b *= f; a*= f; }
+    RI_INLINE void operator+=(const Color& c1)										{ RI_ASSERT(m_format == c1.getInternalFormat()); r += c1.r; g += c1.g; b += c1.b; a += c1.a; }
+    RI_INLINE void operator-=(const Color& c1)										{ RI_ASSERT(m_format == c1.getInternalFormat()); r -= c1.r; g -= c1.g; b -= c1.b; a -= c1.a; }
+
+    void						set(RIfloat cl, RIfloat ca, InternalFormat cs)							{ RI_ASSERT(cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); r = cl; g = cl; b = cl; a = ca; m_format = cs; }
+    void						set(RIfloat cr, RIfloat cg, RIfloat cb, RIfloat ca, InternalFormat cs)	{ RI_ASSERT(cs == lRGBA || cs == sRGBA || cs == lRGBA_PRE || cs == sRGBA_PRE); r = cr; g = cg; b = cb; a = ca; m_format = cs; }
+    void						unpack(unsigned int inputData, const Descriptor& inputDesc);
+    unsigned int				pack(const Descriptor& outputDesc) const;
+    RI_INLINE InternalFormat	getInternalFormat() const							{ return m_format; }
+
+    //clamps nonpremultiplied colors and alpha to [0,1] range, and premultiplied alpha to [0,1], colors to [0,a]
+    void						clamp()												{ a = RI_CLAMP(a,0.0f,1.0f); RIfloat u = (m_format & PREMULTIPLIED) ? a : (RIfloat)1.0f; r = RI_CLAMP(r,0.0f,u); g = RI_CLAMP(g,0.0f,u); b = RI_CLAMP(b,0.0f,u); }
+    void						convert(InternalFormat outputFormat);
+    void						premultiply()										{ if(!(m_format & PREMULTIPLIED)) { r *= a; g *= a; b *= a; m_format = (InternalFormat)(m_format | PREMULTIPLIED); } }
+    void						unpremultiply()										{ if(m_format & PREMULTIPLIED) { RIfloat ooa = (a != 0.0f) ? 1.0f/a : (RIfloat)0.0f; r *= ooa; g *= ooa; b *= ooa; m_format = (InternalFormat)(m_format & ~PREMULTIPLIED); } }
+    void                        luminanceToRGB()                                    { if(m_format & LUMINANCE) { RI_ASSERT(r == g && g == b); m_format = (InternalFormat)(m_format & ~LUMINANCE); } }
+
+    bool                        isNonlinear() const                                 { return (m_format & NONLINEAR) ? true : false; }
+    bool                        isPremultiplied() const                             { return (m_format & PREMULTIPLIED) ? true : false; }
+    bool                        isLuminance() const                                 { return (m_format & LUMINANCE) ? true : false; }
+
+    RI_INLINE void              assertConsistency() const;
+
+    // \note Why are these in the color class instead of descriptor?
+    static VGImageFormat        descriptorToVGImageFormat(const Descriptor& desc);
+    RI_INLINE static Descriptor formatToDescriptorConst(VGImageFormat format);
+    static Descriptor			formatToDescriptor(VGImageFormat format);
+    static bool					isValidDescriptor(const Descriptor& desc);
+
+    RIfloat		r;
+    RIfloat		g;
+    RIfloat		b;
+    RIfloat		a;
+private:
+    InternalFormat	m_format;
+};
+
+RI_INLINE Color::Descriptor::Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp, Shape shape) :
+    redBits(dredBits),
+    redShift(dredShift),
+    greenBits(dgreenBits),
+    greenShift(dgreenShift),
+    blueBits(dblueBits),
+    blueShift(dblueShift),
+    alphaBits(dalphaBits),
+    alphaShift(dalphaShift),
+    luminanceBits(dluminanceBits),
+    luminanceShift(dluminanceShift),
+    shape(shape),
+    internalFormat(dinternalFormat),
+    bitsPerPixel(dbpp)
+{
+    bytesPerPixel = bitsPerPixel / 8;
+
+    if (alphaBits)
+    {
+        maskBits = alphaBits;
+        maskShift = alphaShift;
+    }
+    else if (!this->isLuminance())
+    {
+        maskBits = redBits;
+        maskShift = redShift;
+    }
+    else
+    {
+        maskBits = luminanceBits;
+        maskShift = luminanceShift;
+    }
+    RI_ASSERT(getShape() == shape);
+}
+
+RI_INLINE void Color::Descriptor::setNonlinear(bool nonlinear)
+{
+    if (nonlinear)
+        internalFormat = (InternalFormat)(((RIuint32)internalFormat)|NONLINEAR);
+    else
+        internalFormat = (InternalFormat)(((RIuint32)internalFormat)&(~NONLINEAR));
+}
+
+/**
+ * \brief	Creates a pixel format descriptor out of VGImageFormat
+ * \todo    The formats without alpha were non-premultiplied in the reference
+ *          implementation, but wouldn't it make more sense to consider them
+ *          premultiplied? This would make sense at least when blitting to
+ *          windows, etc., where the output color should have the alpha
+ *          multiplied "in".
+ */
+RI_INLINE Color::Descriptor Color::formatToDescriptorConst(VGImageFormat format)
+{
+    switch(format)
+    {
+    case VG_sRGBX_8888:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_RGBX);
+    case VG_sRGBA_8888:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::sRGBA, 32, SHAPE_RGBA);
+    case VG_sRGBA_8888_PRE:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::sRGBA_PRE, 32, SHAPE_RGBA);
+    case VG_sRGB_565:
+        return Color::Descriptor(5, 11, 6, 5, 5, 0, 0, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGB);
+    case VG_sRGBA_5551:
+        return Color::Descriptor(5, 11, 5, 6, 5, 1, 1, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGBA);
+    case VG_sRGBA_4444:
+        return Color::Descriptor(4, 12, 4, 8, 4, 4, 4, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGBA);
+    case VG_sL_8:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, Color::sLA, 8, SHAPE_L);
+    case VG_lRGBX_8888:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_RGBX);
+    case VG_lRGBA_8888:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::lRGBA, 32, SHAPE_RGBA);
+    case VG_lRGBA_8888_PRE:
+        return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::lRGBA_PRE, 32, SHAPE_RGBA);
+    case VG_lL_8:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, Color::lLA, 8, SHAPE_L);
+    case VG_A_8:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 8, 0, 0, 0, Color::lRGBA, 8, SHAPE_A);
+    case VG_BW_1:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, Color::lLA, 1, SHAPE_L);
+    case VG_A_1:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, Color::lRGBA, 1, SHAPE_A);
+    case VG_A_4:
+        return Color::Descriptor(0, 0, 0, 0, 0, 0, 4, 0, 0, 0, Color::lRGBA, 4, SHAPE_A);
+
+  /* {A,X}RGB channel ordering */
+    case VG_sXRGB_8888:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_XRGB);
+    case VG_sARGB_8888:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::sRGBA, 32, SHAPE_ARGB);
+    case VG_sARGB_8888_PRE:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::sRGBA_PRE, 32, SHAPE_ARGB);
+    case VG_sARGB_1555:
+        return Color::Descriptor(5, 10, 5, 5, 5, 0, 1, 15, 0, 0, Color::sRGBA, 16, SHAPE_ARGB);
+    case VG_sARGB_4444:
+        return Color::Descriptor(4, 8, 4, 4, 4, 0, 4, 12, 0, 0, Color::sRGBA, 16, SHAPE_ARGB);
+    case VG_lXRGB_8888:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_XRGB);
+    case VG_lARGB_8888:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::lRGBA, 32, SHAPE_ARGB);
+    case VG_lARGB_8888_PRE:
+        return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::lRGBA_PRE, 32, SHAPE_ARGB);
+
+  /* BGR{A,X} channel ordering */
+    case VG_sBGRX_8888:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_BGRX);
+    case VG_sBGRA_8888:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::sRGBA, 32, SHAPE_BGRA);
+    case VG_sBGRA_8888_PRE:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::sRGBA_PRE, 32, SHAPE_BGRA);
+    case VG_sBGR_565:
+        return Color::Descriptor(5, 0, 6, 5, 5, 11, 0, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGR);
+    case VG_sBGRA_5551:
+        return Color::Descriptor(5, 1, 5, 6, 5, 11, 1, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGRA);
+    case VG_sBGRA_4444:
+        return Color::Descriptor(4, 4, 4, 8, 4, 12, 4, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGRA);
+    case VG_lBGRX_8888:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_BGRX);
+    case VG_lBGRA_8888:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::lRGBA, 32, SHAPE_BGRA);
+    case VG_lBGRA_8888_PRE:
+        return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::lRGBA_PRE, 32, SHAPE_BGRA);
+
+  /* {A,X}BGR channel ordering */
+    case VG_sXBGR_8888:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_XBGR);
+    case VG_sABGR_8888:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::sRGBA, 32, SHAPE_ABGR);
+    case VG_sABGR_8888_PRE:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::sRGBA_PRE, 32, SHAPE_ABGR);
+    case VG_sABGR_1555:
+        return Color::Descriptor(5, 0, 5, 5, 5, 10, 1, 15, 0, 0, Color::sRGBA, 16, SHAPE_ABGR);
+    case VG_sABGR_4444:
+        return Color::Descriptor(4, 0, 4, 4, 4, 8, 4, 12, 0, 0, Color::sRGBA, 16, SHAPE_ABGR);
+    case VG_lXBGR_8888:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_XBGR);
+    case VG_lABGR_8888:
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::lRGBA, 32, SHAPE_ABGR);
+    default:
+    //case VG_lABGR_8888_PRE:
+        RI_ASSERT(format == VG_lABGR_8888_PRE);
+        return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::lRGBA_PRE, 32, SHAPE_ABGR);
+    }
+}
+
+RI_INLINE bool 	Color::Descriptor::operator==(const Descriptor& rhs) const
+{
+    return memcmp(this, &rhs, sizeof(Descriptor)) ? false : true;
+}
+
+RI_INLINE bool Color::Descriptor::isZeroConversion(const Descriptor& rhs) const
+{
+    return (shape == rhs.shape) &&
+        (internalFormat == rhs.internalFormat) &&
+        (redBits == rhs.redBits) &&
+        (greenBits == rhs.greenBits) &&
+        (blueBits == rhs.blueBits) &&
+        (alphaBits == rhs.alphaBits) &&
+        (luminanceBits == rhs.luminanceBits);
+}
+
+RI_INLINE bool Color::Descriptor::isShiftConversion(const Descriptor& rhs) const
+{
+    // \note BW conversion is always forced to full at the moment.
+    if (isBW() != rhs.isBW()) 
+        return false;
+
+    return (isPremultiplied() == rhs.isPremultiplied())
+            && (isNonlinear() == rhs.isNonlinear())
+            && (isLuminance() == rhs.isLuminance());
+}
+
+RI_INLINE bool Color::Descriptor::isShiftConversionToLower(const Descriptor& rhs) const
+{
+    // \note BW conversion is always forced to full at the moment.
+    if (isBW() != rhs.isBW()) 
+        return false;
+    // \note Mask bits are not checked because they are derived information.
+    return (isShiftConversion(rhs)
+            && (rhs.redBits <= redBits)
+            && (rhs.greenBits <= greenBits)
+            && (rhs.blueBits <= blueBits)
+            && (rhs.alphaBits <= alphaBits)
+            && (rhs.luminanceBits <= luminanceBits));
+
+}
+
+/**
+ * \brief   In-place conversion of packed color to lower bit-depth
+ * \param   c   Input packed color
+ * \param   src Source color descriptor
+ * \param   dst Destination color descriptor
+ */
+RI_INLINE RIuint32  Color::Descriptor::crossConvertToLower(RIuint32 c, const Descriptor& src, const Descriptor& dst)
+{
+    RIuint32 r = 0;
+
+    RI_ASSERT(dst.redBits <= src.redBits);
+    RI_ASSERT(dst.greenBits <= src.greenBits);
+    RI_ASSERT(dst.blueBits <= src.blueBits);
+    RI_ASSERT(dst.alphaBits <= src.alphaBits);
+
+    if (src.isLuminance())
+    {
+        RI_ASSERT(dst.isLuminance());
+        r = ((c >> (src.luminanceShift + src.luminanceBits - dst.luminanceBits)) & ((1u<<dst.luminanceBits)-1)) << dst.luminanceShift;
+    } else
+    {
+        r = ((c >> (src.redShift + src.redBits - dst.redBits)) & ((1u<<dst.redBits)-1)) << dst.redShift;
+        r |= ((c >> (src.greenShift + src.greenBits - dst.greenBits)) & ((1u<<dst.greenBits)-1)) << dst.greenShift;
+        r |= ((c >> (src.blueShift + src.blueBits - dst.blueBits)) & ((1u<<dst.blueBits)-1)) << dst.blueShift;
+    }
+
+    if (src.hasAlpha())
+    {
+        if (dst.hasAlpha())
+            r |= ((c >> (src.alphaShift + src.alphaBits - dst.alphaBits)) & ((1u<<dst.alphaBits)-1)) << dst.alphaShift;
+        else
+        {
+            // Make sure that the alpha is applied to the color if doing only a shift conversion.
+            RI_ASSERT(src.isPremultiplied() == dst.isPremultiplied());
+        }
+    }
+
+    return r;
+}
+
+RI_INLINE RIuint32 Color::Descriptor::toIndex() const
+{
+    SmallDescriptor smallDesc;
+    toSmallDescriptor(smallDesc);
+    return smallDesc.toUint32();
+}
+
+RI_INLINE Color operator*(const Color& c, RIfloat f)			{ return Color(c.r*f, c.g*f, c.b*f, c.a*f, c.getInternalFormat()); }
+RI_INLINE Color operator*(RIfloat f, const Color& c)			{ return Color(c.r*f, c.g*f, c.b*f, c.a*f, c.getInternalFormat()); }
+RI_INLINE Color operator+(const Color& c0, const Color& c1)		{ RI_ASSERT(c0.getInternalFormat() == c1.getInternalFormat()); return Color(c0.r+c1.r, c0.g+c1.g, c0.b+c1.b, c0.a+c1.a, c0.getInternalFormat()); }
+RI_INLINE Color operator-(const Color& c0, const Color& c1)		{ RI_ASSERT(c0.getInternalFormat() == c1.getInternalFormat()); return Color(c0.r-c1.r, c0.g-c1.g, c0.b-c1.b, c0.a-c1.a, c0.getInternalFormat()); }
+RI_INLINE void  Color::assertConsistency() const
+{
+    RI_ASSERT(r >= 0.0f && r <= 1.0f);
+    RI_ASSERT(g >= 0.0f && g <= 1.0f);
+    RI_ASSERT(b >= 0.0f && b <= 1.0f);
+    RI_ASSERT(a >= 0.0f && a <= 1.0f);
+    RI_ASSERT(!isPremultiplied() || (r <= a && g <= a && b <= a));	//premultiplied colors must have color channels less than or equal to alpha
+    RI_ASSERT((isLuminance() && r == g && r == b) || !isLuminance());	//if luminance, r=g=b
+}
+
+class IntegerColor
+{
+public:
+
+    IntegerColor() {r = g = b = a = 0;}
+    IntegerColor(const Color& color);
+
+    RI_INLINE           IntegerColor(RIuint32 packedColor, const Color::Descriptor& desc) { fromPackedColor(packedColor, desc); }
+    RI_INLINE           IntegerColor(RIuint32 cr, RIuint32 cg, RIuint32 cb, RIuint32 ca) { r = cr; g = cg; b = cb; a = ca; }
+    RI_INLINE void      asFixedPoint(const Color& color);
+    RI_INLINE void      fromPackedColor(RIuint32 packedColor, const Color::Descriptor& desc);
+    RI_INLINE void      expandColor(const Color::Descriptor& desc);
+    RI_INLINE void      truncateColor(const Color::Descriptor& desc);
+    RI_INLINE void      clampToAlpha();
+    RI_INLINE RIuint32  getPackedColor(const Color::Descriptor& desc) const;
+    RI_INLINE RIuint32  getPackedMaskColor(const Color::Descriptor& desc) const;
+    RI_INLINE void      premultiply(bool luminance = false);
+    RI_INLINE void      unpremultiply(bool luminance = false);
+    //RI_INLINE void      linearToGamma(bool luminance, bool premultipliedIn, bool premultipliedOut);
+    RI_INLINE void      linearToGamma(bool luminance = false);
+    RI_INLINE void      gammaToLinear(bool luminance = false);
+    RI_INLINE void      fromPackedMask(RIuint32 packedColor, const Color::Descriptor& desc);
+    RI_INLINE void      expandMask(const Color::Descriptor& desc);
+    RI_INLINE void      truncateMask(const Color::Descriptor& desc);
+    RI_INLINE void      fullLuminanceToRGB(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut);
+    RI_INLINE void      fullRGBToLuminance(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut);
+    RI_INLINE void      luminanceToRGB();
+    RI_INLINE void      rgbToLuminance();
+    RI_INLINE void      convertToFrom(const Color::Descriptor& dst, const Color::Descriptor& src, bool srcIsMask);
+
+    RI_INLINE static IntegerColor linearBlendNS(const IntegerColor& c0, const IntegerColor& c1, int k);
+
+    RIuint32 r;
+    RIuint32 g;
+    RIuint32 b;
+    RIuint32 a;
+
+};
+
+/**
+ * \brief   Blend two colors linearly. The output will not be scaled into original range.
+ * \param   k   Blend coefficient. Must be [0..255] for correct results.
+ * \todo    Parameterize against bits in k? To perform well, that setup must be compiled rt.
+ */
+RI_INLINE IntegerColor IntegerColor::linearBlendNS(const IntegerColor& c0, const IntegerColor& c1, int k)
+{
+    RI_ASSERT(k >= 0 && k <= 255);
+    IntegerColor ret;
+    RIuint32 ik = 255 - k;
+
+    ret.r = ik * c0.r + k * c1.r;
+    ret.g = ik * c0.g + k * c1.g;
+    ret.b = ik * c0.b + k * c1.b;
+    ret.a = ik * c0.a + k * c1.a;
+
+    return ret;
+}
+
+/**
+ *	\note 	Assumes that each individual component is in proper range (usually indicated by the
+ *			corresponding shift).
+ */
+RI_INLINE RIuint32 packRGBAInteger(RIuint32 cr, int rs, RIuint32 cg, int gs, RIuint32 cb, int bs, RIuint32 ca, int as)
+{
+    return (cr << rs) | (cg << gs) | (cb << bs) | (ca << as);
+}
+
+/**
+ * \brief   Packs a color into RIuint32.
+ * \note    The color must have been truncated to contain correct amount of bits per channel
+ * \note    This function is efficient only if runtime compilation is used.
+ */
+RI_INLINE RIuint32 IntegerColor::getPackedColor(const Color::Descriptor& desc) const
+{
+    RIuint32 res = 0;
+    if (desc.luminanceBits)
+    {
+        RI_ASSERT(desc.redBits == 0 && desc.greenBits == 0 && desc.blueBits == 0);
+        RI_ASSERT(r < (1u<<desc.luminanceBits));
+        res = r << desc.luminanceShift;
+    }
+    else if (desc.redBits)
+    {
+        RI_ASSERT(r < (1u<<desc.redBits));
+        res = r << desc.redShift;
+        if (desc.greenBits)
+        {
+            RI_ASSERT(desc.blueBits);
+            RI_ASSERT(g < (1u<<desc.greenBits));
+            RI_ASSERT(b < (1u<<desc.blueBits));
+            res |= g << desc.greenShift;
+            res |= b << desc.blueShift;
+        }
+    }
+
+    if (desc.alphaBits)
+    {
+        RI_ASSERT(a < (1u<<desc.alphaBits));
+        res |= a << desc.alphaShift;
+    }
+
+    return res;
+}
+
+RI_INLINE RIuint32 IntegerColor::getPackedMaskColor(const Color::Descriptor& desc) const
+{
+    if (desc.alphaBits)
+        return packRGBAInteger(0, desc.redShift, 0, desc.greenShift, 0, desc.blueShift, a, desc.alphaShift);
+    else if(desc.redBits)
+        return packRGBAInteger(a, desc.redShift, 0, desc.greenShift, 0, desc.blueShift, 0, desc.alphaShift);
+    else
+    {
+        RI_ASSERT(desc.luminanceBits);
+        return packRGBAInteger(a, desc.luminanceBits, 0, desc.greenShift, 0, desc.blueShift, 0, desc.alphaShift);
+    }
+
+}
+
+RI_INLINE void IntegerColor::premultiply(bool luminance)
+{
+    // \todo Check the round!!!
+    RIuint32 fxa = a + (a>>7);
+    r = (r * fxa); r = (r + (1<<7))>>8;
+
+    if (!luminance)
+    {
+        g = (g * fxa); g = (g + (1<<7))>>8;
+        b = (b * fxa); b = (b + (1<<7))>>8;
+    }
+}
+
+RI_INLINE void IntegerColor::unpremultiply(bool luminance)
+{
+    RI_ASSERT(a <= 255);
+
+    RIuint32 rcp = sc_alphaRcp[a];
+    r = (r * rcp) >> 8;
+
+    if (!luminance)
+    {
+        g = (g * rcp) >> 8;
+        b = (b * rcp) >> 8;
+    }
+}
+
+RI_INLINE void IntegerColor::linearToGamma(bool luminance)
+{
+    RI_ASSERT(r <= 255 && g <= 255 && b <= 255 && a <= 255);
+
+    r = sc_lRGB_to_sRGB[r];
+
+    if (!luminance)
+    {
+        g = sc_lRGB_to_sRGB[g];
+        b = sc_lRGB_to_sRGB[b];
+    }
+
+    // \note Alpha is _not_ converted and it must be considered linear always
+}
+
+RI_INLINE void IntegerColor::gammaToLinear(bool luminance)
+{
+    RI_ASSERT(r <= 255 && g <= 255 && b <= 255 && a <= 255);
+
+    r = sc_sRGB_to_lRGB[r];
+    if (!luminance)
+    {
+        g = sc_sRGB_to_lRGB[g];
+        b = sc_sRGB_to_lRGB[b];
+    }
+
+    // \note Alpha is _not_ converted and it must be considered linear always
+}
+
+RI_INLINE void IntegerColor::asFixedPoint(const Color& color)
+{
+    r = (RIuint32)(color.r * 256.0f + 0.5f);
+    g = (RIuint32)(color.g * 256.0f + 0.5f);
+    b = (RIuint32)(color.b * 256.0f + 0.5f);
+    a = (RIuint32)(color.a * 256.0f + 0.5f);
+}
+
+RI_INLINE void IntegerColor::fromPackedColor(RIuint32 packedColor, const Color::Descriptor& desc)
+{
+    /* \note Expand MUST be done separately! */
+
+    if (desc.luminanceBits)
+    {
+        r = (packedColor >> desc.luminanceShift) & ((1u << desc.luminanceBits)-1);
+        g = b = r;
+    }
+    else
+    {
+        r = (packedColor >> desc.redShift) & ((1u << desc.redBits)-1);
+        g = (packedColor >> desc.greenShift) & ((1u << desc.greenBits)-1);
+        b = (packedColor >> desc.blueShift) & ((1u << desc.blueBits)-1);
+    }
+
+    if (desc.alphaBits)
+        a = (packedColor >> desc.alphaShift) & ((1u << desc.alphaBits)-1);
+    else
+        a = 255;
+}
+
+/**
+ * \brief   Expand color to larger (or same) bit depth as in the OpenVG specification.
+ * \todo    1 and 2 bpp!
+ */
+RI_INLINE RIuint32 expandComponent(RIuint32 c, RIuint32 srcBits)
+{
+    const RIuint32 destBits = 8;
+    RI_ASSERT(destBits >= srcBits);
+
+    if (!srcBits) return 0;
+
+    if (srcBits == destBits) return c;
+
+    switch (srcBits)
+    {
+    case 6:
+        return (c << 2) | (c >> 4);
+    case 5:
+        return (c << 3) | (c >> 2);
+    case 4:
+        return (c << 4) | c;
+    case 2:
+        return c | (c << 2) | (c << 4) | (c << 6);
+    default:
+        RI_ASSERT(srcBits == 1);
+        if (c) return 0xff;
+        return 0;
+    }
+}
+
+/**
+ * \brief   Expands integer color representation to internal format (8-bits per component atm.).
+ * \todo    Do nothing when bits == 8.
+ */
+RI_INLINE void IntegerColor::expandColor(const Color::Descriptor& desc)
+{
+    if (desc.luminanceBits)
+    {
+        r = expandComponent(r, desc.luminanceBits);
+        g = b = r;
+        a = 255;
+    } else
+    {
+        if (desc.redBits < 8 || desc.luminanceBits < 8)
+            r = expandComponent(r, desc.redBits);
+        if (desc.greenBits < 8)
+            g = expandComponent(g, desc.greenBits);
+        if (desc.blueBits < 8)
+            b = expandComponent(b, desc.blueBits);
+    }
+
+    if (desc.alphaBits && desc.alphaBits < 8)
+        a = expandComponent(a, desc.alphaBits);
+
+    if (desc.isAlphaOnly())
+    {
+        if (!desc.isPremultiplied())
+            r = g = b = 255;
+        else
+            r = g = b = a;
+    }
+}
+
+/**
+ * \brief   Convert IntegerColor components to destination bitdepth (from internal) by
+ *          shifting. Rounding does not take place.
+ */
+RI_INLINE void IntegerColor::truncateColor(const Color::Descriptor& desc)
+{
+    if (desc.luminanceBits)
+    {
+        RI_ASSERT(desc.redBits == 0 && desc.greenBits == 0 && desc.blueBits == 0);
+        if (desc.luminanceBits == 1)
+        {
+            // Round the 1-bit case a bit better?
+            r = (r + 128)>>8;
+        } else if (desc.luminanceBits < 8)
+            r >>= (8 - desc.luminanceBits);
+    }
+    else
+    {
+        if (desc.redBits < 8)
+            r >>= (8 - desc.redBits);
+        if (desc.greenBits < 8)
+            g >>= (8 - desc.greenBits);
+        if (desc.blueBits < 8)
+            b >>= (8 - desc.blueBits);
+    }
+
+    if (desc.alphaBits < 8)
+    {
+        if (desc.alphaBits == 1)
+            a = (a+128)>>8;
+        else
+            a >>= (8 - desc.alphaBits);
+    }
+}
+
+RI_INLINE void IntegerColor::truncateMask(const Color::Descriptor& desc)
+{
+    if (desc.redBits < 8 || desc.luminanceBits < 8)
+        r >>= (8 - desc.maskBits);
+    if (desc.greenBits < 8)
+        g >>= (8 - desc.maskBits);
+    if (desc.blueBits < 8)
+        b >>= (8 - desc.maskBits);
+    if (desc.alphaBits < 8)
+        a >>= (8 - desc.maskBits);
+}
+
+RI_INLINE void IntegerColor::clampToAlpha()
+{
+    if (r > a) r = a;
+    if (g > a) g = a;
+    if (b > a) b = a;
+}
+
+RI_INLINE void IntegerColor::fromPackedMask(RIuint32 packedMask, const Color::Descriptor& desc)
+{
+    RI_ASSERT(desc.maskBits);
+    a = (packedMask >> desc.maskShift) & ((1u << desc.maskBits)-1);
+}
+
+RI_INLINE void IntegerColor::expandMask(const Color::Descriptor& desc)
+{
+    a = expandComponent(a, desc.maskBits);
+    r = g = b = a;
+}
+
+#if 0
+RI_INLINE void IntegerColor::truncateMask(const Color::Descriptor& desc)
+{
+    a >>= (8 - desc.maskBits);
+}
+#endif
+
+RI_INLINE void IntegerColor::fullLuminanceToRGB(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut)
+{
+    if (premultipliedIn)
+        unpremultiply();
+
+    luminanceToRGB();
+
+    if (gammaIn != gammaOut)
+    {
+        if (gammaIn)
+            gammaToLinear();
+        else
+            linearToGamma();
+    }
+
+    if (premultipliedOut)
+        premultiply();
+
+}
+
+RI_INLINE void IntegerColor::fullRGBToLuminance(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut)
+{
+    if (premultipliedIn)
+        unpremultiply();
+
+    if (gammaIn)
+        gammaToLinear();
+
+    rgbToLuminance();
+
+    if (gammaOut)
+        linearToGamma();
+
+    if (premultipliedOut)
+        premultiply();
+
+}
+
+
+// \todo This should not be needed (only r-channel is used anyway)
+RI_INLINE void IntegerColor::luminanceToRGB()
+{
+    g = b = r;
+}
+
+// \todo Only write to R!
+RI_INLINE void IntegerColor::rgbToLuminance()
+{
+    enum { Rx = 871, Gx = 2929, Bx = 296, Bits = 12 };
+    //enum { Rx = 54, Gx = 183, Bx = 18, Bits = 8 };
+    RIuint32 l = Rx * r + Gx * g + Bx * b;
+    r = g = b = l >> Bits;
+}
+
+#if 0
+RI_INLINE void IntegerColor::convertFromInternal(const Color::Descriptor& dst)
+{
+}
+#endif
+
+/**
+ * \brief   Convert color from one format to another using integer operations.
+ * \note    Currently expands the color to intermediate format first (8 bits
+ *          per component.
+ */
+RI_INLINE void IntegerColor::convertToFrom(const Color::Descriptor& dst, const Color::Descriptor& src, bool srcIsMask)
+{
+    if (src.isZeroConversion(dst))
+        return;
+
+    if (src.isShiftConversionToLower(dst))
+    {
+        if (dst.luminanceBits)
+        {
+            if (dst.luminanceBits == 1)
+            {
+                RI_ASSERT(src.luminanceBits == 8);
+                r = (r + 128)>>8;
+            }
+            else
+                r = r >> (src.luminanceBits - dst.luminanceBits);
+        } else
+        {
+            r = r >> (src.redBits - dst.redBits);
+            g = g >> (src.greenBits - dst.greenBits);
+            b = b >> (src.blueBits - dst.blueBits);
+        }
+        if (dst.alphaBits)
+        {
+                //a = (a+128)>>8;
+            if (dst.alphaBits == 1)
+                a = (a+(1<<(src.alphaBits-1)))>>src.alphaBits;
+            else
+                a = a >> (src.alphaBits - dst.alphaBits);
+        }
+
+        return;
+    }
+
+    if (!srcIsMask)
+        expandColor(src);
+    else
+        expandMask(src);
+
+
+    if (dst.isLuminance() != src.isLuminance())
+    {
+        if (src.isLuminance())
+            fullLuminanceToRGB(src.isPremultiplied(), src.isNonlinear(), dst.isPremultiplied(), dst.isNonlinear());
+        else
+            fullRGBToLuminance(src.isPremultiplied(), src.isNonlinear(), dst.isPremultiplied(), dst.isNonlinear());
+    }
+    else if (dst.isNonlinear() != src.isNonlinear())
+    {
+        // No luminance/rgb change.
+        // Change of gamma requires unpremultiplication:
+        if (src.isPremultiplied() && !(src.isAlphaOnly()))
+            unpremultiply();
+
+        if (src.isNonlinear())
+            gammaToLinear(src.isLuminance());
+        else
+            linearToGamma(src.isLuminance());
+
+        if (dst.isPremultiplied() && !(dst.isAlphaOnly()))
+            premultiply();
+    }
+    else
+    if ((dst.isPremultiplied() != src.isPremultiplied()) && !(dst.isAlphaOnly() || dst.isAlphaOnly()))
+    {
+        // \todo Make sure non-alpha formats are properly handled.
+        if (src.isPremultiplied())
+            unpremultiply(dst.isLuminance());
+        else
+            premultiply(dst.isLuminance());
+    }
+
+    truncateColor(dst);
+}
+
+//==============================================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Storage and operations for VGImage.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Surface;
+class Image
+{
+public:
+    Image(const Color::Descriptor& desc, int width, int height, VGbitfield allowedQuality);	//throws bad_alloc
+    //use data from a memory buffer. NOTE: data is not copied, so it is user's responsibility to make sure the data remains valid while the Image is in use.
+    Image(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data);	//throws bad_alloc
+    //child image constructor
+    Image(Image* parent, int x, int y, int width, int height);	//throws bad_alloc
+    ~Image();
+
+    const Color::Descriptor&	getDescriptor() const		{ return m_desc; }
+    int					getWidth() const					{ return m_width; }
+    int					getHeight() const					{ return m_height; }
+    int					getStride() const					{ return m_stride; }
+    Image*				getParent() const					{ return m_parent; }
+    VGbitfield			getAllowedQuality() const			{ return m_allowedQuality; }
+    void				addInUse()							{ m_inUse++; }
+    void				removeInUse()						{ RI_ASSERT(m_inUse > 0); m_inUse--; }
+    int					isInUse() const						{ return m_inUse; }
+    RIuint8*			getData() const						{ return m_data; }
+    void				addReference()						{ m_referenceCount++; }
+    int					removeReference()					{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+    bool				overlaps(const Image* src) const;
+    void                setUnsafe(bool unsafe) { if (unsafe && m_desc.maybeUnsafe()) m_unsafeData = unsafe; else m_unsafeData = false; }
+    bool                isUnsafe() const { return m_unsafeData; }
+
+    void				clear(const Color& clearColor, int x, int y, int w, int h);
+    void				blit(VGContext* context, const Image* src, int sx, int sy, int dx, int dy, int w, int h, Array<Rectangle>* scissors = NULL, bool dither = false);	//throws bad_alloc
+
+    RI_INLINE static const void* incrementPointer(const void* ptr, int bpp, RIint32 x);
+    RI_INLINE static void* calculateAddress(const void* basePtr, int bpp, int x, int y, int stride);
+
+    static RI_INLINE RIuint32   readPackedPixelFromAddress(const void *ptr, int bpp, int x);
+    static RI_INLINE void       writePackedPixelToAddress(void* ptr, int bpp, int x, RIuint32 packedColor);
+
+    RI_INLINE RIuint32 			readPackedPixel(int x, int y) const;
+    Color				readPixel(int x, int y) const;
+    RI_INLINE void      writePackedPixelToAddress(void* ptr, int x, RIuint32 packedColor);
+    void				writePackedPixel(int x, int y, RIuint32 packedColor);
+    void				writePixel(int x, int y, const Color& c);
+
+    void                fillPacked(RIuint32 packedColor);
+
+    static RI_INLINE void   fillPackedPixels(void* data, int bpp, int x, int y, int stride, int nPixels, RIuint32 packedColor);
+    RI_INLINE void		    fillPackedPixels(int x, int y, int nPixels, RIuint32 packedColor);
+    RI_INLINE void          fillPackedRectangle(int x0, int y0, int width, int height, RIuint32 packedColor);
+
+    void				writeFilteredPixel(int x, int y, const Color& c, VGbitfield channelMask);
+
+    RIfloat				readMaskPixel(int x, int y) const;		//can read any image format
+    void				writeMaskPixel(int x, int y, RIfloat m);	//can write only to VG_A_x
+
+    Color				resample(RIfloat x, RIfloat y, const Matrix3x3& surfaceToImage, VGImageQuality quality, VGTilingMode tilingMode, const Color& tileFillColor);	//throws bad_alloc
+    void				makeMipMaps();	//throws bad_alloc
+
+    void				colorMatrix(const Image& src, const RIfloat* matrix, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				convolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernel, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				separableConvolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernelX, const RIint16* kernelY, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				gaussianBlur(const Image& src, RIfloat stdDeviationX, RIfloat stdDeviationY, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				lookup(const Image& src, const RIuint8 * redLUT, const RIuint8 * greenLUT, const RIuint8 * blueLUT, const RIuint8 * alphaLUT, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+    void				lookupSingle(const Image& src, const RIuint32 * lookupTable, VGImageChannel sourceChannel, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask);
+
+    RI_INLINE static int descriptorToStride(const Color::Descriptor& desc, int width) { return (width*desc.bitsPerPixel+7)/8; };
+
+    void getStorageOffset(int& x, int& y) const { x = m_storageOffsetX; y = m_storageOffsetY; }
+
+private:
+    Image(const Image&);					//!< Not allowed.
+    void operator=(const Image&);			//!< Not allowed.
+
+#if defined(RI_DEBUG)
+    bool                ptrInImage(const void* ptr) const;
+#endif
+    Color				readTexel(int u, int v, int level, VGTilingMode tilingMode, const Color& tileFillColor) const;
+
+    Color::Descriptor	m_desc;
+    int					m_width;
+    int					m_height;
+    VGbitfield			m_allowedQuality;
+    int					m_inUse;
+    int					m_stride;
+    RIuint8*			m_data;
+    int					m_referenceCount;
+    bool				m_ownsData;
+    Image*				m_parent;
+    int					m_storageOffsetX;
+    int					m_storageOffsetY;
+    bool                m_unsafeData; // Data may contain incorrect pixel data
+
+#ifndef RI_COMPILE_LLVM_BYTECODE
+
+#endif /* RI_COMPILE_LLVM_BYTECODE */
+};
+
+#if defined(RI_DEBUG)
+RI_INLINE bool Image::ptrInImage(const void* ptr) const
+{
+    RIuint8* p = (RIuint8*)ptr;
+
+    if (p < m_data) return false;
+    if (p >= (m_data + m_height * m_stride)) return false;
+    return true;
+}
+#endif
+
+RI_INLINE const void* Image::incrementPointer(const void* ptr, int bpp, int x)
+{
+    if (bpp >= 8)
+        return (((RIuint8*)ptr) + (bpp >> 3));
+    // Increment the pointer only when the byte is actually about to change.
+    int mask;
+    if (bpp == 4)
+        mask = 1;
+    else if (bpp == 2)
+        mask = 3;
+    else
+        mask = 7;
+    if ((x & mask) == mask)
+        return ((RIuint8*)ptr + 1);
+    return ptr;
+}
+
+RI_INLINE void* Image::calculateAddress(const void* basePtr, int bpp, int x, int y, int stride)
+{
+    if (bpp >= 8)
+    {
+        return (void*)((RIuint8*)basePtr + y * stride + x * (bpp >> 3));
+    } else
+    {
+        // 4, 2, or 1 bits per pixel
+        RI_ASSERT(bpp == 4 || bpp == 2 || bpp == 1);
+        return (void*)((RIuint8*)basePtr + y * stride + ((x * bpp) >> 3));
+    }
+}
+
+RI_INLINE RIuint32 Image::readPackedPixel(int x, int y) const
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(x >= 0 && x < m_width);
+    RI_ASSERT(y >= 0 && y < m_height);
+    RI_ASSERT(m_referenceCount > 0);
+
+    RIuint32 p = 0;
+
+    void* ptr = Image::calculateAddress(m_data, m_desc.bitsPerPixel, x+m_storageOffsetX, y+m_storageOffsetY, m_stride);
+    p = readPackedPixelFromAddress(ptr, m_desc.bitsPerPixel, x+m_storageOffsetX);
+
+    return p;
+}
+
+
+RI_INLINE void Image::writePackedPixelToAddress(void* ptr, int bpp, int x, RIuint32 packedColor)
+{
+    // \note packedColor must contain the whole data (including < 8 bpp data)?
+    switch(bpp)
+    {
+    case 32:
+    {
+        RIuint32* s = ((RIuint32*)ptr);
+        *s = (RIuint32)packedColor;
+        break;
+    }
+
+    case 16:
+    {
+        RIuint16* s = ((RIuint16*)ptr);
+        *s = (RIuint16)packedColor;
+        break;
+    }
+
+    case 8:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        *s = (RIuint8)packedColor;
+        break;
+    }
+    case 4:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+        break;
+    }
+
+    case 2:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1))));
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(bpp == 1);
+        RIuint8* s = ((RIuint8*)ptr);
+        *s = (RIuint8)((packedColor << (x&7)) | ((unsigned int)*s & ~(0x1 << (x&7))));
+        break;
+    }
+    }
+    // m_mipmapsValid = false; // \note Will never do this, must be handled outside this class somehow!
+}
+
+/**
+ * \brief   Write packed pixel into address.
+ * \param   x   Which x-coordinate (starting from the start of the scanline
+ *              pointed to) is addressed? This is only required for formats
+ *              that have less than 8 bpp.
+ */
+void Image::writePackedPixelToAddress(void* address, int x, RIuint32 packedColor)
+{
+    writePackedPixelToAddress(address, m_desc.bitsPerPixel, x, packedColor);
+}
+
+/**
+ * \brief   Read a packed pixel from a given address. Notice the use of param x!
+ * \param   x   Check which part of byte to return if bpp < 8
+ */
+RI_INLINE RIuint32 Image::readPackedPixelFromAddress(const void *ptr, int bpp, int x)
+{
+    switch(bpp)
+    {
+    case 32:
+    {
+        RIuint32* s = (RIuint32*)ptr;
+        return *s;
+    }
+
+    case 16:
+    {
+        RIuint16* s = (RIuint16*)ptr;
+        return (RIuint32)*s;
+    }
+
+    case 8:
+    {
+        RIuint8* s = (RIuint8*)ptr;
+        return (RIuint32)*s;
+    }
+    case 4:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        return (RIuint32)(*s >> ((x&1)<<2)) & 0xf;
+    }
+
+    case 2:
+    {
+        RIuint8* s = ((RIuint8*)ptr);
+        return (RIuint32)(*s >> ((x&3)<<1)) & 0x3;
+    }
+
+    default:
+    {
+        RI_ASSERT(bpp == 1);
+        RIuint8* s = ((RIuint8*)ptr);
+        return (RIuint32)(*s >> (x&7)) & 0x1;
+    }
+    }
+}
+
+RI_INLINE void Image::writePackedPixel(int x, int y, RIuint32 packedColor)
+{
+    RI_ASSERT(m_data);
+    RI_ASSERT(x >= 0 && x < m_width);
+    RI_ASSERT(y >= 0 && y < m_height);
+    RI_ASSERT(m_referenceCount > 0);
+
+    x += m_storageOffsetX;
+    y += m_storageOffsetY;
+
+    RIuint8* scanline = m_data + y * m_stride;
+    switch(m_desc.bitsPerPixel)
+    {
+    case 32:
+    {
+        RIuint32* s = ((RIuint32*)scanline) + x;
+        *s = (RIuint32)packedColor;
+        break;
+    }
+
+    case 16:
+    {
+        RIuint16* s = ((RIuint16*)scanline) + x;
+        *s = (RIuint16)packedColor;
+        break;
+    }
+
+    case 8:
+    {
+        RIuint8* s = ((RIuint8*)scanline) + x;
+        *s = (RIuint8)packedColor;
+        break;
+    }
+    case 4:
+    {
+        RIuint8* s = ((RIuint8*)scanline) + (x>>1);
+        *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+        break;
+    }
+
+    case 2:
+    {
+        RIuint8* s = ((RIuint8*)scanline) + (x>>2);
+        *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1))));
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(m_desc.bitsPerPixel == 1);
+        RIuint8* s = ((RIuint8*)scanline) + (x>>3);
+        *s = (RIuint8)((packedColor << (x&7)) | ((unsigned int)*s & ~(0x1 << (x&7))));
+        break;
+    }
+    }
+    //m_mipmapsValid = false;
+}
+
+
+/**
+ * \brief   Unsafe static method for setting image pixels
+ */
+RI_INLINE void Image::fillPackedPixels(void* data, int bpp, int x, int y, int stride, int nPixels, RIuint32 packedColor)
+{
+    RI_ASSERT(nPixels > 0);
+    RI_ASSERT(data);
+
+    RIuint8* scanline = (RIuint8*)data + y * stride;
+
+    switch(bpp)
+    {
+    case 32:
+    {
+        RIuint32* s = ((RIuint32*)scanline) + x;
+
+        for (int i = 0; i < nPixels; i++)
+            s[i] = packedColor;
+
+        break;
+    }
+
+    case 16:
+    {
+        RIuint16* s = ((RIuint16*)scanline) + x;
+
+        for (int i = 0; i < nPixels; i++)
+            s[i] = (RIuint16)packedColor;
+
+        break;
+    }
+
+    case 8:
+    {
+        RIuint8* s = ((RIuint8*)scanline) + x;
+
+        for (int i = 0; i < nPixels; i++)
+            s[i] = (RIuint8)packedColor;
+
+        break;
+    }
+    case 4:
+    {
+        //RI_ASSERT((packedColor & 0xf) == 0);
+        //packedColor &= 0xf;
+        RIuint8* s = ((RIuint8*)scanline) + (x>>1);
+        if (x & 1)
+        {
+            *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+            s++;
+            x++;
+            nPixels--;
+        }
+        RI_ASSERT(!(x&1));
+
+        int c = nPixels / 2;
+        RIuint8 bytePacked = packedColor | (packedColor << 4);
+        while (c)
+        {
+            *s++ = bytePacked;
+            c--;
+            x+=2;
+        }
+        nPixels &= 1;
+
+        if (nPixels)
+        {
+            *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+            s++;
+            x++;
+            nPixels--;
+        }
+        RI_ASSERT(nPixels == 0);
+        break;
+    }
+
+    case 2:
+    {
+        // This case should not be needed!
+        RI_ASSERT(false);
+        RIuint8* s = ((RIuint8*)scanline) + (x>>2);
+        *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1))));
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(bpp == 1);
+        RIuint8* s = ((RIuint8*)scanline) + (x>>3);
+        // \todo Get this as input instead?
+        RI_ASSERT(packedColor == 1 || packedColor == 0);
+        RIuint8 fullyPacked = (RIuint8)(-(RIint8)packedColor);
+
+        if (x & 7)
+        {
+            // Handle the first byte:
+            RIuint8 o = *s;
+            int a = x&7;
+            RI_ASSERT(a>=1);
+            int b = RI_INT_MIN(a + nPixels, 8);
+            RI_ASSERT(b > a);
+            RIuint8 emask = (1u << b)-1;
+            RIuint8 mask = (0xffu<<a) & emask;
+            RI_ASSERT(mask>0);
+            RI_ASSERT(mask<=254);
+            *s++ = (o&(~mask))|(fullyPacked & mask);
+            nPixels -= 8-(x&7);
+            x += 8-(x&7);
+        }
+
+        if (nPixels < 0)
+            return;
+
+        RI_ASSERT(!(x&1));
+
+        int c = nPixels/8;
+        while (c)
+        {
+            *s++ = fullyPacked;
+            c--;
+            x+=8;
+        }
+        nPixels -= ((nPixels/8) * 8);
+
+
+        if (nPixels)
+        {
+            RI_ASSERT((x&7) == 0);
+
+            RIuint8 o = *s;
+            int b = nPixels;
+            RI_ASSERT(b<=7);
+            RIuint8 mask = (1u<<b)-1;
+            RI_ASSERT(mask <= 127);
+            *s++ = (o&(~mask))|(fullyPacked & mask);
+        }
+        break;
+    }
+    }
+    //m_mipmapsValid = false;
+}
+RI_INLINE void Image::fillPackedPixels(int x, int y, int nPixels, RIuint32 packedColor)
+{
+    fillPackedPixels((void*)m_data, m_desc.bitsPerPixel, x + m_storageOffsetX, y + m_storageOffsetY, m_stride, nPixels, packedColor);
+}
+
+RI_INLINE void Image::fillPackedRectangle(int x0, int y0, int width, int height, RIuint32 packedColor)
+{
+    int y = y0;
+    while (height)
+    {
+        fillPackedPixels(x0, y, width, packedColor);
+        y++;
+        height--;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Surface class abstracting multisampled rendering surface.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Surface
+{
+public:
+    Surface(const Color::Descriptor& desc, int width, int height, int numSamples);	//throws bad_alloc
+    Surface(Image* image);	//throws bad_alloc
+    Surface(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data);	//throws bad_alloc
+    ~Surface();
+
+    RI_INLINE const Image* getImage() const {return m_image;}
+    RI_INLINE const Color::Descriptor&	getDescriptor() const		{ return m_image->getDescriptor(); }
+    RI_INLINE int		getWidth() const							{ return m_width; }
+    RI_INLINE int		getHeight() const							{ return m_height; }
+    RI_INLINE int		getNumSamples() const						{ return m_numSamples; }
+    RI_INLINE void		addReference()								{ m_referenceCount++; }
+    RI_INLINE int		removeReference()							{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+    RI_INLINE int		isInUse() const								{ return m_image->isInUse(); }
+    RI_INLINE bool		isInUse(Image* image) const					{ return image == m_image ? true : false; }
+
+    void				clear(const Color& clearColor, int x, int y, int w, int h, const Array<Rectangle>* scissors = NULL);
+#if 0
+    // Currently does not support msaa surfaces
+    void				blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h);	//throws bad_alloc
+    void				blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h, const Array<Rectangle>& scissors);	//throws bad_alloc
+    void				blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h);	//throws bad_alloc
+    void				blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h, const Array<Rectangle>& scissors);	//throws bad_alloc
+#endif
+    void				mask(DynamicBlitter& blitter, const Image* src, VGMaskOperation operation, int x, int y, int w, int h);
+
+    RI_INLINE void      writePackedPixelToAddress(void* address, int x, RIuint32 p)        { m_image->writePackedPixelToAddress(address, x, p); }
+   RI_INLINE RIuint32 	readPackedSample(int x, int y, int sample) const			 { return m_image->readPackedPixel(x*m_numSamples+sample, y); }
+    RI_INLINE Color		readSample(int x, int y, int sample) const                   { return m_image->readPixel(x*m_numSamples+sample, y); }
+    RI_INLINE void		writePackedSample(int x, int y, int sample, RIuint32 p)		 { m_image->writePackedPixel(x*m_numSamples+sample, y, p); }
+    RI_INLINE void		writeSample(int x, int y, int sample, const Color& c)        { m_image->writePixel(x*m_numSamples+sample, y, c); }
+    RI_INLINE void		fillPackedSamples(int x, int y, int nPixels, RIuint32 p);
+
+    RIfloat				readMaskCoverage(int x, int y) const;
+    void				writeMaskCoverage(int x, int y, RIfloat m);
+    unsigned int		readMaskMSAA(int x, int y) const;
+    void				writeMaskMSAA(int x, int y, unsigned int m);
+
+    RIuint32 			FSAAResolvePacked(int x, int y) const;
+    Color				FSAAResolve(int x, int y) const;	//for fb=>img: vgGetPixels, vgReadPixels
+
+private:
+    Surface(const Surface&);			//!< Not allowed.
+    void operator=(const Surface&);			//!< Not allowed.
+
+    struct ScissorEdge
+    {
+        ScissorEdge() : x(0), miny(0), maxy(0), direction(0) {}
+        bool operator<(const ScissorEdge& e) const	{ return x < e.x; }
+        int			x;
+        int			miny;
+        int			maxy;
+        int			direction;		//1 start, -1 end
+    };
+
+    int				m_width;
+    int				m_height;
+    int				m_numSamples;
+    int				m_referenceCount;
+
+public:
+    // \todo TERO: Broke the design of this by making it public, make proper
+    // friend/etc. C++ accessor for optimized pixel-pipelines. Combine with the
+    // removal of (remnants of) the FSAA support.
+    Image*			m_image;
+};
+
+RI_INLINE void Surface::fillPackedSamples(int x, int y, int nPixels, RIuint32 p)
+{
+    m_image->fillPackedPixels(x, y, nPixels, p);
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Drawable class for encapsulating color and mask buffers.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Drawable
+{
+public:
+    Drawable(const Color::Descriptor& desc, int width, int height, int numSamples, int maskBits);	//throws bad_alloc
+    Drawable(Image* image, int maskBits);	//throws bad_alloc
+    Drawable(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data, int maskBits);	//throws bad_alloc
+    ~Drawable();
+
+    RI_INLINE const Color::Descriptor&	getDescriptor() const		{ return m_color->getDescriptor(); }
+    RI_INLINE int       getNumMaskBits() const                      { if(!m_mask) return 0; return m_mask->getDescriptor().alphaBits; }
+    RI_INLINE int		getWidth() const							{ return m_color->getWidth(); }
+    RI_INLINE int		getHeight() const							{ return m_color->getHeight(); }
+    RI_INLINE int		getNumSamples() const						{ return m_color->getNumSamples(); }
+    RI_INLINE void		addReference()								{ m_referenceCount++; }
+    RI_INLINE int		removeReference()							{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+    RI_INLINE int		isInUse() const								{ return m_color->isInUse() || (m_mask && m_mask->isInUse()); }
+    RI_INLINE bool		isInUse(Image* image) const					{ return m_color->isInUse(image) || (m_mask && m_mask->isInUse(image)); }
+    RI_INLINE Surface*  getColorBuffer() const                      { return m_color; }
+    RI_INLINE Surface*  getMaskBuffer() const                       { return m_mask; }
+
+    void				resize(VGContext* context, int newWidth, int newHeight);	//throws bad_alloc
+private:
+    Drawable(const Drawable&);			//!< Not allowed.
+    void operator=(const Drawable&);	//!< Not allowed.
+
+    int                 m_referenceCount;
+    Surface*			m_color;
+    Surface*            m_mask;
+};
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+//==============================================================================================
+
+#endif /* __RIIMAGE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riMath.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,102 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of non-inline matrix functions.
+ * \note	
+ *//*-------------------------------------------------------------------*/
+
+#include "riDefs.h"
+#include "riMath.h"
+
+#if 0
+#include <stdio.h>
+
+static void printMatrix(const Matrix3x3& m)
+{
+    // For tracing a bug in matrix inverse in release-builds.
+    for(int i = 0; i < 3; i++)
+    {
+        printf("[%.4f %.4f %.4f]\n", m[i][0], m[i][1], m[i][2]);
+    }
+}
+
+#endif
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Inverts a 3x3 matrix. Returns false if the matrix is singular.
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+bool Matrix3x3::invert()
+{
+    // \todo Save computation on affine matrices?
+	bool affine = isAffine();
+	RIfloat det00 = matrix[1][1]*matrix[2][2] - matrix[2][1]*matrix[1][2];
+	RIfloat det01 = matrix[2][0]*matrix[1][2] - matrix[1][0]*matrix[2][2];
+	RIfloat det02 = matrix[1][0]*matrix[2][1] - matrix[2][0]*matrix[1][1];
+
+	RIfloat d = matrix[0][0]*det00 + matrix[0][1]*det01 + matrix[0][2]*det02;
+	if( d == 0.0f ) return false;	//singular, leave the matrix unmodified and return false
+	d = 1.0f / d;
+
+	Matrix3x3 t;
+
+    // \note There is some bug (in GCC?) in accessing matrix elements: If data
+    // is accessed like: t[i][j], then the following will produce incorrect
+    // resulst on optimized builds. If the data is accessed through t.matrix,
+    // then the output is correct. Debug build works correctly, and if print
+    // calls are inserted, the code also works correctly. The context to get
+    // this bug appear are fill paints (linear and radial gradient test
+    // functions).
+
+	t.matrix[0][0] = d * det00;
+	t.matrix[1][0] = d * det01;
+	t.matrix[2][0] = d * det02;
+    //printf("t\n");
+    //printMatrix(t);
+	t.matrix[0][1] = d * (matrix[2][1]*matrix[0][2] - matrix[0][1]*matrix[2][2]);
+	t.matrix[1][1] = d * (matrix[0][0]*matrix[2][2] - matrix[2][0]*matrix[0][2]);
+	t.matrix[2][1] = d * (matrix[2][0]*matrix[0][1] - matrix[0][0]*matrix[2][1]);
+	t.matrix[0][2] = d * (matrix[0][1]*matrix[1][2] - matrix[1][1]*matrix[0][2]);
+	t.matrix[1][2] = d * (matrix[1][0]*matrix[0][2] - matrix[0][0]*matrix[1][2]);
+	t.matrix[2][2] = d * (matrix[0][0]*matrix[1][1] - matrix[1][0]*matrix[0][1]);
+	if(affine)
+		t[2].set(0,0,1);	//affine matrix stays affine
+	*this = t;
+	return true;
+}
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riMath.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,452 @@
+#ifndef __RIMATH_H
+#define __RIMATH_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Math functions, Vector and Matrix classes.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIDEFS_H
+#include "riDefs.h"
+#endif
+
+#include <math.h>
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RI_INLINE int		RI_ISNAN(float a)
+{
+    RIfloatInt p;
+    p.f = a;
+    unsigned int exponent = (p.i>>23) & 0xff;
+    unsigned int mantissa = p.i & 0x7fffff;
+    if(exponent == 255 && mantissa)
+        return 1;
+    return 0;
+}
+
+#if (RI_MANTISSA_BITS > 23)
+#error RI_MANTISSA_BITS is greater than 23
+#elif (RI_EXPONENT_BITS > 8)
+#error RI_EXPONENT_BITS is greater than 8
+#elif (RI_MANTISSA_BITS != 23) || (RI_EXPONENT_BITS != 8)
+
+class RIfloat
+{
+public:
+    RIfloat() : v(0.0f)						{ removeBits(); }
+    RIfloat(float a) : v(a)					{ removeBits(); }
+    RIfloat(double a) : v((float)a)			{ removeBits(); }
+    RIfloat(int a) : v((float)a)			{ removeBits(); }
+    RIfloat(unsigned int a) : v((float)a)	{ removeBits(); }
+    RIfloat&	operator=(const RIfloat &a)	{ v = a.v; removeBits(); return *this; }
+    RIfloat&	operator+=(const RIfloat &a){ v += a.v; removeBits(); return *this; }
+    RIfloat&	operator-=(const RIfloat &a){ v -= a.v; removeBits(); return *this; }
+    RIfloat&	operator*=(const RIfloat &a){ v *= a.v; removeBits(); return *this; }
+    RIfloat&	operator/=(const RIfloat &a){ v /= a.v; removeBits(); return *this; }
+    RIfloat		operator-() const			{ return -v; }
+    operator float() const					{ return v; }
+    operator double() const					{ return (double)v; }
+    operator int() const					{ return (int)v; }
+
+    friend RIfloat	operator+(const RIfloat &a, const RIfloat &b);
+    friend RIfloat	operator+(float a, const RIfloat &b);
+    friend RIfloat	operator+(const RIfloat &a, float b);
+    friend RIfloat	operator-(const RIfloat &a, const RIfloat &b);
+    friend RIfloat	operator-(float a, const RIfloat &b);
+    friend RIfloat	operator-(const RIfloat &a, float b);
+    friend RIfloat	operator*(const RIfloat &a, const RIfloat &b);
+    friend RIfloat	operator*(float a, const RIfloat &b);
+    friend RIfloat	operator*(const RIfloat &a, float b);
+    friend RIfloat	operator/(const RIfloat &a, const RIfloat &b);
+    friend RIfloat	operator/(float a, const RIfloat &b);
+    friend RIfloat	operator/(const RIfloat &a, float b);
+
+    friend bool		operator<(const RIfloat &a, const RIfloat &b);
+    friend bool		operator<(float a, const RIfloat &b);
+    friend bool		operator<(const RIfloat &a, float b);
+    friend bool		operator>(const RIfloat &a, const RIfloat &b);
+    friend bool		operator>(float a, const RIfloat &b);
+    friend bool		operator>(const RIfloat &a, float b);
+    friend bool		operator<=(const RIfloat &a, const RIfloat &b);
+    friend bool		operator<=(float a, const RIfloat &b);
+    friend bool		operator<=(const RIfloat &a, float b);
+    friend bool		operator>=(const RIfloat &a, const RIfloat &b);
+    friend bool		operator>=(float a, const RIfloat &b);
+    friend bool		operator>=(const RIfloat &a, float b);
+    friend bool		operator==(const RIfloat &a, const RIfloat &b);
+    friend bool		operator==(float a, const RIfloat &b);
+    friend bool		operator==(const RIfloat &a, float b);
+    friend bool		operator!=(const RIfloat &a, const RIfloat &b);
+    friend bool		operator!=(float a, const RIfloat &b);
+    friend bool		operator!=(const RIfloat &a, float b);
+private:
+    void	removeBits()
+    {
+        RIfloatInt p;
+        p.f = v;
+        unsigned int exponent = (p.i>>23) & 0xff;
+        if(exponent == 0 || exponent == 255)
+            return;	//zero, denormal, infinite, or NaN
+
+        p.i &= ~((1<<(23-RI_MANTISSA_BITS))-1);
+
+#if (RI_EXPONENT_BITS != 8)
+        if (exponent > 127 + (1 << (RI_EXPONENT_BITS-1)))
+            exponent = 127 + (1 << (RI_EXPONENT_BITS-1));
+
+        if (exponent < 127 + 1 - (1 << (RI_EXPONENT_BITS-1)))
+            exponent = 127 + 1 - (1 << (RI_EXPONENT_BITS-1));
+
+        p.i &= ~(0xff<<23);
+        p.i |= exponent<<23;
+#endif
+        v = p.f;
+    }
+
+    float		v;
+};
+
+RI_INLINE RIfloat operator+(const RIfloat &a, const RIfloat &b)	{ return RIfloat(a.v+b.v); }
+RI_INLINE RIfloat operator+(float a, const RIfloat &b)			{ return RIfloat(a+b.v); }
+RI_INLINE RIfloat operator+(const RIfloat &a, float b)			{ return RIfloat(a.v+b); }
+RI_INLINE RIfloat operator-(const RIfloat &a, const RIfloat &b)	{ return RIfloat(a.v-b.v); }
+RI_INLINE RIfloat operator-(float a, const RIfloat &b)			{ return RIfloat(a-b.v); }
+RI_INLINE RIfloat operator-(const RIfloat &a, float b)			{ return RIfloat(a.v-b); }
+RI_INLINE RIfloat operator*(const RIfloat &a, const RIfloat &b)	{ return RIfloat(a.v*b.v); }
+RI_INLINE RIfloat operator*(float a, const RIfloat &b)			{ return RIfloat(a*b.v); }
+RI_INLINE RIfloat operator*(const RIfloat &a, float b)			{ return RIfloat(a.v*b); }
+RI_INLINE RIfloat operator/(const RIfloat &a, const RIfloat &b)	{ return RIfloat(a.v/b.v); }
+RI_INLINE RIfloat operator/(float a, const RIfloat &b)			{ return RIfloat(a/b.v); }
+RI_INLINE RIfloat operator/(const RIfloat &a, float b)			{ return RIfloat(a.v/b); }
+
+RI_INLINE bool operator<(const RIfloat &a, const RIfloat &b)	{ return a.v < b.v ? true : false; }
+RI_INLINE bool operator<(float a, const RIfloat &b)				{ return a < b.v ? true : false; }
+RI_INLINE bool operator<(const RIfloat &a, float b)				{ return a.v < b ? true : false; }
+RI_INLINE bool operator>(const RIfloat &a, const RIfloat &b)	{ return a.v > b.v ? true : false; }
+RI_INLINE bool operator>(float a, const RIfloat &b)				{ return a > b.v ? true : false; }
+RI_INLINE bool operator>(const RIfloat &a, float b)				{ return a.v > b ? true : false; }
+RI_INLINE bool operator<=(const RIfloat &a, const RIfloat &b)	{ return a.v <= b.v ? true : false; }
+RI_INLINE bool operator<=(float a, const RIfloat &b)			{ return a <= b.v ? true : false; }
+RI_INLINE bool operator<=(const RIfloat &a, float b)			{ return a.v <= b ? true : false; }
+RI_INLINE bool operator>=(const RIfloat &a, const RIfloat &b)	{ return a.v >= b.v ? true : false; }
+RI_INLINE bool operator>=(float a, const RIfloat &b)			{ return a >= b.v ? true : false; }
+RI_INLINE bool operator>=(const RIfloat &a, float b)			{ return a.v >= b ? true : false; }
+RI_INLINE bool operator==(const RIfloat &a, const RIfloat &b)	{ return a.v == b.v ? true : false; }
+RI_INLINE bool operator==(float a, const RIfloat &b)			{ return a == b.v ? true : false; }
+RI_INLINE bool operator==(const RIfloat &a, float b)			{ return a.v == b ? true : false; }
+RI_INLINE bool operator!=(const RIfloat &a, const RIfloat &b)	{ return a.v != b.v ? true : false; }
+RI_INLINE bool operator!=(float a, const RIfloat &b)			{ return a != b.v ? true : false; }
+RI_INLINE bool operator!=(const RIfloat &a, float b)			{ return a.v != b ? true : false; }
+
+#else
+typedef float RIfloat;
+#endif
+
+#define	RI_PI						3.141592654f
+
+RI_INLINE RIfloat   RI_FRAC(RIfloat f)                          { return f - (RIfloat)(int)f; }
+RI_INLINE int       RI_ROUND_TO_INT(RIfloat v)                  { return (v >= 0.0f) ? (int)(v+0.5f) : (int)(v-0.5f); }
+RI_INLINE RIfloat	RI_MAX(RIfloat a, RIfloat b)				{ return (a > b) ? a : b; }
+RI_INLINE int		RI_MAX(int a, int b)						{ return (a > b) ? a : b; }
+RI_INLINE RIfloat	RI_MIN(RIfloat a, RIfloat b)				{ return (a < b) ? a : b; }
+RI_INLINE int		RI_MIN(int a, int b)						{ return (a < b) ? a : b; }
+RI_INLINE RIfloat	RI_CLAMP(RIfloat a, RIfloat l, RIfloat h)	{ if(RI_ISNAN(a)) return l; RI_ASSERT(l <= h); return (a < l) ? l : (a > h) ? h : a; }
+RI_INLINE int       RI_CEIL(RIfloat a) {return (int)ceilf(a);}
+RI_INLINE int       RI_FLOOR(RIfloat a) { return (int)floorf(a); }
+RI_INLINE void		RI_SWAP(RIfloat &a, RIfloat &b)				{ RIfloat tmp = a; a = b; b = tmp; }
+RI_INLINE RIfloat	RI_ABS(RIfloat a)							{ return (a < 0.0f) ? -a : a; }
+RI_INLINE RIfloat	RI_SQR(RIfloat a)							{ return a * a; }
+RI_INLINE RIfloat	RI_DEG_TO_RAD(RIfloat a)					{ return a * RI_PI / 180.0f; }
+RI_INLINE RIfloat	RI_RAD_TO_DEG(RIfloat a)					{ return a * 180.0f/ RI_PI; }
+RI_INLINE RIfloat	RI_MOD(RIfloat a, RIfloat b)				{ if(RI_ISNAN(a) || RI_ISNAN(b)) return 0.0f; RI_ASSERT(b >= 0.0f); if(b == 0.0f) return 0.0f; RIfloat f = (RIfloat)fmod(a, b); if(f < 0.0f) f += b; RI_ASSERT(f >= 0.0f && f <= b); return f; }
+
+#define RI_ANY_SWAP(type, a, b) {type tmp = a; a = b; b = tmp;}
+
+RI_INLINE void      RI_INT16_SWAP(RIint16 &a, RIint16 &b) {RIint16 tmp = a; a = b; b = tmp;}
+RI_INLINE int       RI_INT_ABS(int a)                   { return (a >= 0) ? a : -a; }
+RI_INLINE int		RI_INT_MAX(int a, int b)			{ return (a > b) ? a : b; }
+RI_INLINE int		RI_INT_MIN(int a, int b)			{ return (a < b) ? a : b; }
+RI_INLINE int       RI_INT_CLAMP(int a, int l, int h)   { return (a < l) ? l : (a > h) ? h : a; }
+RI_INLINE void		RI_INT_SWAP(int &a, int &b)			{ int tmp = a; a = b; b = tmp; }
+RI_INLINE int		RI_INT_MOD(int a, int b)			{ RI_ASSERT(b >= 0); if(!b) return 0; int i = a % b; if(i < 0) i += b; RI_ASSERT(i >= 0 && i < b); return i; }
+RI_INLINE int		RI_INT_ADDSATURATE(int a, int b)	{ RI_ASSERT(b >= 0); int r = a + b; return (r >= a) ? r : RI_INT32_MAX; }
+
+RI_INLINE RIfloat validateFloat(RIfloat f)
+{
+    //this function is used for all floating point input values
+    if(RI_ISNAN(f)) return 0.0f;	//convert NaN to zero
+    return RI_CLAMP(f, -RI_FLOAT_MAX, RI_FLOAT_MAX);	//clamp +-inf to +-RIfloat max
+}
+
+
+
+RI_INLINE int       RI_SHL(int a, int sh)
+{
+    RI_ASSERT(sh >= 0 && sh <= 31);
+    int r = a << sh;
+    RI_ASSERT(a >= 0 ? (r >= 0) : (r < 0));
+    return r;
+}
+
+RI_INLINE int RI_SAT_SHL(RIint32 a, int sh)
+{
+    RI_ASSERT(sh >= 0 && sh <= 31);
+
+    RIint64 r = ((RIint64)a) << sh;
+
+    if (r > 0x7fffffff)
+        return 0x7fffffff;
+    else if (r < (long long)(int)0x80000000)
+        return 0x80000000;
+
+    return (RIint32)r;
+}
+
+RI_INLINE int RI_SHR(int a, int sh)
+{
+    RI_ASSERT(sh >= 0 && sh <= 31);
+    int r = a >> sh;
+    return r;
+}
+
+RI_INLINE RIfloat RI_FLOAT_TO_FX(RIfloat f, unsigned int n) { return (RIfloat)RI_ROUND_TO_INT(f * (RIfloat)RI_SHL(1, n)); }
+
+class Matrix3x3;
+class Vector2;
+class Vector3;
+
+//==============================================================================================
+
+//MatrixRxC, R = number of rows, C = number of columns
+//indexing: matrix[row][column]
+//Matrix3x3 inline functions cannot be inside the class because Vector3 is not defined yet when Matrix3x3 is defined
+
+class Matrix3x3
+{
+public:
+    RI_INLINE					Matrix3x3		();						//initialized to identity
+    RI_INLINE					Matrix3x3		( const Matrix3x3& m );
+    RI_INLINE					Matrix3x3		( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 );
+    RI_INLINE					~Matrix3x3		();
+    RI_INLINE Matrix3x3&		operator=		( const Matrix3x3& m );
+    RI_INLINE Vector3&			operator[]		( int i );				//returns a row vector
+    RI_INLINE const Vector3&	operator[]		( int i ) const;
+    RI_INLINE void				set				( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 );
+    RI_INLINE const Vector3		getRow			( int i ) const;
+    RI_INLINE const Vector3		getColumn		( int i ) const;
+    RI_INLINE void				setRow			( int i, const Vector3& v );
+    RI_INLINE void				setColumn		( int i, const Vector3& v );
+    RI_INLINE void				operator*=		( const Matrix3x3& m );
+    RI_INLINE void				operator*=		( RIfloat f );
+    RI_INLINE void				operator+=		( const Matrix3x3& m );
+    RI_INLINE void				operator-=		( const Matrix3x3& m );
+    RI_INLINE const Matrix3x3	operator-		() const;
+    RI_INLINE void				identity		();
+    RI_INLINE void				transpose		();
+    bool						invert			();	//if the matrix is singular, returns false and leaves it unmodified
+    RI_INLINE RIfloat				det				() const;
+    RI_INLINE bool				isAffine		() const;
+    RI_INLINE void              assertValid     () const;
+    RI_INLINE void              validate        ();
+
+private:
+    RIfloat						matrix[3][3];
+};
+
+//==============================================================================================
+
+class Vector2
+{
+public:
+    RI_INLINE					Vector2			() : x(0.0f), y(0.0f)					{}
+    RI_INLINE					Vector2			( const Vector2& v ) : x(v.x), y(v.y)	{}
+    RI_INLINE					Vector2			( RIfloat fx, RIfloat fy ) : x(fx), y(fy)	{}
+    RI_INLINE					~Vector2		()								{}
+    RI_INLINE Vector2&			operator=		( const Vector2& v )			{ x = v.x; y = v.y; return *this; }
+    RI_INLINE RIfloat&			operator[]		( int i )						{ RI_ASSERT(i>=0&&i<2); return (&x)[i]; }
+    RI_INLINE const RIfloat&	operator[]		( int i ) const					{ RI_ASSERT(i>=0&&i<2); return (&x)[i]; }
+    RI_INLINE void				set				( RIfloat fx, RIfloat fy )			{ x = fx; y = fy; }
+    RI_INLINE void				operator*=		( RIfloat f )						{ x *= f; y *= f; }
+    RI_INLINE void				operator+=		( const Vector2& v )			{ x += v.x; y += v.y; }
+    RI_INLINE void				operator-=		( const Vector2& v )			{ x -= v.x; y -= v.y; }
+    RI_INLINE const Vector2		operator-		() const						{ return Vector2(-x,-y); }
+    //if the vector is zero, returns false and leaves it unmodified
+    RI_INLINE bool				normalize		()								{ double l = (double)x*(double)x+(double)y*(double)y; if( l == 0.0 ) return false; l = 1.0 / sqrt(l); x = (RIfloat)((double)x * l); y = (RIfloat)((double)y * l); return true; }
+    RI_INLINE RIfloat			length			() const						{ return (RIfloat)sqrt((double)x*(double)x+(double)y*(double)y); }
+    RI_INLINE void				scale			( const Vector2& v )			{ x *= v.x; y *= v.y; }	//component-wise scale
+    RI_INLINE void				negate			()								{ x = -x; y = -y; }
+
+    RIfloat						x,y;
+};
+
+//==============================================================================================
+
+class Vector3
+{
+public:
+    RI_INLINE					Vector3			() : x(0.0f), y(0.0f), z(0.0f)							{}
+    RI_INLINE					Vector3			( const Vector3& v ) : x(v.x), y(v.y), z(v.z)			{}
+    RI_INLINE					Vector3			( RIfloat fx, RIfloat fy, RIfloat fz ) : x(fx), y(fy), z(fz)	{}
+    RI_INLINE					~Vector3		()								{}
+    RI_INLINE Vector3&			operator=		( const Vector3& v )			{ x = v.x; y = v.y; z = v.z; return *this; }
+    RI_INLINE RIfloat&			operator[]		( int i )						{ RI_ASSERT(i>=0&&i<3); return (&x)[i]; }
+    RI_INLINE const RIfloat&	operator[]		( int i ) const					{ RI_ASSERT(i>=0&&i<3); return (&x)[i]; }
+    RI_INLINE void				set				( RIfloat fx, RIfloat fy, RIfloat fz ){ x = fx; y = fy; z = fz; }
+    RI_INLINE void				operator*=		( RIfloat f )						{ x *= f; y *= f; z *= f; }
+    RI_INLINE void				operator+=		( const Vector3& v )			{ x += v.x; y += v.y; z += v.z; }
+    RI_INLINE void				operator-=		( const Vector3& v )			{ x -= v.x; y -= v.y; z -= v.z; }
+    RI_INLINE const Vector3		operator-		() const						{ return Vector3(-x,-y,-z); }
+    //if the vector is zero, returns false and leaves it unmodified
+    RI_INLINE bool				normalize		()								{ double l = (double)x*(double)x+(double)y*(double)y+(double)z*(double)z; if( l == 0.0 ) return false; l = 1.0 / sqrt(l); x = (RIfloat)((double)x * l); y = (RIfloat)((double)y * l); z = (RIfloat)((double)z * l); return true; }
+    RI_INLINE RIfloat			length			() const						{ return (RIfloat)sqrt((double)x*(double)x+(double)y*(double)y+(double)z*(double)z); }
+    RI_INLINE void				scale			( const Vector3& v )			{ x *= v.x; y *= v.y; z *= v.z; }	//component-wise scale
+    RI_INLINE void				negate			()								{ x = -x; y = -y; z = -z; }
+
+    RIfloat						x,y,z;
+};
+
+//==============================================================================================
+
+//Vector2 global functions
+RI_INLINE bool			operator==	( const Vector2& v1, const Vector2& v2 )	{ return (v1.x == v2.x) && (v1.y == v2.y); }
+RI_INLINE bool			operator!=	( const Vector2& v1, const Vector2& v2 )	{ return (v1.x != v2.x) || (v1.y != v2.y); }
+RI_INLINE bool			isEqual		( const Vector2& v1, const Vector2& v2, RIfloat epsilon )	{ return RI_SQR(v2.x-v1.x) + RI_SQR(v2.y-v1.y) <= epsilon*epsilon; }
+RI_INLINE bool			isZero		( const Vector2& v )						{ return (v.x == 0.0f) && (v.y == 0.0f); }
+RI_INLINE const Vector2	operator*	( RIfloat f, const Vector2& v )				{ return Vector2(v.x*f,v.y*f); }
+RI_INLINE const Vector2	operator*	( const Vector2& v, RIfloat f )				{ return Vector2(v.x*f,v.y*f); }
+RI_INLINE const Vector2	operator+	( const Vector2& v1, const Vector2& v2 )	{ return Vector2(v1.x+v2.x, v1.y+v2.y); }
+RI_INLINE const Vector2	operator-	( const Vector2& v1, const Vector2& v2 )	{ return Vector2(v1.x-v2.x, v1.y-v2.y); }
+RI_INLINE RIfloat		dot			( const Vector2& v1, const Vector2& v2 )	{ return v1.x*v2.x+v1.y*v2.y; }
+//if v is a zero vector, returns a zero vector
+RI_INLINE const Vector2	normalize	( const Vector2& v )						{ double l = (double)v.x*(double)v.x+(double)v.y*(double)v.y; if( l != 0.0 ) l = 1.0 / sqrt(l); return Vector2((RIfloat)((double)v.x * l), (RIfloat)((double)v.y * l)); }
+//if onThis is a zero vector, returns a zero vector
+RI_INLINE const Vector2	project		( const Vector2& v, const Vector2& onThis ) { RIfloat l = dot(onThis,onThis); if( l != 0.0f ) l = dot(v, onThis)/l; return onThis * l; }
+RI_INLINE const Vector2	lerp		( const Vector2& v1, const Vector2& v2, RIfloat ratio )	{ return v1 + ratio * (v2 - v1); }
+RI_INLINE const Vector2	scale		( const Vector2& v1, const Vector2& v2 )	{ return Vector2(v1.x*v2.x, v1.y*v2.y); }
+//matrix * column vector. The input vector2 is implicitly expanded to (x,y,1)
+RI_INLINE const Vector2 affineTransform( const Matrix3x3& m, const Vector2& v )	{ RI_ASSERT(m.isAffine()); return Vector2(v.x * m[0][0] + v.y * m[0][1] + m[0][2], v.x * m[1][0] + v.y * m[1][1] + m[1][2]); }
+//matrix * column vector. The input vector2 is implicitly expanded to (x,y,0)
+RI_INLINE const Vector2 affineTangentTransform(const Matrix3x3& m, const Vector2& v)	{ RI_ASSERT(m.isAffine()); return Vector2(v.x * m[0][0] + v.y * m[0][1], v.x * m[1][0] + v.y * m[1][1]); }
+RI_INLINE const Vector2 perpendicularCW(const Vector2& v)						{ return Vector2(v.y, -v.x); }
+RI_INLINE const Vector2 perpendicularCCW(const Vector2& v)						{ return Vector2(-v.y, v.x); }
+RI_INLINE const Vector2 perpendicular(const Vector2& v, bool cw)				{ if(cw) return Vector2(v.y, -v.x); return Vector2(-v.y, v.x); }
+
+//==============================================================================================
+
+//Vector3 global functions
+RI_INLINE bool			operator==	( const Vector3& v1, const Vector3& v2 )	{ return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); }
+RI_INLINE bool			operator!=	( const Vector3& v1, const Vector3& v2 )	{ return (v1.x != v2.x) || (v1.y != v2.y) || (v1.z != v2.z); }
+RI_INLINE bool			isEqual		( const Vector3& v1, const Vector3& v2, RIfloat epsilon )	{ return RI_SQR(v2.x-v1.x) + RI_SQR(v2.y-v1.y) + RI_SQR(v2.z-v1.z) <= epsilon*epsilon; }
+RI_INLINE const Vector3	operator*	( RIfloat f, const Vector3& v )				{ return Vector3(v.x*f,v.y*f,v.z*f); }
+RI_INLINE const Vector3	operator*	( const Vector3& v, RIfloat f )				{ return Vector3(v.x*f,v.y*f,v.z*f); }
+RI_INLINE const Vector3	operator+	( const Vector3& v1, const Vector3& v2 )	{ return Vector3(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z); }
+RI_INLINE const Vector3	operator-	( const Vector3& v1, const Vector3& v2 )	{ return Vector3(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z); }
+RI_INLINE RIfloat		dot			( const Vector3& v1, const Vector3& v2 )	{ return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z; }
+RI_INLINE const Vector3	cross		( const Vector3& v1, const Vector3& v2 )	{ return Vector3( v1.y*v2.z-v1.z*v2.y, v1.z*v2.x-v1.x*v2.z, v1.x*v2.y-v1.y*v2.x ); }
+//if v is a zero vector, returns a zero vector
+RI_INLINE const Vector3	normalize	( const Vector3& v )						{ double l = (double)v.x*(double)v.x+(double)v.y*(double)v.y+(double)v.z*(double)v.z; if( l != 0.0 ) l = 1.0 / sqrt(l); return Vector3((RIfloat)((double)v.x * l), (RIfloat)((double)v.y * l), (RIfloat)((double)v.z * l)); }
+RI_INLINE const Vector3	lerp		( const Vector3& v1, const Vector3& v2, RIfloat ratio )	{ return v1 + ratio * (v2 - v1); }
+RI_INLINE const Vector3	scale		( const Vector3& v1, const Vector3& v2 )	{ return Vector3(v1.x*v2.x, v1.y*v2.y, v1.z*v2.z); }
+
+//==============================================================================================
+
+//matrix * column vector
+RI_INLINE const Vector3	operator*	( const Matrix3x3& m, const Vector3& v)		{ return Vector3( v.x*m[0][0]+v.y*m[0][1]+v.z*m[0][2], v.x*m[1][0]+v.y*m[1][1]+v.z*m[1][2], v.x*m[2][0]+v.y*m[2][1]+v.z*m[2][2] ); }
+
+//==============================================================================================
+
+//Matrix3x3 global functions
+RI_INLINE bool				operator==	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) if( m1[i][j] != m2[i][j] ) return false; return true; }
+RI_INLINE bool				operator!=	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ return !(m1 == m2); }
+RI_INLINE const Matrix3x3	operator*	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ Matrix3x3 t; for(int i=0;i<3;i++) for(int j=0;j<3;j++) t[i][j] = m1[i][0] * m2[0][j] + m1[i][1] * m2[1][j] + m1[i][2] * m2[2][j]; return t; }
+RI_INLINE const Matrix3x3	operator*	( RIfloat f, const Matrix3x3& m )					{ Matrix3x3 t(m); t *= f; return t; }
+RI_INLINE const Matrix3x3	operator*	( const Matrix3x3& m, RIfloat f )					{ Matrix3x3 t(m); t *= f; return t; }
+RI_INLINE const Matrix3x3	operator+	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ Matrix3x3 t(m1); t += m2; return t; }
+RI_INLINE const Matrix3x3	operator-	( const Matrix3x3& m1, const Matrix3x3& m2 )	{ Matrix3x3 t(m1); t -= m2; return t; }
+RI_INLINE const Matrix3x3	transpose	( const Matrix3x3& m )							{ Matrix3x3 t(m); t.transpose(); return t; }
+// if the matrix is singular, returns it unmodified
+RI_INLINE const Matrix3x3	invert		( const Matrix3x3& m )							{ Matrix3x3 t(m); t.invert(); return t; }
+
+//==============================================================================================
+
+//Matrix3x3 inline functions (cannot be inside the class because Vector3 is not defined yet when Matrix3x3 is defined)
+RI_INLINE					Matrix3x3::Matrix3x3	()									{ identity(); }
+RI_INLINE					Matrix3x3::Matrix3x3	( const Matrix3x3& m )				{ *this = m; }
+RI_INLINE					Matrix3x3::Matrix3x3	( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 )	{ set(m00,m01,m02,m10,m11,m12,m20,m21,m22); }
+RI_INLINE					Matrix3x3::~Matrix3x3	()									{}
+RI_INLINE Matrix3x3&		Matrix3x3::operator=	( const Matrix3x3& m )				{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] = m.matrix[i][j]; return *this; }
+RI_INLINE Vector3&			Matrix3x3::operator[]	( int i )							{ RI_ASSERT(i>=0&&i<3); return (Vector3&)matrix[i][0]; }
+RI_INLINE const Vector3&	Matrix3x3::operator[]	( int i ) const						{ RI_ASSERT(i>=0&&i<3); return (const Vector3&)matrix[i][0]; }
+RI_INLINE void				Matrix3x3::set			( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 ) { matrix[0][0] = m00; matrix[0][1] = m01; matrix[0][2] = m02; matrix[1][0] = m10; matrix[1][1] = m11; matrix[1][2] = m12; matrix[2][0] = m20; matrix[2][1] = m21; matrix[2][2] = m22; }
+RI_INLINE const Vector3		Matrix3x3::getRow		( int i ) const						{ RI_ASSERT(i>=0&&i<3); return Vector3(matrix[i][0], matrix[i][1], matrix[i][2]); }
+RI_INLINE const Vector3		Matrix3x3::getColumn	( int i ) const						{ RI_ASSERT(i>=0&&i<3); return Vector3(matrix[0][i], matrix[1][i], matrix[2][i]); }
+RI_INLINE void				Matrix3x3::setRow		( int i, const Vector3& v )			{ RI_ASSERT(i>=0&&i<3); matrix[i][0] = v.x; matrix[i][1] = v.y; matrix[i][2] = v.z; }
+RI_INLINE void				Matrix3x3::setColumn	( int i, const Vector3& v )			{ RI_ASSERT(i>=0&&i<3); matrix[0][i] = v.x; matrix[1][i] = v.y; matrix[2][i] = v.z; }
+RI_INLINE void				Matrix3x3::operator*=	( const Matrix3x3& m )				{ *this = *this * m; }
+RI_INLINE void				Matrix3x3::operator*=	( RIfloat f )							{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] *= f; }
+RI_INLINE void				Matrix3x3::operator+=	( const Matrix3x3& m )				{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] += m.matrix[i][j]; }
+RI_INLINE void				Matrix3x3::operator-=	( const Matrix3x3& m )				{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] -= m.matrix[i][j]; }
+RI_INLINE const Matrix3x3	Matrix3x3::operator-	() const							{ return Matrix3x3( -matrix[0][0],-matrix[0][1],-matrix[0][2], -matrix[1][0],-matrix[1][1],-matrix[1][2], -matrix[2][0],-matrix[2][1],-matrix[2][2]); }
+RI_INLINE void				Matrix3x3::identity		()									{ for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] = (i == j) ? 1.0f : 0.0f; }
+RI_INLINE void				Matrix3x3::transpose	()									{ RI_SWAP(matrix[1][0], matrix[0][1]); RI_SWAP(matrix[2][0], matrix[0][2]); RI_SWAP(matrix[2][1], matrix[1][2]); }
+RI_INLINE RIfloat			Matrix3x3::det			() const							{ return matrix[0][0] * (matrix[1][1]*matrix[2][2] - matrix[2][1]*matrix[1][2]) + matrix[0][1] * (matrix[2][0]*matrix[1][2] - matrix[1][0]*matrix[2][2]) + matrix[0][2] * (matrix[1][0]*matrix[2][1] - matrix[2][0]*matrix[1][1]); }
+RI_INLINE bool				Matrix3x3::isAffine		() const							{ if(matrix[2][0] == 0.0f && matrix[2][1] == 0.0f && matrix[2][2] == 1.0f) return true; return false; }
+
+RI_INLINE void Matrix3x3::validate()
+{
+    for (int i = 0; i < 3; i++)
+        for (int j = 0; j < 3; j++)
+            matrix[i][j] = validateFloat(matrix[i][j]);
+}
+
+RI_INLINE void Matrix3x3::assertValid() const
+{
+#if defined(RI_DEBUG)
+    for (int i = 0; i < 3; i++)
+        for (int j = 0; j < 3; j++)
+            RI_ASSERT(!RI_ISNAN(matrix[i][j]));
+#endif
+}
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+#endif /* __RIMATH_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riMiniEGL.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2210 @@
+/*------------------------------------------------------------------------
+ *
+ * EGL 1.3
+ * -------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Simple implementation of EGL 1.3
+ * \note	caveats:
+            - always renders into the backbuffer and blits it to window (no single buffered rendering)
+            - no native Windows or Mac OS X pixmap support
+            - no power management events
+            - no support for swap interval
+ * \todo	what happens in egl functions when eglTerminate has been called but the context and surface are still in use?
+ * \todo	OSDeinitMutex should be called in case getEGL fails.
+ *//*-------------------------------------------------------------------*/
+
+#include "EGL/egl.h"
+#include "openvg.h"
+#include "riArray.h"
+#include "riMath.h"
+#include "riContext.h"
+#include "riImage.h"
+
+#include "riEGLOS.h"
+
+// Temp: A blitter is kept in the egl context for surface copies, but it will
+// be placed into the EGL to VG interface in the future.
+#ifndef __SFDYNAMICBLITTER_H
+#   include "sfDynamicBlitter.h"
+#endif
+
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+#if 0
+void* OSGetCurrentThreadID(void);
+void OSAcquireMutex(void);
+void OSReleaseMutex(void);
+void OSDeinitMutex(void);
+
+EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id);
+void* OSCreateWindowContext(EGLNativeWindowType window);
+void OSDestroyWindowContext(void* context);
+bool OSIsWindow(const void* context);
+void OSGetWindowSize(const void* context, int& width, int& height);
+void OSBlitToWindow(void* context, const Drawable* drawable);
+#else
+
+
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class RIEGLConfig
+{
+public:
+    RIEGLConfig() : m_desc(Color::formatToDescriptor(VG_sRGBA_8888)), m_configID(0)	{}
+    ~RIEGLConfig()							{}
+    void		set(int r, int g, int b, int a, int l, int bpp, int samples, int maskBits, int ID)
+    {
+        Color::Shape shape;
+        m_desc.redBits = r;
+        m_desc.greenBits = g;
+        m_desc.blueBits = b;
+        m_desc.alphaBits = a;
+        m_desc.luminanceBits = l;
+#if !defined(_WIN32) && 0
+        m_desc.alphaShift = 0;
+        m_desc.luminanceShift = 0;
+        m_desc.blueShift = b ? a : 0;
+        m_desc.greenShift = g ? a + b : 0;
+        m_desc.redShift = r ? a + b + g : 0;
+#else
+        m_desc.luminanceShift = 0;
+        m_desc.redShift = 0;
+        m_desc.greenShift = g ? r : 0;
+        m_desc.blueShift = b ? r + g : 0;
+        m_desc.alphaShift = a ? r + g + b : 0;
+
+#endif
+        m_desc.internalFormat = l ? (a ? Color::sLA : Color::lLA) : ((r || g || b ) ? Color::sRGBA : Color::lRGBA);
+
+        m_desc.bitsPerPixel = bpp;
+        m_desc.bytesPerPixel = bpp / 8;
+
+        {
+            // Determine shape
+            if (m_desc.hasAlpha())
+            {
+                if (m_desc.redBits > 0)
+                    shape = Color::SHAPE_ARGB;
+                else if (m_desc.isLuminance())
+                    shape = Color::SHAPE_AL;
+                else
+                {
+                    RI_ASSERT(m_desc.isAlphaOnly());
+                    shape = Color::SHAPE_A;
+                }
+            } else
+            {
+                if (m_desc.redBits > 0)
+                {
+                    if (m_desc.bitsPerPixel == 32)
+                        shape = Color::SHAPE_XRGB;
+                    else
+                    {
+                        RI_ASSERT(m_desc.bitsPerPixel == 24 || m_desc.bitsPerPixel == 16);
+                        shape = Color::SHAPE_RGB;
+                    }
+                } else if (m_desc.isLuminance())
+                {
+                    shape = Color::SHAPE_L;
+                } else
+                {
+                    RI_ASSERT(false);
+                }
+            }
+        }
+
+        m_desc.shape = shape;
+        //m_desc.format = Color::descriptorToVGImageFormat(m_desc);
+        m_desc.vgFormat = (VGImageFormat)-1;
+        RI_ASSERT(Color::isValidDescriptor(m_desc));
+        m_samples = samples;
+        m_maskBits = maskBits;
+        m_configID = ID;
+        m_config = (EGLConfig)ID;
+    }
+
+    Color::Descriptor configToDescriptor(bool sRGB, bool premultiplied) const
+    {
+        Color::Descriptor desc = m_desc;
+        unsigned int f = m_desc.luminanceBits ? Color::LUMINANCE : 0;
+        f |= sRGB ? Color::NONLINEAR : 0;
+        f |= premultiplied ? Color::PREMULTIPLIED : 0;
+        desc.internalFormat = (Color::InternalFormat)f;
+        return desc;
+    }
+
+    //EGL RED SIZE bits of Red in the color buffer
+    //EGL GREEN SIZE bits of Green in the color buffer
+    //EGL BLUE SIZE bits of Blue in the color buffer
+    //EGL ALPHA SIZE bits of Alpha in the color buffer
+    //EGL LUMINANCE SIZE bits of Luminance in the color buffer
+    Color::Descriptor	m_desc;
+    int					m_samples;
+    int                 m_maskBits;
+    EGLint				m_configID;			//EGL CONFIG ID unique EGLConfig identifier
+    EGLConfig           m_config;
+    //EGL BUFFER SIZE depth of the color buffer (sum of channel bits)
+    //EGL ALPHA MASK SIZE number alpha mask bits (always 8)
+    //EGL BIND TO TEXTURE RGB boolean True if bindable to RGB textures. (always EGL_FALSE)
+    //EGL BIND TO TEXTURE RGBA boolean True if bindable to RGBA textures. (always EGL_FALSE)
+    //EGL COLOR BUFFER TYPE enum color buffer type (EGL_RGB_BUFFER, EGL_LUMINANCE_BUFFER)
+    //EGL CONFIG CAVEAT enum any caveats for the configuration (always EGL_NONE)
+    //EGL DEPTH SIZE integer bits of Z in the depth buffer (always 0)
+    //EGL LEVEL integer frame buffer level (always 0)
+    //EGL MAX PBUFFER WIDTH integer maximum width of pbuffer (always INT_MAX)
+    //EGL MAX PBUFFER HEIGHT integer maximum height of pbuffer (always INT_MAX)
+    //EGL MAX PBUFFER PIXELS integer maximum size of pbuffer (always INT_MAX)
+    //EGL MAX SWAP INTERVAL integer maximum swap interval (always 1)
+    //EGL MIN SWAP INTERVAL integer minimum swap interval (always 1)
+    //EGL NATIVE RENDERABLE boolean EGL TRUE if native rendering APIs can render to surface (always EGL_FALSE)
+    //EGL NATIVE VISUAL ID integer handle of corresponding native visual (always 0)
+    //EGL NATIVE VISUAL TYPE integer native visual type of the associated visual (always EGL_NONE)
+    //EGL RENDERABLE TYPE bitmask which client rendering APIs are supported. (always EGL_OPENVG_BIT)
+    //EGL SAMPLE BUFFERS integer number of multisample buffers (always 0)
+    //EGL SAMPLES integer number of samples per pixel (always 0)
+    //EGL STENCIL SIZE integer bits of Stencil in the stencil buffer (always 0)
+    //EGL SURFACE TYPE bitmask which types of EGL surfaces are supported. (always EGL WINDOW BIT | EGL PIXMAP BIT | EGL PBUFFER BIT)
+    //EGL TRANSPARENT TYPE enum type of transparency supported (always EGL_NONE)
+    //EGL TRANSPARENT RED VALUE integer transparent red value (undefined)
+    //EGL TRANSPARENT GREEN VALUE integer transparent green value (undefined)
+    //EGL TRANSPARENT BLUE VALUE integer transparent blue value (undefined)
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class RIEGLContext
+{
+public:
+    RIEGLContext(OpenVGRI::VGContext* vgctx, const EGLConfig config);
+    ~RIEGLContext();
+    void	addReference()				{ m_referenceCount++; }
+    int		removeReference()			{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+    VGContext*      getVGContext() const      { return m_vgContext; }
+    EGLConfig       getConfig() const         { return m_config; }
+    DynamicBlitter& getBlitter()              { return m_blitter; }
+private:
+    RIEGLContext(const RIEGLContext&);
+    RIEGLContext& operator=(const RIEGLContext&);
+    VGContext*		m_vgContext;
+    const EGLConfig	m_config;
+    int				m_referenceCount;
+    DynamicBlitter  m_blitter;
+};
+
+RIEGLContext::RIEGLContext(OpenVGRI::VGContext* vgctx, const EGLConfig config) :
+    m_vgContext(vgctx),
+    m_config(config),
+    m_referenceCount(0)
+{
+}
+RIEGLContext::~RIEGLContext()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    RI_DELETE(m_vgContext);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class RIEGLSurface
+{
+public:
+    RIEGLSurface(void* OSWindowContext, const EGLConfig config, Drawable* drawable, bool largestPbuffer, int renderBuffer);
+    ~RIEGLSurface();
+    void	addReference()				{ m_referenceCount++; }
+    int		removeReference()			{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+    void*           getOSWindowContext() const { return m_OSWindowContext; }
+    EGLConfig       getConfig() const          { return m_config; }
+    Drawable*       getDrawable() const        { return m_drawable; }
+    bool            isLargestPbuffer() const   { return m_largestPbuffer; }
+    int             getRenderBuffer() const    { return m_renderBuffer; }
+
+private:
+    RIEGLSurface(const RIEGLSurface&);
+    RIEGLSurface& operator=(const RIEGLSurface&);
+    void*            m_OSWindowContext;
+    const EGLConfig	 m_config;
+    Drawable*        m_drawable;
+    bool			 m_largestPbuffer;
+    int				 m_renderBuffer;		//EGL_BACK_BUFFER or EGL_SINGLE_BUFFER
+    int				 m_referenceCount;
+};
+
+RIEGLSurface::RIEGLSurface(void* OSWindowContext, const EGLConfig config, Drawable* drawable, bool largestPbuffer, int renderBuffer) :
+    m_OSWindowContext(OSWindowContext),
+    m_config(config),
+    m_drawable(drawable),
+    m_largestPbuffer(largestPbuffer),
+    m_renderBuffer(renderBuffer),
+    m_referenceCount(0)
+{
+    RI_ASSERT(m_renderBuffer == EGL_BACK_BUFFER);   //only back buffer rendering is supported
+    m_drawable->addReference();
+}
+
+RIEGLSurface::~RIEGLSurface()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    OSDestroyWindowContext((OSWindowContext*)m_OSWindowContext);
+    if(m_drawable)
+    {
+        if(!m_drawable->removeReference())
+            RI_DELETE(m_drawable);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define EGL_NUMCONFIGS		5
+
+class RIEGLDisplay
+{
+public:
+    RIEGLDisplay(EGLDisplay id);
+    ~RIEGLDisplay();
+
+    int                getNumConfigs() const              { return EGL_NUMCONFIGS; }
+    const RIEGLConfig& getConfig(int i) const             { RI_ASSERT(i >= 0 && i < EGL_NUMCONFIGS); return m_configs[i]; }
+    const RIEGLConfig& getConfig(const EGLConfig config) const        { for(int i=0;i<EGL_NUMCONFIGS;i++) { if(m_configs[i].m_config == config) return m_configs[i]; } RI_ASSERT(0); return m_configs[0]; }
+
+    EGLDisplay         getID() const                       { return m_id; }
+
+    void              addContext(RIEGLContext* ctx)       { RI_ASSERT(ctx); m_contexts.push_back(ctx); }  //throws bad_alloc
+    void              removeContext(RIEGLContext* ctx)    { RI_ASSERT(ctx); bool res = m_contexts.remove(ctx); RI_ASSERT(res); RI_UNREF(res); }
+
+    void              addSurface(RIEGLSurface* srf)       { RI_ASSERT(srf); m_surfaces.push_back(srf); }  //throws bad_alloc
+    void              removeSurface(RIEGLSurface* srf)    { RI_ASSERT(srf); bool res = m_surfaces.remove(srf); RI_ASSERT(res); RI_UNREF(res); }
+
+    EGLBoolean        contextExists(const EGLContext ctx) const;
+    EGLBoolean        surfaceExists(const EGLSurface srf) const;
+    EGLBoolean        configExists(const EGLConfig cfg) const;
+
+private:
+    RIEGLDisplay(const RIEGLDisplay& t);
+    RIEGLDisplay& operator=(const RIEGLDisplay&t);
+
+    EGLDisplay              m_id;
+
+    Array<RIEGLContext*>	m_contexts;
+    Array<RIEGLSurface*>	m_surfaces;
+
+    RIEGLConfig             m_configs[EGL_NUMCONFIGS];
+};
+
+RIEGLDisplay::RIEGLDisplay(EGLDisplay id) :
+    m_id(id),
+    m_contexts(),
+    m_surfaces()
+{
+
+    //sorted by RGB/LUMINANCE (exact), larger total number of color bits (at least), buffer size (at least), config ID (exact)
+    //NOTE: 16 bit configs need to be sorted on the fly if the request ignores some channels
+    //NOTE: config IDs start from 1
+    //                 R  B  G  A  L  bpp samples maskBits ID
+    int i = 0;
+    m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 8, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 32
+    m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++;    // RGBX
+    m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 8, i+1); i++;	// 565
+    m_configs[i].set(0, 0, 0, 0, 8, 8,  1, 8, i+1); i++;	// L8
+    m_configs[i].set(0, 0, 0, 8, 0, 8,  1, 8, i+1); i++;	// A8
+    // \note The reference implementation does not support LA16 config, so it is currently
+    // not possible to test it. See if the format fits the specification.
+    //m_configs[i].set(0, 0, 0, 8, 8, 16,  1, 8, i+1); i++;	// LA16
+#if 0
+    m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 8, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 32
+    m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++;    // RGBX
+    m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 24
+    //m_configs[i].set(5, 5, 5, 1, 0, 16, 1, 4, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 4, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    //m_configs[i].set(4, 4, 4, 4, 0, 16, 1, 4, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    m_configs[i].set(0, 0, 0, 8, 0, 8,  1, 8, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 4, 0, 4,  1, 4, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 1, 0, 1,  1, 1, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 0, 8, 8,  1, 8, i+1); i++;	//EGL_LUMINANCE_BUFFER, buffer size = 8
+    //m_configs[i].set(0, 0, 0, 0, 1, 1,  1, 1, i+1); i++;	//EGL_LUMINANCE_BUFFER, buffer size = 1
+
+    //configs without mask
+    m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 32
+    m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 24
+    //m_configs[i].set(5, 5, 5, 1, 0, 16, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    //m_configs[i].set(4, 4, 4, 4, 0, 16, 1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 16
+    m_configs[i].set(0, 0, 0, 8, 0, 8,  1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 4, 0, 4,  1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 1, 0, 1,  1, 0, i+1); i++;	//EGL_RGB_BUFFER, buffer size = 8
+    m_configs[i].set(0, 0, 0, 0, 8, 8,  1, 0, i+1); i++;	//EGL_LUMINANCE_BUFFER, buffer size = 8
+    //m_configs[i].set(0, 0, 0, 0, 1, 1,  1, 0, 20);	//EGL_LUMINANCE_BUFFER, buffer size = 1
+#endif
+
+    RI_ASSERT(EGL_NUMCONFIGS == i);
+
+/*
+attrib                default        criteria order   priority
+--------------------------------------------------------------
+EGL_COLOR_BUFFER_TYPE EGL_RGB_BUFFER Exact    None    2
+EGL_RED_SIZE          0              AtLeast  Special 3
+EGL_GREEN_SIZE        0              AtLeast  Special 3
+EGL_BLUE_SIZE         0              AtLeast  Special 3
+EGL_LUMINANCE_SIZE    0              AtLeast  Special 3
+EGL_ALPHA_SIZE        0              AtLeast  Special 3
+EGL_BUFFER_SIZE       0              AtLeast  Smaller 4
+EGL_ALPHA_MASK_SIZE   0              AtLeast  Smaller 9
+EGL_CONFIG_ID         EGL_DONT_CARE  Exact    Smaller 11
+*/
+}
+
+RIEGLDisplay::~RIEGLDisplay()
+{
+    //mark everything for deletion, but don't delete the current context and surface
+    for(int i=0;i<m_contexts.size();i++)
+    {
+        if(!m_contexts[i]->removeReference())
+            RI_DELETE(m_contexts[i]);
+    }
+    m_contexts.clear();	//remove all contexts from the list (makes further references to the current contexts invalid)
+
+    for(int i=0;i<m_surfaces.size();i++)
+    {
+        if(!m_surfaces[i]->removeReference())
+            RI_DELETE(m_surfaces[i]);
+    }
+    m_surfaces.clear();	//remove all surfaces from the list (makes further references to the current surfaces invalid)
+}
+
+EGLBoolean RIEGLDisplay::contextExists(const EGLContext ctx) const
+{
+    for(int i=0;i<m_contexts.size();i++)
+    {
+        if(m_contexts[i] == ctx)
+            return EGL_TRUE;
+    }
+    return EGL_FALSE;
+}
+
+EGLBoolean RIEGLDisplay::surfaceExists(const EGLSurface surf) const
+{
+    for(int i=0;i<m_surfaces.size();i++)
+    {
+        if(m_surfaces[i] == surf)
+            return EGL_TRUE;
+    }
+    return EGL_FALSE;
+}
+
+EGLBoolean RIEGLDisplay::configExists(const EGLConfig config) const
+{
+    for(int i=0;i<EGL_NUMCONFIGS;i++)
+    {
+        if(m_configs[i].m_config == config)
+        return EGL_TRUE;
+    }
+    return EGL_FALSE;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class RIEGLThread
+{
+public:
+    RIEGLThread(void* currentThreadID);
+    ~RIEGLThread();
+
+    void*           getThreadID() const       { return m_threadID; }
+
+    void            makeCurrent(RIEGLContext* c, RIEGLSurface* s)       { m_context = c; m_surface = s; }
+    RIEGLContext*	getCurrentContext() const   { return m_context; }
+    RIEGLSurface*	getCurrentSurface() const   { return m_surface; }
+
+    void            setError(EGLint error)      { m_error = error; }
+    EGLint          getError() const            { return m_error; }
+
+    void            bindAPI(EGLint api)         { m_boundAPI = api; }
+    EGLint          getBoundAPI() const         { return m_boundAPI; }
+
+private:
+    RIEGLThread(const RIEGLThread&);
+    RIEGLThread operator=(const RIEGLThread&);
+
+    RIEGLContext*		m_context;
+    RIEGLSurface*		m_surface;
+    EGLint              m_error;
+    void*               m_threadID;
+    EGLint              m_boundAPI;
+};
+
+RIEGLThread::RIEGLThread(void* currentThreadID) :
+    m_context(NULL),
+    m_surface(NULL),
+    m_error(EGL_SUCCESS),
+    m_threadID(currentThreadID),
+    m_boundAPI(EGL_NONE)
+{
+}
+
+RIEGLThread::~RIEGLThread()
+{
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class EGL
+{
+public:
+    EGL();
+    ~EGL();
+
+    void	addReference()				{ m_referenceCount++; }
+    int		removeReference()			{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+    void                addDisplay(RIEGLDisplay* display)           { RI_ASSERT(display); m_displays.push_back(display); }  //throws bad alloc
+    void                removeDisplay(RIEGLDisplay* display)        { RI_ASSERT(display); bool res = m_displays.remove(display); RI_ASSERT(res); RI_UNREF(res); }
+    RIEGLDisplay*       getDisplay(const EGLDisplay displayID) const;
+    EGLDisplay          findDisplay(const EGLContext ctx) const;
+
+    void                addCurrentThread(RIEGLThread* thread)       { RI_ASSERT(thread); m_currentThreads.push_back(thread); }  //throws bad alloc
+    void                removeCurrentThread(RIEGLThread* thread)    { RI_ASSERT(thread); bool res = m_currentThreads.remove(thread); RI_ASSERT(res); RI_UNREF(res); }
+    RIEGLThread*        getCurrentThread() const;
+
+    RIEGLThread*        getThread();
+    void                destroyThread();
+
+    bool                isInUse(const void* image) const;
+
+private:
+    EGL(const EGL&);						// Not allowed.
+    const EGL& operator=(const EGL&);		// Not allowed.
+
+    Array<RIEGLThread*>		m_threads;			//threads that have called EGL
+    Array<RIEGLThread*>		m_currentThreads;	//threads that have a bound context
+    Array<RIEGLDisplay*>	m_displays;
+
+    int                     m_referenceCount;
+};
+
+EGL::EGL() :
+    m_threads(),
+    m_currentThreads(),
+    m_displays(),
+    m_referenceCount(0)
+{
+}
+EGL::~EGL()
+{
+    for(int i=0;i<m_displays.size();i++)
+    {
+        RI_DELETE(m_displays[i]);
+    }
+    for(int i=0;i<m_threads.size();i++)
+    {
+        RI_DELETE(m_threads[i]);
+    }
+    //currentThreads contain just pointers to threads we just deleted
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static EGL* g_egl = NULL;	//never use this directly
+static EGL* getEGL()
+{
+    if(!g_egl)
+    {
+        try
+        {
+            g_egl = RI_NEW(EGL, ());				//throws bad_alloc
+            g_egl->addReference();
+        }
+        catch(std::bad_alloc)
+        {
+            g_egl = NULL;
+        }
+    }
+    return g_egl;
+}
+static void releaseEGL()
+{
+    if(g_egl)
+    {
+        if(!g_egl->removeReference())
+        {
+            RI_DELETE(g_egl);
+            g_egl = NULL;
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Given a display ID, return the corresponding object, or NULL
+*			if the ID hasn't been initialized.
+* \param
+* \return
+* \note		if egl has been initialized for this display, the display ID can
+*			be found from egl->m_displays
+*//*-------------------------------------------------------------------*/
+
+RIEGLDisplay* EGL::getDisplay(EGLDisplay displayID) const
+{
+    for(int i=0;i<m_displays.size();i++)
+    {
+        if(displayID == m_displays[i]->getID())
+            return m_displays[i];
+    }
+    return NULL;		//error: the display hasn't been eglInitialized
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	return EGLDisplay for the current context
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLDisplay EGL::findDisplay(EGLContext ctx) const
+{
+    for(int i=0;i<m_displays.size();i++)
+    {
+        if(m_displays[i]->contextExists(ctx))
+            return m_displays[i]->getID();
+    }
+    return EGL_NO_DISPLAY;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	return an EGL thread struct for the thread made current, or
+*            NULL if there's no current context.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RIEGLThread* EGL::getCurrentThread() const
+{
+    void* currentThreadID = OSGetCurrentThreadID();
+    for(int i=0;i<m_currentThreads.size();i++)
+    {
+        if(currentThreadID == m_currentThreads[i]->getThreadID())
+            return m_currentThreads[i];
+    }
+    return NULL;		//thread is not current
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	return an EGL thread struct corresponding to current OS thread.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+RIEGLThread* EGL::getThread()
+{
+    void* currentThreadID = OSGetCurrentThreadID();
+    for(int i=0;i<m_threads.size();i++)
+    {
+        if(currentThreadID == m_threads[i]->getThreadID())
+            return m_threads[i];
+    }
+
+    //EGL doesn't have a struct for the thread yet, add it to EGL's list
+    RIEGLThread* newThread = NULL;
+    try
+    {
+        newThread = RI_NEW(RIEGLThread, (OSGetCurrentThreadID()));	//throws bad_alloc
+        m_threads.push_back(newThread);	//throws bad_alloc
+        return newThread;
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(newThread);
+        return NULL;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	destroy an EGL thread struct
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void EGL::destroyThread()
+{
+    void* currentThreadID = OSGetCurrentThreadID();
+    for(int i=0;i<m_threads.size();i++)
+    {
+        if(currentThreadID == m_threads[i]->getThreadID())
+        {
+            RIEGLThread* thread = m_threads[i];
+            bool res = m_threads.remove(thread);
+            RI_ASSERT(res);
+            RI_UNREF(res);
+            RI_DELETE(thread);
+            break;
+        }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool EGL::isInUse(const void* image) const
+{
+    for(int i=0;i<m_currentThreads.size();i++)
+    {
+        RIEGLSurface* s = m_currentThreads[i]->getCurrentSurface();
+        if(s && s->getDrawable() && s->getDrawable()->isInUse((Image*)image))
+            return true;
+    }
+    return false;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define EGL_GET_DISPLAY(DISPLAY, RETVAL) \
+    OSAcquireMutex(); \
+    EGL* egl = getEGL(); \
+    if(!egl) \
+    { \
+        OSReleaseMutex(); \
+        return RETVAL; \
+    } \
+    RIEGLDisplay* display = egl->getDisplay(DISPLAY); \
+
+#define EGL_GET_EGL(RETVAL) \
+    OSAcquireMutex(); \
+    EGL* egl = getEGL(); \
+    if(!egl) \
+    { \
+        OSReleaseMutex(); \
+        return RETVAL; \
+    } \
+
+#define EGL_IF_ERROR(COND, ERRORCODE, RETVAL) \
+    if(COND) { eglSetError(egl, ERRORCODE); OSReleaseMutex(); return RETVAL; } \
+
+#define EGL_RETURN(ERRORCODE, RETVAL) \
+    { \
+        eglSetError(egl, ERRORCODE); \
+        OSReleaseMutex(); \
+        return RETVAL; \
+    }
+
+// Note: egl error handling model differs from OpenVG. The latest error is stored instead of the oldest one.
+static void eglSetError(EGL* egl, EGLint error)
+{
+    RIEGLThread* thread = egl->getThread();
+    if(thread)
+        thread->setError(error);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns the OpenVG context current to the calling thread.
+* \param
+* \return
+* \note		This function is always called from a mutexed API function
+*//*-------------------------------------------------------------------*/
+
+void* eglvgGetCurrentVGContext(void)
+{
+    EGL* egl = getEGL();
+    if(egl)
+    {
+        RIEGLThread* thread = egl->getCurrentThread();
+        if(thread)
+        {
+            RI_ASSERT(thread->getCurrentContext() && thread->getCurrentSurface());
+            return thread->getCurrentContext()->getVGContext();
+        }
+    }
+    return NULL;	//not initialized or made current
+}
+
+bool  eglvgLockSurface(bool read, bool write)
+{
+    (void)read;
+    (void)write;
+    return true;
+}
+
+bool  eglvgUnlockSurface()
+{
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Check if the image is current in any of the displays
+* \param
+* \return
+* \note		This function is always called from a mutexed API function
+*//*-------------------------------------------------------------------*/
+
+bool eglvgIsInUse(void* image)
+{
+    EGL* egl = getEGL();
+    if(egl)
+    {
+        return egl->isInUse(image);
+    }
+    return false;
+}
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+using namespace OpenVGRI;
+
+
+
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLint EGLAPIENTRY eglGetError()
+{
+    OSAcquireMutex();
+    EGLint ret = EGL_SUCCESS;
+    EGL* egl = getEGL();
+    if(egl)
+    {
+        RIEGLThread* thread = egl->getThread();
+        if(thread)
+            ret = thread->getError();	//initialized, return error code
+    }
+    else ret = EGL_NOT_INITIALIZED;
+    OSReleaseMutex();
+    return ret;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id)
+{
+    return OSGetDisplay(display_id);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(display, EGL_SUCCESS, EGL_TRUE);	//already initialized
+
+    //create the current display
+    //if a context and a surface are bound by the time of eglTerminate, they remain bound until eglMakeCurrent is called
+    RIEGLDisplay* newDisplay = NULL;
+    try
+    {
+        newDisplay = RI_NEW(RIEGLDisplay, (dpy));	//throws bad_alloc
+        egl->addDisplay(newDisplay);	//throws bad_alloc
+        display = newDisplay;
+        RI_ASSERT(display);
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(newDisplay);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE);
+    }
+
+    if(major) *major = 1;
+    if(minor) *minor = 2;
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglTerminate(EGLDisplay dpy)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_SUCCESS, EGL_TRUE);
+    egl->removeDisplay(display);
+    RI_DELETE(display);
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+const char* EGLAPIENTRY eglQueryString(EGLDisplay dpy, EGLint name)
+{
+    EGL_GET_DISPLAY(dpy, NULL);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, NULL);
+
+    static const char apis[] = "OpenVG";
+    static const char extensions[] = "";
+    static const char vendor[] = "Khronos Group";
+    static const char version[] = "1.3";
+
+    const char* ret = NULL;
+    switch(name)
+    {
+    case EGL_CLIENT_APIS:
+        ret = apis;
+        break;
+
+    case EGL_EXTENSIONS:
+        ret = extensions;
+        break;
+
+    case EGL_VENDOR:
+        ret = vendor;
+        break;
+
+    case EGL_VERSION:
+        ret = version;
+        break;
+
+    default:
+        EGL_RETURN(EGL_BAD_PARAMETER, NULL);
+    }
+    EGL_RETURN(EGL_SUCCESS, ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglGetConfigs(EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!num_config, EGL_BAD_PARAMETER, EGL_FALSE);
+    if(!configs)
+    {
+        *num_config = display->getNumConfigs();
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+    }
+    *num_config = RI_INT_MIN(config_size, display->getNumConfigs());
+    for(int i=0;i<*num_config;i++)
+        configs[i] = display->getConfig(i).m_config;
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static bool smaller(EGLint c, EGLint filter)
+{
+    return (filter != EGL_DONT_CARE) && (c < filter);
+}
+
+EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!num_config, EGL_BAD_PARAMETER, EGL_FALSE);
+
+    if(!configs)
+    {
+        *num_config = display->getNumConfigs();
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+    }
+    *num_config = 0;
+    if(!config_size)
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+
+    int bufferSize = 0;
+    int redSize = 0;
+    int greenSize = 0;
+    int blueSize = 0;
+    int luminanceSize = 0;
+    int alphaSize = 0;
+    int alphaMaskSize = 0;
+    int colorBufferType = EGL_RGB_BUFFER;
+    int configID = EGL_DONT_CARE;
+    int sampleBuffers = 0;
+    int samples = 0;
+    if(attrib_list)
+    {
+        for(int i=0;attrib_list[i] != EGL_NONE;i+=2)
+        {
+            switch(attrib_list[i])
+            {
+            case EGL_BUFFER_SIZE:				//depth of the color buffer
+                bufferSize = attrib_list[i+1];
+                break;
+            case EGL_RED_SIZE:					//bits of Red in the color buffer
+                redSize = attrib_list[i+1];
+                break;
+            case EGL_GREEN_SIZE:				//bits of Green in the color buffer
+                greenSize = attrib_list[i+1];
+                break;
+            case EGL_BLUE_SIZE:					//bits of Blue in the color buffer
+                blueSize = attrib_list[i+1];
+                break;
+            case EGL_LUMINANCE_SIZE:			//bits of Luminance in the color buffer
+                luminanceSize = attrib_list[i+1];
+                break;
+            case EGL_ALPHA_SIZE:				//bits of Alpha in the color buffer
+                alphaSize = attrib_list[i+1];
+                break;
+            case EGL_ALPHA_MASK_SIZE:			//bits of Alpha in the alpha mask buffer
+                alphaMaskSize = attrib_list[i+1];
+                if(attrib_list[i+1] > 8)
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+            case EGL_COLOR_BUFFER_TYPE:			//enum color buffer type (EGL_RGB_BUFFER, EGL_LUMINANCE_BUFFER)
+                EGL_IF_ERROR(attrib_list[i+1] != EGL_RGB_BUFFER && attrib_list[i+1] != EGL_LUMINANCE_BUFFER && attrib_list[i+1] != EGL_DONT_CARE, EGL_BAD_ATTRIBUTE, EGL_FALSE);
+                colorBufferType = attrib_list[i+1];
+                break;
+            case EGL_CONFIG_ID:					//unique EGLConfig identifier
+                configID = attrib_list[i+1];
+                break;
+
+            case EGL_SAMPLE_BUFFERS:			//integer number of multisample buffers
+                sampleBuffers = attrib_list[i+1];
+                break;
+            case EGL_SAMPLES:					//integer number of samples per pixel
+                samples = attrib_list[i+1];
+                break;
+
+            case EGL_BIND_TO_TEXTURE_RGB:		//boolean True if bindable to RGB textures. (always EGL_FALSE)
+            case EGL_BIND_TO_TEXTURE_RGBA:		//boolean True if bindable to RGBA textures. (always EGL_FALSE)
+            case EGL_DEPTH_SIZE:				//integer bits of Z in the depth buffer (always 0)
+            case EGL_LEVEL:						//integer frame buffer level (always 0)
+            case EGL_NATIVE_RENDERABLE:			//boolean EGL TRUE if native rendering APIs can render to surface (always EGL_FALSE)
+            case EGL_STENCIL_SIZE:				//integer bits of Stencil in the stencil buffer (always 0)
+                if(attrib_list[i+1])
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+
+            case EGL_CONFIG_CAVEAT:				//enum any caveats for the configuration (always EGL_NONE)
+            case EGL_NATIVE_VISUAL_TYPE:		//integer native visual type of the associated visual (always EGL_NONE)
+                if(attrib_list[i+1] != EGL_NONE)
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+
+            case EGL_MAX_SWAP_INTERVAL:			//integer maximum swap interval (always 1)
+            case EGL_MIN_SWAP_INTERVAL:			//integer minimum swap interval (always 1)
+                if(attrib_list[i+1] != 1)
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+
+            case EGL_RENDERABLE_TYPE:			//bitmask which client rendering APIs are supported. (always EGL_OPENVG_BIT)
+                if(!(attrib_list[i+1] & EGL_OPENVG_BIT))
+                    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);	//not supported
+                break;
+
+            case EGL_SURFACE_TYPE:				//bitmask which types of EGL surfaces are supported. (always EGL_WINDOW_BIT | EGL_PIXMAP_BIT | EGL_PBUFFER_BIT | EGL_VG_COLORSPACE_LINEAR_BIT | EGL_VG_ALPHA_FORMAT_PRE_BIT)
+                break;	//all types are always supported
+
+            case EGL_TRANSPARENT_TYPE:			//enum type of transparency supported (always EGL_NONE)
+            case EGL_NATIVE_VISUAL_ID:			//integer handle of corresponding native visual (always 0)
+            case EGL_MAX_PBUFFER_WIDTH:			//integer maximum width of pbuffer (always INT_MAX)
+            case EGL_MAX_PBUFFER_HEIGHT:		//integer maximum height of pbuffer (always INT_MAX)
+            case EGL_MAX_PBUFFER_PIXELS:		//integer maximum size of pbuffer (always INT_MAX)
+            case EGL_TRANSPARENT_RED_VALUE:		//integer transparent red value (undefined)
+            case EGL_TRANSPARENT_GREEN_VALUE:	//integer transparent green value (undefined)
+            case EGL_TRANSPARENT_BLUE_VALUE:	//integer transparent blue value (undefined)
+                break;	//ignored
+
+            default:
+                EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE);	//unknown attribute
+            }
+        }
+    }
+
+    if(configID && configID != EGL_DONT_CARE)
+    {	//if CONFIG_ID is defined, ignore the rest of the attribs
+        for(int i=0;i<EGL_NUMCONFIGS;i++)
+        {
+            if(display->getConfig(i).m_configID == configID)
+            {
+                *num_config = 1;
+                *configs = display->getConfig(i).m_config;
+            }
+        }
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+    }
+
+    //go through all configs, add passed configs to return list
+    //TODO take alpha mask size into account
+    EGLConfig found[EGL_NUMCONFIGS];
+    int keys[EGL_NUMCONFIGS];
+    int numFound = 0;
+    for(int i=0;i<display->getNumConfigs();i++)
+    {
+        const RIEGLConfig& c = display->getConfig(i);
+
+        int configMaskBits = c.m_maskBits;
+        int colorBits = c.m_desc.redBits + c.m_desc.greenBits + c.m_desc.blueBits;
+        int luminanceBits = c.m_desc.luminanceBits;
+        int configBufferSize;
+        if(colorBits)
+        {
+            RI_ASSERT(!luminanceBits);
+            colorBits += c.m_desc.alphaBits;
+            configBufferSize = colorBits;
+        }
+        else if(luminanceBits)
+        {
+            luminanceBits += c.m_desc.alphaBits;
+            configBufferSize = luminanceBits;
+        }
+        else
+        {	//alpha only surface
+            colorBits = c.m_desc.alphaBits;
+            luminanceBits = c.m_desc.alphaBits;
+            configBufferSize = colorBits;
+        }
+
+        if (smaller(configBufferSize, bufferSize))
+            continue;
+
+        int configSampleBuffers = c.m_samples == 1 ? 0 : 1;
+        if (smaller(configSampleBuffers, sampleBuffers))
+            continue;
+        if (smaller(c.m_samples, samples))
+            continue;
+
+        if (smaller(c.m_desc.redBits, redSize)
+            || smaller(c.m_desc.greenBits, greenSize)
+            || smaller(c.m_desc.blueBits, blueSize)
+            || smaller(c.m_desc.alphaBits, alphaSize) )
+            continue;
+
+        if (smaller(c.m_desc.luminanceBits, luminanceSize))
+            continue;
+
+        if (smaller(configMaskBits, alphaMaskSize))
+            continue;
+
+        if ((colorBufferType == EGL_RGB_BUFFER && !colorBits) ||
+            (colorBufferType == EGL_LUMINANCE_BUFFER && !luminanceBits))
+            continue;
+
+        // \todo Add the alphaMaskSize into the sort order also!
+        int sortKey = c.m_configID;	//sort from smaller to larger
+        int sortBits = 0;
+        if(redSize != 0 && redSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.redBits;
+        if(greenSize != 0 && greenSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.greenBits;
+        if(blueSize != 0 && blueSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.blueBits;
+        if(alphaSize != 0 && alphaSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.alphaBits;
+        if(luminanceSize != 0 && luminanceSize != EGL_DONT_CARE)
+            sortBits += c.m_desc.luminanceBits;
+        RI_ASSERT(c.m_configID <= EGL_NUMCONFIGS);	//if there are more configs, increase the shift value
+        RI_ASSERT(sortBits <= 32);
+        sortKey += (32-sortBits) << 4;	//sort from larger to smaller
+
+        found[numFound] = c.m_config;
+        keys[numFound++] = sortKey;
+    }
+    if(!numFound)
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+
+    //sort return list into increasing order
+    for(int e=0;e<numFound-1;e++)
+    {
+        for(int f=e+1;f<numFound;f++)
+        {
+            if(keys[e] > keys[f])
+            {
+                EGLConfig tmp = found[e];
+                found[e] = found[f];
+                found[f] = tmp;
+                RI_INT_SWAP(keys[e], keys[f]);
+            }
+        }
+    }
+
+    //write configs into return array
+    numFound = RI_INT_MIN(numFound, config_size);
+    for(int i=0;i<numFound;i++)
+    {
+        configs[i] = found[i];
+    }
+    *num_config = numFound;
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_FALSE);
+    const RIEGLConfig& c = display->getConfig(config);
+    switch(attribute)
+    {
+    case EGL_BUFFER_SIZE:
+        *value = RI_INT_MAX(c.m_desc.redBits + c.m_desc.greenBits + c.m_desc.blueBits + c.m_desc.alphaBits, c.m_desc.luminanceBits + c.m_desc.alphaBits);
+        break;
+
+    case EGL_RED_SIZE:
+        *value = c.m_desc.redBits;
+        break;
+
+    case EGL_GREEN_SIZE:
+        *value = c.m_desc.greenBits;
+        break;
+
+    case EGL_BLUE_SIZE:
+        *value = c.m_desc.blueBits;
+        break;
+
+    case EGL_LUMINANCE_SIZE:
+        *value = c.m_desc.luminanceBits;
+        break;
+
+    case EGL_ALPHA_SIZE:
+        *value = c.m_desc.alphaBits;
+        break;
+
+    case EGL_ALPHA_MASK_SIZE:
+        *value = c.m_maskBits;
+        break;
+
+    case EGL_BIND_TO_TEXTURE_RGB:
+    case EGL_BIND_TO_TEXTURE_RGBA:
+        *value = EGL_FALSE;
+        break;
+
+    case EGL_COLOR_BUFFER_TYPE:
+        if(c.m_desc.redBits)
+            *value = EGL_RGB_BUFFER;
+        else
+            *value = EGL_LUMINANCE_BUFFER;
+        break;
+
+    case EGL_CONFIG_CAVEAT:
+        *value = EGL_NONE;
+        break;
+
+    case EGL_CONFIG_ID:
+        *value = c.m_configID;
+        break;
+
+    case EGL_DEPTH_SIZE:
+        *value = 0;
+        break;
+
+    case EGL_LEVEL:
+        *value = 0;
+        break;
+
+    case EGL_MAX_PBUFFER_WIDTH:
+    case EGL_MAX_PBUFFER_HEIGHT:
+        *value = 16384;			//NOTE arbitrary maximum
+        break;
+
+    case EGL_MAX_PBUFFER_PIXELS:
+        *value = 16384*16384;	//NOTE arbitrary maximum
+        break;
+
+    case EGL_MAX_SWAP_INTERVAL:
+    case EGL_MIN_SWAP_INTERVAL:
+        *value = 1;
+        break;
+
+    case EGL_NATIVE_RENDERABLE:
+        *value = EGL_FALSE;
+        break;
+
+    case EGL_NATIVE_VISUAL_ID:
+        *value = 0;
+        break;
+
+    case EGL_NATIVE_VISUAL_TYPE:
+        *value = EGL_NONE;
+        break;
+
+    case EGL_RENDERABLE_TYPE:
+        *value = EGL_OPENVG_BIT;
+        break;
+
+    case EGL_SAMPLE_BUFFERS:
+        *value = c.m_samples > 1 ? 1 : 0;
+        break;
+
+    case EGL_SAMPLES:
+        *value = c.m_samples > 1 ? c.m_samples : 0;
+        break;
+
+    case EGL_STENCIL_SIZE:
+        *value = 0;
+        break;
+
+    case EGL_SURFACE_TYPE:
+        *value = EGL_WINDOW_BIT | EGL_PIXMAP_BIT | EGL_PBUFFER_BIT | EGL_VG_COLORSPACE_LINEAR_BIT | EGL_VG_ALPHA_FORMAT_PRE_BIT;
+        break;
+
+    case EGL_TRANSPARENT_TYPE:
+        *value = EGL_NONE;
+        break;
+
+    case EGL_TRANSPARENT_RED_VALUE:
+    case EGL_TRANSPARENT_GREEN_VALUE:
+    case EGL_TRANSPARENT_BLUE_VALUE:
+        *value = 0;
+        break;
+
+    case EGL_CONFORMANT:
+        *value = EGL_OPENVG_BIT;  //TODO return proper value
+        break;
+
+    default:
+        EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE);
+    }
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list)
+{
+    EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE);
+
+    int renderBuffer = EGL_BACK_BUFFER;
+    int colorSpace = EGL_VG_COLORSPACE_sRGB;
+    int alphaFormat = EGL_VG_ALPHA_FORMAT_NONPRE;
+    if(attrib_list)
+    {
+        for(int i=0;attrib_list[i] != EGL_NONE;i+=2)
+        {
+            switch(attrib_list[i])
+            {
+            case EGL_RENDER_BUFFER:
+                renderBuffer = attrib_list[i+1];
+                break;
+
+            case EGL_VG_COLORSPACE:
+                colorSpace = attrib_list[i+1];
+                break;
+
+            case EGL_VG_ALPHA_FORMAT:
+                alphaFormat = attrib_list[i+1];
+                break;
+
+            default:
+                EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
+            }
+        }
+    }
+    //we ignore the renderBuffer parameter since we can only render to double buffered surfaces
+
+    //TODO If the attributes of win do not correspond to config, then an EGL BAD MATCH error is generated.
+    //TODO If there is already an EGLConfig associated with win (as a result of a previous eglCreateWindowSurface call), then an EGL BAD ALLOC error is generated
+
+    void* wc = NULL;
+    OpenVGRI::Drawable* d = NULL;
+    RIEGLSurface* s = NULL;
+    try
+    {
+        wc = OSCreateWindowContext((EGLNativeWindowType)win);
+        RI_ASSERT(wc);
+        //TODO what should happen if window width or height is zero?
+        int windowWidth = 0, windowHeight = 0;
+        OSGetWindowSize((OSWindowContext*)wc, windowWidth, windowHeight);
+        bool isWindow = OSIsWindow((const OSWindowContext*)wc);
+        if(windowWidth <= 0 || windowHeight <= 0 || !isWindow)
+        {
+            OSDestroyWindowContext((OSWindowContext*)wc);
+            EGL_IF_ERROR(!isWindow, EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
+            EGL_IF_ERROR(windowWidth <= 0 || windowHeight <= 0, EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
+        }
+        Color::Descriptor colorDescriptor = display->getConfig(config).configToDescriptor((colorSpace == EGL_VG_COLORSPACE_LINEAR) ? false : true, (alphaFormat == EGL_VG_ALPHA_FORMAT_PRE) ? true : false);
+        d = RI_NEW(OpenVGRI::Drawable, (colorDescriptor, windowWidth, windowHeight, display->getConfig(config).m_samples, display->getConfig(config).m_maskBits));	//throws bad_alloc
+        RI_ASSERT(d);
+        s = RI_NEW(RIEGLSurface,(wc, config, d, false, renderBuffer));	//throws bad_alloc
+        RI_ASSERT(s);
+        s->addReference();
+        display->addSurface(s);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        OSDestroyWindowContext((OSWindowContext*)wc);
+        RI_DELETE(d);
+        RI_DELETE(s);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+    }
+    EGL_RETURN(EGL_SUCCESS, (EGLSurface)s);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list)
+{
+    EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE);
+
+    int width = 0, height = 0;
+    bool largestPbuffer = false;
+    int colorSpace = EGL_VG_COLORSPACE_sRGB;
+    int alphaFormat = EGL_VG_ALPHA_FORMAT_NONPRE;
+    if(attrib_list)
+    {
+        for(int i=0;attrib_list[i] != EGL_NONE;i+=2)
+        {
+            switch(attrib_list[i])
+            {
+            case EGL_WIDTH:
+                width = attrib_list[i+1];
+                break;
+
+            case EGL_HEIGHT:
+                height = attrib_list[i+1];
+                break;
+
+            case EGL_LARGEST_PBUFFER:
+                largestPbuffer = attrib_list[i+1] ? true : false;
+                break;
+
+            case EGL_VG_COLORSPACE:
+                colorSpace = attrib_list[i+1];
+                break;
+
+            case EGL_VG_ALPHA_FORMAT:
+                alphaFormat = attrib_list[i+1];
+                break;
+
+            case EGL_TEXTURE_FORMAT:	//config doesn't support OpenGL ES
+            case EGL_TEXTURE_TARGET:	//config doesn't support OpenGL ES
+            case EGL_MIPMAP_TEXTURE:	//config doesn't support OpenGL ES
+            default:
+                EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
+            break;
+            }
+        }
+    }
+    EGL_IF_ERROR(width <= 0 || height <= 0, EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);
+
+    OpenVGRI::Drawable* d = NULL;
+    RIEGLSurface* s = NULL;
+    try
+    {
+        d = RI_NEW(OpenVGRI::Drawable, (display->getConfig(config).configToDescriptor((colorSpace == EGL_VG_COLORSPACE_LINEAR) ? false : true, (alphaFormat == EGL_VG_ALPHA_FORMAT_PRE) ? true : false), width, height, display->getConfig(config).m_samples, display->getConfig(config).m_maskBits));	//throws bad_alloc
+        RI_ASSERT(d);
+        s = RI_NEW(RIEGLSurface,(NULL, config, d, largestPbuffer, EGL_BACK_BUFFER));	//throws bad_alloc
+        RI_ASSERT(s);
+        s->addReference();
+        display->addSurface(s);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(d);
+        RI_DELETE(s);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+    }
+    EGL_RETURN(EGL_SUCCESS, (EGLSurface)s);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list)
+{
+    EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE);
+    EGL_IF_ERROR(buftype != EGL_OPENVG_IMAGE, EGL_BAD_PARAMETER, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!buffer, EGL_BAD_PARAMETER, EGL_NO_SURFACE);	//TODO should also check if buffer really is a valid VGImage object (needs VG context for that)
+    Image* image = (Image*)buffer;
+    EGL_IF_ERROR(image->isInUse(), EGL_BAD_ACCESS, EGL_NO_SURFACE);	//buffer is in use by OpenVG
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE);
+    EGL_IF_ERROR(attrib_list && attrib_list[0] != EGL_NONE, EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE);	//there are no valid attribs for OpenVG
+    const Color::Descriptor& bc = ((Image*)buffer)->getDescriptor();
+    const Color::Descriptor& cc = display->getConfig(config).m_desc;
+    EGL_IF_ERROR(bc.redBits != cc.redBits || bc.greenBits != cc.greenBits || bc.blueBits != cc.blueBits ||
+                 bc.alphaBits != cc.alphaBits || bc.luminanceBits != cc.luminanceBits, EGL_BAD_MATCH, EGL_NO_SURFACE);
+
+    //TODO If buffer is already bound to another pbuffer, an EGL BAD ACCESS error is generated.
+
+    OpenVGRI::Drawable* d = NULL;
+    RIEGLSurface* s = NULL;
+    try
+    {
+        d = RI_NEW(OpenVGRI::Drawable, (image, display->getConfig(config).m_maskBits));
+        RI_ASSERT(d);
+        s = RI_NEW(RIEGLSurface,(NULL, config, d, false, EGL_BACK_BUFFER));	//throws bad_alloc
+        RI_ASSERT(s);
+        s->addReference();
+        display->addSurface(s);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(d);
+        RI_DELETE(s);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+    }
+    EGL_RETURN(EGL_SUCCESS, (EGLSurface)s);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list)
+{
+    // Seems that this function has not been implemented correctly in the RI:
+    // cannot assume that EGLNativePixmapType has format, data, etc.
+#if 0
+    EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE);
+    EGL_IF_ERROR(!pixmap || !isValidImageFormat(pixmap->format) || !pixmap->data || pixmap->width <= 0 || pixmap->height <= 0, EGL_BAD_NATIVE_PIXMAP, EGL_NO_SURFACE);
+    RI_UNREF(attrib_list);
+    EGL_IF_ERROR(display->getConfig(config).m_samples != 1, EGL_BAD_MATCH, EGL_NO_SURFACE);
+
+    //TODO If there is already an EGLSurface associated with pixmap (as a result of a previous eglCreatePixmapSurface call), then a EGL BAD ALLOC error is generated.
+
+    Drawable* d = NULL;
+    RIEGLSurface* s = NULL;
+    try
+    {
+        d = RI_NEW(Drawable, (Color::formatToDescriptor((VGImageFormat)pixmap->format), pixmap->width, pixmap->height, pixmap->stride, (RIuint8*)pixmap->data, display->getConfig(config).m_maskBits));	//throws bad_alloc
+        RI_ASSERT(d);
+        s = RI_NEW(RIEGLSurface,(NULL, config, d, false, EGL_BACK_BUFFER));	//throws bad_alloc
+        RI_ASSERT(s);
+        s->addReference();
+        display->addSurface(s);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(d);
+        RI_DELETE(s);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE);
+    }
+    EGL_RETURN(EGL_SUCCESS, (EGLSurface)s);
+#else
+    (void)dpy;
+    (void)config;
+    (void)pixmap;
+    (void)attrib_list;
+    return 0;
+#endif
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglDestroySurface(EGLDisplay dpy, EGLSurface surface)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+
+    display->removeSurface((RIEGLSurface*)surface);
+    if(!((RIEGLSurface*)surface)->removeReference())
+        RI_DELETE((RIEGLSurface*)surface);
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+    RI_UNREF(attribute);
+    RI_UNREF(value);
+    //do nothing
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglQuerySurface(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+    //TODO give an error if value is NULL?
+
+    RIEGLSurface* s = (RIEGLSurface*)surface;
+    switch(attribute)
+    {
+    case EGL_VG_ALPHA_FORMAT:
+        *value = (s->getDrawable()->getDescriptor().isPremultiplied()) ? EGL_VG_ALPHA_FORMAT_PRE : EGL_VG_ALPHA_FORMAT_NONPRE;
+        break;
+
+    case EGL_VG_COLORSPACE:
+        *value = (s->getDrawable()->getDescriptor().isNonlinear()) ? EGL_VG_COLORSPACE_sRGB : EGL_VG_COLORSPACE_LINEAR;
+        break;
+
+    case EGL_CONFIG_ID:
+        *value = display->getConfig(s->getConfig()).m_configID;
+        break;
+
+    case EGL_HEIGHT:
+        *value = s->getDrawable()->getHeight();
+        break;
+
+    case EGL_HORIZONTAL_RESOLUTION:
+        *value = EGL_UNKNOWN;			//TODO Horizontal dot pitch
+        break;
+
+    case EGL_LARGEST_PBUFFER:
+        if(!s->getOSWindowContext())
+            *value = s->isLargestPbuffer() ? EGL_TRUE : EGL_FALSE;
+        break;
+
+    case EGL_MIPMAP_TEXTURE:
+        if(!s->getOSWindowContext())
+            *value = EGL_FALSE;
+        break;
+
+    case EGL_MIPMAP_LEVEL:
+        if(!s->getOSWindowContext())
+            *value = 0;
+        break;
+
+    case EGL_PIXEL_ASPECT_RATIO:
+        *value = EGL_UNKNOWN;			//TODO Display aspect ratio
+        break;
+
+    case EGL_RENDER_BUFFER:
+        *value = s->getRenderBuffer();
+        break;
+
+    case EGL_SWAP_BEHAVIOR:
+        *value = EGL_BUFFER_PRESERVED;
+        break;
+
+    case EGL_TEXTURE_FORMAT:
+        if(!s->getOSWindowContext())
+            *value = EGL_NO_TEXTURE;
+        break;
+
+    case EGL_TEXTURE_TARGET:
+        if(!s->getOSWindowContext())
+            *value = EGL_NO_TEXTURE;
+        break;
+
+    case EGL_VERTICAL_RESOLUTION:
+        *value = EGL_UNKNOWN;			//TODO Vertical dot pitch
+        break;
+
+    case EGL_WIDTH:
+        *value = s->getDrawable()->getWidth();
+        break;
+
+    default:
+        EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE);
+    }
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list)
+{
+    EGL_GET_DISPLAY(dpy, EGL_NO_CONTEXT);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_CONTEXT);
+    EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_CONTEXT);
+    RI_UNREF(attrib_list);
+
+    RIEGLThread* thread = egl->getThread();
+    if(!thread)
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
+
+    //creation of OpenGL ES contexts is not allowed in this implementation
+    if(thread->getBoundAPI() != EGL_OPENVG_API)
+        EGL_RETURN(EGL_BAD_MATCH, EGL_NO_CONTEXT);
+
+    OpenVGRI::VGContext* vgctx = NULL;
+    RIEGLContext* c = NULL;
+    try
+    {
+        vgctx = RI_NEW(OpenVGRI::VGContext, (share_context ? ((RIEGLContext*)share_context)->getVGContext() : NULL));	//throws bad_alloc
+        c = RI_NEW(RIEGLContext, (vgctx, config));	//throws bad_alloc
+        c->addReference();
+        display->addContext(c);	//throws bad_alloc
+    }
+    catch(std::bad_alloc)
+    {
+        RI_DELETE(vgctx);
+        RI_DELETE(c);
+        EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_CONTEXT);
+    }
+
+    EGL_RETURN(EGL_SUCCESS, (EGLContext)c);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglDestroyContext(EGLDisplay dpy, EGLContext ctx)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE);
+
+    RIEGLContext* context = (RIEGLContext*)ctx;
+    display->removeContext(context);
+    if(!context->removeReference() )
+        RI_DELETE(context);
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(ctx != EGL_NO_CONTEXT && !display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE);
+    EGL_IF_ERROR(draw != EGL_NO_SURFACE && !display->surfaceExists(draw), EGL_BAD_SURFACE, EGL_FALSE);
+    EGL_IF_ERROR(read != EGL_NO_SURFACE && !display->surfaceExists(read), EGL_BAD_SURFACE, EGL_FALSE);
+    EGL_IF_ERROR(draw != read, EGL_BAD_MATCH, EGL_FALSE);	//TODO what's the proper error code?
+    EGL_IF_ERROR((draw != EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT) || (draw == EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT), EGL_BAD_MATCH, EGL_FALSE);
+
+    RIEGLSurface* s = NULL;
+    RIEGLContext* c = NULL;
+    if(draw != EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT)
+    {
+        EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+
+        s = (RIEGLSurface*)draw;
+        c = (RIEGLContext*)ctx;
+
+        //If either draw or read are pbuffers created with eglCreatePbufferFromClientBuffer, and the underlying bound client API buffers
+        //are in use by the client API that created them, an EGL BAD ACCESS error is generated.
+        EGL_IF_ERROR(s->getDrawable()->isInUse(), EGL_BAD_ACCESS, EGL_FALSE);
+
+
+        //TODO properly check compatibility of surface and context:
+        //-both have RGB or LUMINANCE configs
+        //-buffer bit depths match
+        //-configs support OpenVG
+        //-both have the same display
+        EGL_IF_ERROR(s->getConfig() != c->getConfig(), EGL_BAD_MATCH, EGL_FALSE);
+        //TODO check if context or surfaces are already bound to another thread
+
+        //If a native window underlying either draw or read is no longer valid, an EGL BAD NATIVE WINDOW error is generated.
+        EGL_IF_ERROR(s->getOSWindowContext() && !OSIsWindow((const OSWindowContext*)s->getOSWindowContext()), EGL_BAD_NATIVE_WINDOW, EGL_FALSE);
+
+        //TODO If the previous context of the calling display has unflushed commands, and the previous surface is no longer valid, an EGL BAD CURRENT SURFACE error is generated. (can this happen?)
+        //TODO If the ancillary buffers for draw and read cannot be allocated, an EGL BAD ALLOC error is generated. (mask buffer?)
+    }
+
+    //check if the thread is current
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread)
+    {	//thread is current, release the old bindinds and remove the thread from the current thread list
+        RIEGLContext* pc = thread->getCurrentContext();
+        RIEGLSurface* ps = thread->getCurrentSurface();
+        if(pc)
+        {
+            vgFlush();
+            pc->getVGContext()->setDefaultDrawable(NULL);
+            if(!pc->removeReference())
+                RI_DELETE(pc);
+        }
+        if(ps)
+        {
+            if(!ps->removeReference())
+                RI_DELETE(ps);
+        }
+
+        egl->removeCurrentThread(thread);
+    }
+
+    if( c && s )
+    {
+        //bind context and surface to the current display
+        RIEGLThread* newThread = egl->getThread();
+        if(!newThread)
+            EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE);
+        newThread->makeCurrent(c, s);
+        c->getVGContext()->setDefaultDrawable(s->getDrawable());
+
+        try
+        {
+            egl->addCurrentThread(newThread);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+            EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE);
+        }
+
+        c->addReference();
+        s->addReference();
+    }
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLContext EGLAPIENTRY eglGetCurrentContext()
+{
+    EGL_GET_EGL(EGL_NO_CONTEXT);
+    EGLContext ret = EGL_NO_CONTEXT;
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread && thread->getBoundAPI() == EGL_OPENVG_API)
+    {
+        ret = thread->getCurrentContext();
+        RI_ASSERT(ret);
+    }
+    EGL_RETURN(EGL_SUCCESS, ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLSurface EGLAPIENTRY eglGetCurrentSurface(EGLint readdraw)
+{
+    EGL_GET_EGL(EGL_NO_SURFACE);
+    EGL_IF_ERROR(readdraw != EGL_READ && readdraw != EGL_DRAW, EGL_BAD_PARAMETER, EGL_NO_SURFACE);
+    EGLContext ret = EGL_NO_SURFACE;
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread && thread->getBoundAPI() == EGL_OPENVG_API)
+    {
+        ret = thread->getCurrentSurface();
+        RI_ASSERT(ret);
+    }
+    EGL_RETURN(EGL_SUCCESS, ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Returns the current display
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLDisplay EGLAPIENTRY eglGetCurrentDisplay(void)
+{
+    EGL_GET_EGL(EGL_NO_DISPLAY);
+
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(!thread || thread->getBoundAPI() != EGL_OPENVG_API)
+        EGL_RETURN(EGL_SUCCESS, EGL_NO_DISPLAY);
+
+    RIEGLContext* ctx = thread->getCurrentContext();
+    RI_ASSERT(ctx);
+    EGLDisplay ret = egl->findDisplay(ctx);
+    EGL_RETURN(EGL_SUCCESS, ret);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglQueryContext(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint* value)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE);
+    EGL_IF_ERROR(attribute != EGL_CONFIG_ID && attribute != EGL_CONTEXT_CLIENT_TYPE, EGL_BAD_ATTRIBUTE, EGL_FALSE);
+    if(attribute == EGL_CONFIG_ID)
+        *value = display->getConfig(((RIEGLContext*)ctx)->getConfig()).m_configID;
+    if(attribute == EGL_CONTEXT_CLIENT_TYPE)
+        *value = EGL_OPENVG_API;
+    // \todo [kalle 05/Jul/05] Handling of EGL_RENDER_BUFFER attribute is missing.
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglBindAPI(EGLenum api)
+{
+    EGL_GET_EGL(EGL_FALSE);
+    EGL_IF_ERROR(api != EGL_OPENVG_API && api != EGL_OPENGL_ES_API, EGL_BAD_PARAMETER, EGL_FALSE);
+    RIEGLThread* thread = egl->getThread();
+    if(thread)
+        thread->bindAPI(api);
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLenum EGLAPIENTRY eglQueryAPI(void)
+{
+    EGL_GET_EGL(EGL_NONE);
+    RIEGLThread* thread = egl->getThread();
+    if(thread)
+        EGL_RETURN(EGL_SUCCESS, thread->getBoundAPI());
+    EGL_RETURN(EGL_SUCCESS, EGL_NONE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglWaitClient()
+{
+    EGL_GET_EGL(EGL_FALSE);
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread && thread->getBoundAPI() == EGL_OPENVG_API)
+        vgFinish();
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Waits for OpenGL ES
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglWaitGL(void)
+{
+    return EGL_TRUE;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note		We don't support native rendering
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglWaitNative(EGLint engine)
+{
+    RI_UNREF(engine);
+    return EGL_TRUE;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface surface)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+
+    RIEGLSurface* s = (RIEGLSurface*)surface;
+
+    RIEGLThread* currentThread = egl->getCurrentThread();
+    EGL_IF_ERROR(!currentThread || currentThread->getCurrentSurface() != s, EGL_BAD_SURFACE, EGL_FALSE);
+    EGL_IF_ERROR(!OSIsWindow((const OSWindowContext*)s->getOSWindowContext()), EGL_BAD_NATIVE_WINDOW, EGL_FALSE);
+
+    vgFlush();
+
+    if(!s->getOSWindowContext())
+    {	//do nothing for other than window surfaces (NOTE: single-buffered window surfaces should return immediately as well)
+        EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+    }
+
+    int windowWidth = 0, windowHeight = 0;
+    OSGetWindowSize((OSWindowContext*)s->getOSWindowContext(), windowWidth, windowHeight);
+
+    if(windowWidth != s->getDrawable()->getWidth() || windowHeight != s->getDrawable()->getHeight())
+    {	//resize the back buffer
+        RIEGLContext* c = currentThread->getCurrentContext();
+        RI_ASSERT(c);
+        try
+        {
+            s->getDrawable()->resize(c->getVGContext(), windowWidth, windowHeight);	//throws bad_alloc
+        }
+        catch(std::bad_alloc)
+        {
+            c->getVGContext()->setDefaultDrawable(NULL);
+            EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE);
+        }
+    }
+
+    OSBlitToWindow((OSWindowContext*)s->getOSWindowContext(), s->getDrawable());
+
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target)
+{
+    // This RI implementation does not make sense.
+#if 0
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE);
+    EGL_IF_ERROR(!target || !isValidImageFormat(target->format) || !target->data || target->width <= 0 || target->height <= 0, EGL_BAD_NATIVE_PIXMAP, EGL_FALSE);
+    RIEGLThread* currentThread = egl->getCurrentThread();
+    RIEGLContext* c = currentThread->getCurrentContext();
+    RI_ASSERT(c);
+    try
+    {
+        Image output(Color::formatToDescriptor((VGImageFormat)target->format), target->width, target->height, target->stride, (RIuint8*)target->data);
+        output.addReference();
+        output.blit(c->getVGContext(), ((RIEGLSurface*)surface)->getDrawable()->getColorBuffer()->getImage(), 0, 0, 0, 0, target->width, target->height);	//throws bad_alloc
+        output.removeReference();
+    }
+    catch(std::bad_alloc)
+    {
+    }
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+#else
+    (void)dpy;
+    (void)surface;
+    (void)target;
+    return EGL_FALSE;
+#endif
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note		We support only swap interval one
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglSwapInterval(EGLDisplay dpy, EGLint interval)
+{
+    EGL_GET_DISPLAY(dpy, EGL_FALSE);
+    EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE);
+    RI_UNREF(interval);
+    EGL_RETURN(EGL_SUCCESS, EGL_TRUE);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+typedef void RI_Proc();
+
+__eglMustCastToProperFunctionPointerType EGLAPIENTRY eglGetProcAddress(const char *procname)
+{
+    if(!procname)
+        return NULL;
+    return NULL;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+EGLBoolean EGLAPIENTRY eglReleaseThread(void)
+{
+    EGL_GET_EGL(EGL_FALSE);
+
+    //check if the thread is current
+    RIEGLThread* thread = egl->getCurrentThread();
+    if(thread)
+    {	//thread is current, release the old bindings and remove the thread from the current thread list
+        RIEGLContext* pc = thread->getCurrentContext();
+        RIEGLSurface* ps = thread->getCurrentSurface();
+        if(pc)
+        {
+            vgFlush();
+            pc->getVGContext()->setDefaultDrawable(NULL);
+            if(!pc->removeReference())
+                RI_DELETE(pc);
+        }
+        if(ps)
+        {
+            if(!ps->removeReference())
+                RI_DELETE(ps);
+        }
+
+        egl->removeCurrentThread(thread);
+    }
+
+    //destroy EGL's thread struct
+    egl->destroyThread();
+
+    //destroy the EGL instance
+    releaseEGL();
+
+    OSReleaseMutex();
+    OSDeinitMutex();
+
+    return EGL_SUCCESS;
+}
+
+#undef EGL_NUMCONFIGS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riPath.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2779 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief   Implementation of Path functions.
+ * \note    
+ *//*-------------------------------------------------------------------*/
+
+#include "riPath.h"
+
+//==============================================================================================
+
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+RIfloat inputFloat(VGfloat f);  //defined in riApi.cpp
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Form a reliable normalized average of the two unit input vectors.
+*           The average always lies to the given direction from the first
+*           vector.
+* \param    u0, u1 Unit input vectors.
+* \param    cw True if the average should be clockwise from u0, false if
+*              counterclockwise.
+* \return   Average of the two input vectors.
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static const Vector2 unitAverage(const Vector2& u0, const Vector2& u1, bool cw)
+{
+    Vector2 u = 0.5f * (u0 + u1);
+    Vector2 n0 = perpendicularCCW(u0);
+
+    if( dot(u, u) > 0.25f )
+    {   //the average is long enough and thus reliable
+        if( dot(n0, u1) < 0.0f )
+            u = -u; //choose the larger angle
+    }
+    else
+    {   // the average is too short, use the average of the normals to the vectors instead
+        Vector2 n1 = perpendicularCW(u1);
+        u = 0.5f * (n0 + n1);
+    }
+    if( cw )
+        u = -u;
+
+    return normalize(u);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Form a reliable normalized average of the two unit input vectors.
+*           The average lies on the side where the angle between the input
+*           vectors is less than 180 degrees.
+* \param    u0, u1 Unit input vectors.
+* \return   Average of the two input vectors.
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static const Vector2 unitAverage(const Vector2& u0, const Vector2& u1)
+{
+    Vector2 u = 0.5f * (u0 + u1);
+
+    if( dot(u, u) < 0.25f )
+    {   // the average is unreliable, use the average of the normals to the vectors instead
+        Vector2 n0 = perpendicularCCW(u0);
+        Vector2 n1 = perpendicularCW(u1);
+        u = 0.5f * (n0 + n1);
+        if( dot(n1, u0) < 0.0f )
+            u = -u;
+    }
+
+    return normalize(u);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Interpolate the given unit tangent vectors to the given
+*           direction on a unit circle.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static const Vector2 circularLerp(const Vector2& t0, const Vector2& t1, RIfloat ratio, bool cw)
+{
+    Vector2 u0 = t0, u1 = t1;
+    RIfloat l0 = 0.0f, l1 = 1.0f;
+    for(int i=0;i<18;i++)
+    {
+        Vector2 n = unitAverage(u0, u1, cw);
+        RIfloat l = 0.5f * (l0 + l1);
+        if( ratio < l )
+        {
+            u1 = n;
+            l1 = l;
+        }
+        else
+        {
+            u0 = n;
+            l0 = l;
+        }
+    }
+    return u0;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Interpolate the given unit tangent vectors on a unit circle.
+*           Smaller angle between the vectors is used.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static const Vector2 circularLerp(const Vector2& t0, const Vector2& t1, RIfloat ratio)
+{
+    Vector2 u0 = t0, u1 = t1;
+    RIfloat l0 = 0.0f, l1 = 1.0f;
+    for(int i=0;i<18;i++)
+    {
+        Vector2 n = unitAverage(u0, u1);
+        RIfloat l = 0.5f * (l0 + l1);
+        if( ratio < l )
+        {
+            u1 = n;
+            l1 = l;
+        }
+        else
+        {
+            u0 = n;
+            l0 = l;
+        }
+    }
+    return u0;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Path constructor.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+Path::Path(VGint format, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int segmentCapacityHint, int coordCapacityHint, VGbitfield caps) :
+    m_format(format),
+    m_datatype(datatype),
+    m_scale(scale),
+    m_bias(bias),
+    m_capabilities(caps),
+    m_referenceCount(0),
+    m_segments(),
+    m_data(),
+    m_vertices(),
+    m_segmentToVertex(),
+    m_userMinx(0.0f),
+    m_userMiny(0.0f),
+    m_userMaxx(0.0f),
+    m_userMaxy(0.0f)
+{
+    RI_ASSERT(format == VG_PATH_FORMAT_STANDARD);
+    RI_ASSERT(datatype >= VG_PATH_DATATYPE_S_8 && datatype <= VG_PATH_DATATYPE_F);
+    if(segmentCapacityHint > 0)
+        m_segments.reserve(RI_INT_MIN(segmentCapacityHint, 65536));
+    if(coordCapacityHint > 0)
+        m_data.reserve(RI_INT_MIN(coordCapacityHint, 65536) * getBytesPerCoordinate(datatype));
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Path destructor.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+Path::~Path()
+{
+    RI_ASSERT(m_referenceCount == 0);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Reads a coordinate and applies scale and bias.
+* \param    
+* \return   
+*//*-------------------------------------------------------------------*/
+
+RIfloat Path::getCoordinate(int i) const
+{
+    RI_ASSERT(i >= 0 && i < m_data.size() / getBytesPerCoordinate(m_datatype));
+    RI_ASSERT(m_scale != 0.0f);
+
+    const RIuint8* ptr = &m_data[0];
+    switch(m_datatype)
+    {
+    case VG_PATH_DATATYPE_S_8:
+        return (RIfloat)(((const RIint8*)ptr)[i]) * m_scale + m_bias;
+
+    case VG_PATH_DATATYPE_S_16:
+        return (RIfloat)(((const RIint16*)ptr)[i]) * m_scale + m_bias;
+
+    case VG_PATH_DATATYPE_S_32:
+        return (RIfloat)(((const RIint32*)ptr)[i]) * m_scale + m_bias;
+
+    default:
+        RI_ASSERT(m_datatype == VG_PATH_DATATYPE_F);
+        return (RIfloat)(((const RIfloat32*)ptr)[i]) * m_scale + m_bias;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Writes a coordinate, subtracting bias and dividing out scale.
+* \param    
+* \return   
+* \note     If the coordinates do not fit into path datatype range, they
+*           will overflow silently.
+*//*-------------------------------------------------------------------*/
+
+void Path::setCoordinate(Array<RIuint8>& data, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int i, RIfloat c)
+{
+    RI_ASSERT(i >= 0 && i < data.size()/getBytesPerCoordinate(datatype));
+    RI_ASSERT(!RI_ISNAN(scale));    
+    RI_ASSERT(!RI_ISNAN(bias));
+    RI_ASSERT(scale != 0.0f);
+
+    c = inputFloat(c); // Revalidate: Can happen when a coordinate has been transformed.
+    c -= bias;
+    c /= scale;
+
+    RI_ASSERT(!RI_ISNAN(c));
+
+    RIuint8* ptr = &data[0];
+    switch(datatype)
+    {
+    case VG_PATH_DATATYPE_S_8:
+        ((RIint8*)ptr)[i] = (RIint8)floor(c + 0.5f);    //add 0.5 for correct rounding
+        break;
+
+    case VG_PATH_DATATYPE_S_16:
+        ((RIint16*)ptr)[i] = (RIint16)floor(c + 0.5f);  //add 0.5 for correct rounding
+        break;
+
+    case VG_PATH_DATATYPE_S_32:
+        ((RIint32*)ptr)[i] = (RIint32)floor(c + 0.5f);  //add 0.5 for correct rounding
+        break;
+
+    default:
+        RI_ASSERT(datatype == VG_PATH_DATATYPE_F);
+        ((RIfloat32*)ptr)[i] = (RIfloat32)c;
+        break;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Given a datatype, returns the number of bytes per coordinate.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+int Path::getBytesPerCoordinate(VGPathDatatype datatype)
+{
+    if(datatype == VG_PATH_DATATYPE_S_8)
+        return 1;
+    if(datatype == VG_PATH_DATATYPE_S_16)
+        return 2;
+    RI_ASSERT(datatype == VG_PATH_DATATYPE_S_32 || datatype == VG_PATH_DATATYPE_F);
+    return 4;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Given a path segment type, returns the number of coordinates
+*           it uses.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+int Path::segmentToNumCoordinates(VGPathSegment segment)
+{
+    RI_ASSERT(((int)segment >> 1) >= 0 && ((int)segment >> 1) <= 12);
+    static const int coords[13] = {0,2,2,1,1,4,6,2,4,5,5,5,5};
+    return coords[(int)segment >> 1];
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Computes the number of coordinates a segment sequence uses.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+int Path::countNumCoordinates(const RIuint8* segments, int numSegments)
+{
+    RI_ASSERT(segments);
+    RI_ASSERT(numSegments >= 0);
+
+    int coordinates = 0;
+    for(int i=0;i<numSegments;i++)
+        coordinates += segmentToNumCoordinates(getPathSegment(segments[i]));
+    return coordinates;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Clears path segments and data, and resets capabilities.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::clear(VGbitfield capabilities)
+{
+    m_segments.clear();
+    m_data.clear();
+    m_capabilities = capabilities;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Appends user segments and data.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::appendData(const RIuint8* segments, int numSegments, const RIuint8* data)
+{
+    RI_ASSERT(numSegments > 0);
+    RI_ASSERT(segments && data);
+    RI_ASSERT(m_referenceCount > 0);
+
+    //allocate new arrays
+    int oldSegmentsSize = m_segments.size();
+    int newSegmentsSize = oldSegmentsSize + numSegments;
+    Array<RIuint8> newSegments;
+    newSegments.resize(newSegmentsSize);    //throws bad_alloc
+
+    int newCoords = countNumCoordinates(segments, numSegments);
+    int bytesPerCoordinate = getBytesPerCoordinate(m_datatype);
+    int newDataSize = m_data.size() + newCoords * bytesPerCoordinate;
+    Array<RIuint8> newData;
+    newData.resize(newDataSize);    //throws bad_alloc
+    //if we get here, the memory allocations have succeeded
+
+    //copy old segments and append new ones
+    if(m_segments.size())
+        ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+    ri_memcpy(&newSegments[0] + m_segments.size(), segments, numSegments);
+
+    //copy old data and append new ones
+    if(newData.size())
+    {
+        if(m_data.size())
+            ri_memcpy(&newData[0], &m_data[0], m_data.size());
+        if(m_datatype == VG_PATH_DATATYPE_F)
+        {
+            RIfloat32* d = (RIfloat32*)(&newData[0] + m_data.size());
+            const RIfloat32* s = (const RIfloat32*)data;
+            for(int i=0;i<newCoords;i++)
+                *d++ = (RIfloat32)inputFloat(*s++);
+        }
+        else
+        {
+            ri_memcpy(&newData[0] + m_data.size(), data, newCoords * bytesPerCoordinate);
+        }
+    }
+
+    RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype));
+
+    //replace old arrays
+    m_segments.swap(newSegments);
+    m_data.swap(newData);
+
+    int c = 0;
+    for(int i=0;i<m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+        c += coords;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Appends a path.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::append(const Path* srcPath)
+{
+    RI_ASSERT(srcPath);
+    RI_ASSERT(m_referenceCount > 0 && srcPath->m_referenceCount > 0);
+
+    if(srcPath->m_segments.size())
+    {
+        //allocate new arrays
+        int newSegmentsSize = m_segments.size() + srcPath->m_segments.size();
+        Array<RIuint8> newSegments;
+        newSegments.resize(newSegmentsSize);    //throws bad_alloc
+
+        int newDataSize = m_data.size() + srcPath->getNumCoordinates() * getBytesPerCoordinate(m_datatype);
+        Array<RIuint8> newData;
+        newData.resize(newDataSize);    //throws bad_alloc
+        //if we get here, the memory allocations have succeeded
+
+        //copy old segments and append new ones
+        if(m_segments.size())
+            ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+        if(srcPath->m_segments.size())
+            ri_memcpy(&newSegments[0] + m_segments.size(), &srcPath->m_segments[0], srcPath->m_segments.size());
+
+        //copy old data and append new ones
+        if(m_data.size())
+            ri_memcpy(&newData[0], &m_data[0], m_data.size());
+        for(int i=0;i<srcPath->getNumCoordinates();i++)
+            setCoordinate(newData, m_datatype, m_scale, m_bias, i + getNumCoordinates(), srcPath->getCoordinate(i));
+
+        RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype));
+
+        //replace old arrays
+        m_segments.swap(newSegments);
+        m_data.swap(newData);
+    }
+}
+
+int Path::coordsSizeInBytes( int startIndex, int numSegments )
+    {
+    RI_ASSERT(numSegments > 0);
+    RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size());
+    RI_ASSERT(m_referenceCount > 0);
+
+    int numCoords = countNumCoordinates(&m_segments[startIndex], numSegments);
+    if(!numCoords)
+        return 0;
+    int bytesPerCoordinate = getBytesPerCoordinate(m_datatype);
+    return (numCoords * bytesPerCoordinate);
+    }
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Modifies existing coordinate data.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::modifyCoords(int startIndex, int numSegments, const RIuint8* data)
+{
+    RI_ASSERT(numSegments > 0);
+    RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size());
+    RI_ASSERT(data);
+    RI_ASSERT(m_referenceCount > 0);
+
+    int startCoord = countNumCoordinates(&m_segments[0], startIndex);
+    int numCoords = countNumCoordinates(&m_segments[startIndex], numSegments);
+    if(!numCoords)
+        return;
+    int bytesPerCoordinate = getBytesPerCoordinate(m_datatype);
+    RIuint8* dst = &m_data[startCoord * bytesPerCoordinate];
+    if(m_datatype == VG_PATH_DATATYPE_F)
+    {
+        RIfloat32* d = (RIfloat32*)dst;
+        const RIfloat32* s = (const RIfloat32*)data;
+        for(int i=0;i<numCoords;i++)
+            *d++ = (RIfloat32)inputFloat(*s++);
+    }
+    else
+    {
+        ri_memcpy(dst, data, numCoords*bytesPerCoordinate);
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Appends a transformed copy of the source path.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::transform(const Path* srcPath, const Matrix3x3& matrix)
+{
+    RI_ASSERT(srcPath);
+    RI_ASSERT(m_referenceCount > 0 && srcPath->m_referenceCount > 0);
+    RI_ASSERT(matrix.isAffine());
+
+    if(!srcPath->m_segments.size())
+        return;
+
+    //count the number of resulting coordinates
+    int numSrcCoords = 0;
+    int numDstCoords = 0;
+    for(int i=0;i<srcPath->m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(srcPath->m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+        numSrcCoords += coords;
+        if(segment == VG_HLINE_TO || segment == VG_VLINE_TO)
+            coords = 2; //convert hline and vline to lines
+        numDstCoords += coords;
+    }
+
+    //allocate new arrays
+    Array<RIuint8> newSegments;
+    newSegments.resize(m_segments.size() + srcPath->m_segments.size()); //throws bad_alloc
+    Array<RIuint8> newData;
+    newData.resize(m_data.size() + numDstCoords * getBytesPerCoordinate(m_datatype));   //throws bad_alloc
+    //if we get here, the memory allocations have succeeded
+
+    //copy old segments
+    if(m_segments.size())
+        ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+
+    //copy old data
+    if(m_data.size())
+        ri_memcpy(&newData[0], &m_data[0], m_data.size());
+
+    int srcCoord = 0;
+    int dstCoord = getNumCoordinates();
+    Vector2 s(0,0);     //the beginning of the current subpath
+    Vector2 o(0,0);     //the last point of the previous segment
+    for(int i=0;i<srcPath->m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(srcPath->m_segments[i]);
+        VGPathAbsRel absRel = getPathAbsRel(srcPath->m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+
+        switch(segment)
+        {
+        case VG_CLOSE_PATH:
+        {
+            RI_ASSERT(coords == 0);
+            o = s;
+            break;
+        }
+
+        case VG_MOVE_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 tc;
+
+            if (absRel == VG_ABSOLUTE)
+                tc = affineTransform(matrix, c);
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+            
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            s = c;
+            o = c;
+            break;
+        }
+
+        case VG_LINE_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 tc;
+
+            if (absRel == VG_ABSOLUTE)
+                tc = affineTransform(matrix, c);
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            o = c;
+            break;
+        }
+
+        case VG_HLINE_TO:
+        {
+            RI_ASSERT(coords == 1);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), 0);
+            Vector2 tc;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                c.y = o.y;
+                tc = affineTransform(matrix, c);
+            }
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            o = c;
+            segment = VG_LINE_TO;
+            break;
+        }
+
+        case VG_VLINE_TO:
+        {
+            RI_ASSERT(coords == 1);
+            Vector2 c(0, srcPath->getCoordinate(srcCoord+0));
+            Vector2 tc;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                c.x = o.x;
+                tc = affineTransform(matrix, c);
+            }
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            o = c;
+            segment = VG_LINE_TO;
+            break;
+        }
+
+        case VG_QUAD_TO:
+        {
+            RI_ASSERT(coords == 4);
+            Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            Vector2 tc0, tc1;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                tc0 = affineTransform(matrix, c0);
+                tc1 = affineTransform(matrix, c1);
+            }
+            else
+            {
+                tc0 = affineTangentTransform(matrix, c0);
+                tc1 = affineTangentTransform(matrix, c1);
+                c1 += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.y);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y);
+            o = c1;
+            break;
+        }
+
+        case VG_CUBIC_TO:
+        {
+            RI_ASSERT(coords == 6);
+            Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            Vector2 c2(srcPath->getCoordinate(srcCoord+4), srcPath->getCoordinate(srcCoord+5));
+            Vector2 tc0, tc1, tc2;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                tc0 = affineTransform(matrix, c0);
+                tc1 = affineTransform(matrix, c1);
+                tc2 = affineTransform(matrix, c2);
+            }
+            else
+            {
+                tc0 = affineTangentTransform(matrix, c0);
+                tc1 = affineTangentTransform(matrix, c1);
+                tc2 = affineTangentTransform(matrix, c2);
+                c2 += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.y);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.y);
+            o = c2;
+            break;
+        }
+
+        case VG_SQUAD_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 tc1;
+
+            if (absRel == VG_ABSOLUTE)
+                tc1 = affineTransform(matrix, c1);
+            else
+            {
+                tc1 = affineTangentTransform(matrix, c1);
+                c1 += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y);
+            o = c1;
+            break;
+        }
+
+        case VG_SCUBIC_TO:
+        {
+            RI_ASSERT(coords == 4);
+            Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c2(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            Vector2 tc1, tc2;
+
+            if (absRel == VG_ABSOLUTE)
+            {
+                tc1 = affineTransform(matrix, c1);
+                tc2 = affineTransform(matrix, c2);
+            }
+            else
+            {
+                tc1 = affineTangentTransform(matrix, c1);
+                tc2 = affineTangentTransform(matrix, c2);
+                c2 += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.y);
+            o = c2;
+            break;
+        }
+
+        default:
+        {
+            RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO ||
+                      segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO);
+            RI_ASSERT(coords == 5);
+            RIfloat rh = srcPath->getCoordinate(srcCoord+0);
+            RIfloat rv = srcPath->getCoordinate(srcCoord+1);
+            RIfloat rot = srcPath->getCoordinate(srcCoord+2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+3), srcPath->getCoordinate(srcCoord+4));
+
+            rot = RI_DEG_TO_RAD(rot);
+            Matrix3x3 u((RIfloat)cos(rot)*rh, -(RIfloat)sin(rot)*rv,  0,
+                        (RIfloat)sin(rot)*rh,  (RIfloat)cos(rot)*rv,  0,
+                        0,                   0,                   1);
+            u = matrix * u;
+            u[2].set(0,0,1);        //force affinity
+            //u maps from the unit circle to transformed ellipse
+
+            //compute new rh, rv and rot
+            Vector2 p(u[0][0], u[1][0]);
+            Vector2 q(u[1][1], -u[0][1]);
+            bool swapped = false;
+            if(dot(p,p) < dot(q,q))
+            {
+                RI_SWAP(p.x,q.x);
+                RI_SWAP(p.y,q.y);
+                swapped = true;
+            }
+            Vector2 h = (p+q) * 0.5f;
+            Vector2 hp = (p-q) * 0.5f;
+            RIfloat hlen = h.length();
+            RIfloat hplen = hp.length();
+            rh = hlen + hplen;
+            rv = hlen - hplen;
+
+            if (RI_ISNAN(rh)) rh = 0.0f;
+            if (RI_ISNAN(rv)) rv = 0.0f;
+
+            h = hplen * h + hlen * hp;
+            hlen = dot(h,h);
+            if(hlen == 0.0f)
+                rot = 0.0f;
+            else
+            {
+                h.normalize();
+                rot = (RIfloat)acos(h.x);
+                if(h.y < 0.0f)
+                    rot = 2.0f*RI_PI - rot;
+                if (RI_ISNAN(rot))
+                    rot = 0.0f;
+            }
+            if(swapped)
+                rot += RI_PI*0.5f;
+
+            Vector2 tc;
+            if (absRel == VG_ABSOLUTE)
+                tc = affineTransform(matrix, c);
+            else
+            {
+                tc = affineTangentTransform(matrix, c);
+                c += o;
+            }
+
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, rh);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, rv);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, RI_RAD_TO_DEG(rot));
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x);
+            setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y);
+            o = c;
+
+            //flip winding if the determinant is negative
+            if (matrix.det() < 0)
+            {
+                switch (segment)
+                {
+                case VG_SCCWARC_TO: segment = VG_SCWARC_TO;     break;
+                case VG_SCWARC_TO:  segment = VG_SCCWARC_TO;    break;
+                case VG_LCCWARC_TO: segment = VG_LCWARC_TO;     break;
+                case VG_LCWARC_TO:  segment = VG_LCCWARC_TO;    break;
+                default:                                        break;
+                }
+            }
+            break;
+        }
+        }
+
+        newSegments[m_segments.size() + i] = (RIuint8)(segment | absRel);
+        srcCoord += coords;
+    }
+    RI_ASSERT(srcCoord == numSrcCoords);
+    RI_ASSERT(dstCoord == getNumCoordinates() + numDstCoords);
+
+    RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype));
+
+    //replace old arrays
+    m_segments.swap(newSegments);
+    m_data.swap(newData);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Normalizes a path for interpolation.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::normalizeForInterpolation(const Path* srcPath)
+{
+    RI_ASSERT(srcPath);
+    RI_ASSERT(srcPath != this);
+    RI_ASSERT(srcPath->m_referenceCount > 0);
+
+    //count the number of resulting coordinates
+    int numSrcCoords = 0;
+    int numDstCoords = 0;
+    for(int i=0;i<srcPath->m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(srcPath->m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+        numSrcCoords += coords;
+        switch(segment)
+        {
+        case VG_CLOSE_PATH:
+        case VG_MOVE_TO:
+        case VG_LINE_TO:
+            break;
+
+        case VG_HLINE_TO:
+        case VG_VLINE_TO:
+            coords = 2;
+            break;
+
+        case VG_QUAD_TO:
+        case VG_CUBIC_TO:
+        case VG_SQUAD_TO:
+        case VG_SCUBIC_TO:
+            coords = 6;
+            break;
+
+        default:
+            RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO ||
+                      segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO);
+            break;
+        }
+        numDstCoords += coords;
+    }
+
+    m_segments.resize(srcPath->m_segments.size());  //throws bad_alloc
+    m_data.resize(numDstCoords * getBytesPerCoordinate(VG_PATH_DATATYPE_F));    //throws bad_alloc
+
+    int srcCoord = 0;
+    int dstCoord = 0;
+    Vector2 s(0,0);     //the beginning of the current subpath
+    Vector2 o(0,0);     //the last point of the previous segment
+
+    // the last internal control point of the previous segment, if the
+    //segment was a (regular or smooth) quadratic or cubic
+    //Bezier, or else the last point of the previous segment
+    Vector2 p(0,0);     
+    for(int i=0;i<srcPath->m_segments.size();i++)
+    {
+        VGPathSegment segment = getPathSegment(srcPath->m_segments[i]);
+        VGPathAbsRel absRel = getPathAbsRel(srcPath->m_segments[i]);
+        int coords = segmentToNumCoordinates(segment);
+
+        switch(segment)
+        {
+        case VG_CLOSE_PATH:
+        {
+            RI_ASSERT(coords == 0);
+            p = s;
+            o = s;
+            break;
+        }
+
+        case VG_MOVE_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            if(absRel == VG_RELATIVE)
+                c += o;
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            s = c;
+            p = c;
+            o = c;
+            break;
+        }
+
+        case VG_LINE_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            if(absRel == VG_RELATIVE)
+                c += o;
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            p = c;
+            o = c;
+            break;
+        }
+
+        case VG_HLINE_TO:
+        {
+            RI_ASSERT(coords == 1);
+            Vector2 c(srcPath->getCoordinate(srcCoord+0), o.y);
+            if(absRel == VG_RELATIVE)
+                c.x += o.x;
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            p = c;
+            o = c;
+            segment = VG_LINE_TO;
+            break;
+        }
+
+        case VG_VLINE_TO:
+        {
+            RI_ASSERT(coords == 1);
+            Vector2 c(o.x, srcPath->getCoordinate(srcCoord+0));
+            if(absRel == VG_RELATIVE)
+                c.y += o.y;
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            p = c;
+            o = c;
+            segment = VG_LINE_TO;
+            break;
+        }
+
+        case VG_QUAD_TO:
+        {
+            RI_ASSERT(coords == 4);
+            Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            if(absRel == VG_RELATIVE)
+            {
+                c0 += o;
+                c1 += o;
+            }
+            Vector2 d0 = (1.0f/3.0f) * (o + 2.0f * c0);
+            Vector2 d1 = (1.0f/3.0f) * (c1 + 2.0f * c0);
+            setCoordinate(dstCoord++, d0.x);
+            setCoordinate(dstCoord++, d0.y);
+            setCoordinate(dstCoord++, d1.x);
+            setCoordinate(dstCoord++, d1.y);
+            setCoordinate(dstCoord++, c1.x);
+            setCoordinate(dstCoord++, c1.y);
+            p = c0;
+            o = c1;
+            segment = VG_CUBIC_TO;
+            break;
+        }
+
+        case VG_CUBIC_TO:
+        {
+            RI_ASSERT(coords == 6);
+            Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            Vector2 c2(srcPath->getCoordinate(srcCoord+4), srcPath->getCoordinate(srcCoord+5));
+            if(absRel == VG_RELATIVE)
+            {
+                c0 += o;
+                c1 += o;
+                c2 += o;
+            }
+            setCoordinate(dstCoord++, c0.x);
+            setCoordinate(dstCoord++, c0.y);
+            setCoordinate(dstCoord++, c1.x);
+            setCoordinate(dstCoord++, c1.y);
+            setCoordinate(dstCoord++, c2.x);
+            setCoordinate(dstCoord++, c2.y);
+            p = c1;
+            o = c2;
+            break;
+        }
+
+        case VG_SQUAD_TO:
+        {
+            RI_ASSERT(coords == 2);
+            Vector2 c0 = 2.0f * o - p;
+            Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            if(absRel == VG_RELATIVE)
+                c1 += o;
+            Vector2 d0 = (1.0f/3.0f) * (o + 2.0f * c0);
+            Vector2 d1 = (1.0f/3.0f) * (c1 + 2.0f * c0);
+            setCoordinate(dstCoord++, d0.x);
+            setCoordinate(dstCoord++, d0.y);
+            setCoordinate(dstCoord++, d1.x);
+            setCoordinate(dstCoord++, d1.y);
+            setCoordinate(dstCoord++, c1.x);
+            setCoordinate(dstCoord++, c1.y);
+            p = c0;
+            o = c1;
+            segment = VG_CUBIC_TO;
+            break;
+        }
+
+        case VG_SCUBIC_TO:
+        {
+            RI_ASSERT(coords == 4);
+            Vector2 c0 = 2.0f * o - p;
+            Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1));
+            Vector2 c2(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3));
+            if(absRel == VG_RELATIVE)
+            {
+                c1 += o;
+                c2 += o;
+            }
+            setCoordinate(dstCoord++, c0.x);
+            setCoordinate(dstCoord++, c0.y);
+            setCoordinate(dstCoord++, c1.x);
+            setCoordinate(dstCoord++, c1.y);
+            setCoordinate(dstCoord++, c2.x);
+            setCoordinate(dstCoord++, c2.y);
+            p = c1;
+            o = c2;
+            segment = VG_CUBIC_TO;
+            break;
+        }
+
+        default:
+        {
+            RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO ||
+                      segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO);
+            RI_ASSERT(coords == 5);
+            RIfloat rh = srcPath->getCoordinate(srcCoord+0);
+            RIfloat rv = srcPath->getCoordinate(srcCoord+1);
+            RIfloat rot = srcPath->getCoordinate(srcCoord+2);
+            Vector2 c(srcPath->getCoordinate(srcCoord+3), srcPath->getCoordinate(srcCoord+4));
+            if(absRel == VG_RELATIVE)
+                c += o;
+            setCoordinate(dstCoord++, rh);
+            setCoordinate(dstCoord++, rv);
+            setCoordinate(dstCoord++, rot);
+            setCoordinate(dstCoord++, c.x);
+            setCoordinate(dstCoord++, c.y);
+            p = c;
+            o = c;
+            break;
+        }
+        }
+
+        m_segments[i] = (RIuint8)(segment | VG_ABSOLUTE);
+        srcCoord += coords;
+    }
+    RI_ASSERT(srcCoord == numSrcCoords);
+    RI_ASSERT(dstCoord == numDstCoords);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Appends a linearly interpolated copy of the two source paths.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+bool Path::interpolate(const Path* startPath, const Path* endPath, RIfloat amount)
+{
+    RI_ASSERT(startPath && endPath);
+    RI_ASSERT(m_referenceCount > 0 && startPath->m_referenceCount > 0 && endPath->m_referenceCount > 0);
+
+    if(!startPath->m_segments.size() || startPath->m_segments.size() != endPath->m_segments.size())
+        return false;   //start and end paths are incompatible or zero length
+
+    Path start(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F, 1.0f, 0.0f, 0, 0, 0);
+    start.normalizeForInterpolation(startPath); //throws bad_alloc
+
+    Path end(VG_PATH_FORMAT_STANDARD, VG_PATH_DATATYPE_F, 1.0f, 0.0f, 0, 0, 0);
+    end.normalizeForInterpolation(endPath); //throws bad_alloc
+
+    //check that start and end paths are compatible
+    if(start.m_data.size() != end.m_data.size() || start.m_segments.size() != end.m_segments.size())
+        return false;   //start and end paths are incompatible
+
+    //allocate new arrays
+    Array<RIuint8> newSegments;
+    newSegments.resize(m_segments.size() + start.m_segments.size());    //throws bad_alloc
+    Array<RIuint8> newData;
+    newData.resize(m_data.size() + start.m_data.size() * getBytesPerCoordinate(m_datatype) / getBytesPerCoordinate(start.m_datatype));  //throws bad_alloc
+    //if we get here, the memory allocations have succeeded
+
+    //copy old segments
+    if(m_segments.size())
+        ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+
+    //copy old data
+    if(m_data.size())
+        ri_memcpy(&newData[0], &m_data[0], m_data.size());
+
+    //copy segments
+    for(int i=0;i<start.m_segments.size();i++)
+    {
+        VGPathSegment s = getPathSegment(start.m_segments[i]);
+        VGPathSegment e = getPathSegment(end.m_segments[i]);
+
+        if(s == VG_SCCWARC_TO || s == VG_SCWARC_TO || s == VG_LCCWARC_TO || s == VG_LCWARC_TO)
+        {
+            if(e != VG_SCCWARC_TO && e != VG_SCWARC_TO && e != VG_LCCWARC_TO && e != VG_LCWARC_TO)
+                return false;   //start and end paths are incompatible
+            if(amount < 0.5f)
+                newSegments[m_segments.size() + i] = start.m_segments[i];
+            else
+                newSegments[m_segments.size() + i] = end.m_segments[i];
+        }
+        else
+        {
+            if(s != e)
+                return false;   //start and end paths are incompatible
+            newSegments[m_segments.size() + i] = start.m_segments[i];
+        }
+    }
+
+    //interpolate data
+    int oldNumCoords = getNumCoordinates();
+    for(int i=0;i<start.getNumCoordinates();i++)
+        setCoordinate(newData, m_datatype, m_scale, m_bias, oldNumCoords + i, start.getCoordinate(i) * (1.0f - amount) + end.getCoordinate(i) * amount);
+
+    RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype));
+
+    //replace old arrays
+    m_segments.swap(newSegments);
+    m_data.swap(newData);
+
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path for filling and appends resulting edges
+*           to a rasterizer.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::fill(const Matrix3x3& pathToSurface, Rasterizer& rasterizer)
+{
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(pathToSurface.isAffine());
+
+    tessellate(pathToSurface, 0.0f);    //throws bad_alloc
+
+    try
+    {
+        Vector2 p0(0,0), p1(0,0);
+        for(int i=0;i<m_vertices.size();i++)
+        {
+            p1 = affineTransform(pathToSurface, m_vertices[i].userPosition);
+
+            if(!(m_vertices[i].flags & START_SEGMENT))
+            {   //in the middle of a segment
+                rasterizer.addEdge(p0, p1); //throws bad_alloc
+            }
+
+            p0 = p1;
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        rasterizer.clear(); //remove the unfinished path
+        throw;
+    }
+}
+
+/**
+ *  \brief  Intersection between lines (p0->p1) and (p2->p3)
+ *  \todo   This must be done in the rasterizer to get correct results.
+ */
+static void intersectLines(const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3, Vector2& pt)
+{
+    RIfloat n = (p1.x-p0.x)*(p0.y-p2.y)-(p1.y-p0.y)*(p0.x-p2.x);
+    RIfloat d = (p3.y-p2.y)*(p1.x-p0.x)-(p3.x-p2.x)*(p1.y-p0.y);
+    if (d == 0) 
+    {
+        pt = p0;
+        return;
+    }
+    RIfloat t = n/d;
+    Vector2 dir = p1-p0;
+
+    pt = p0+t*dir;
+}
+
+static bool isCCW(const Vector2& a, const Vector2& b)
+{
+    RIfloat c = a.x*b.y - a.y*b.x;
+    return c >= 0;
+}
+
+/**
+ * \brief   Add a CCW stitch-triangle so that accw -> acw is the base of the triangle.
+ * \param   accw    Counter-clockwise stroke end (for example).
+ * \param   acw     Clockwise stroke end.
+ * \param   p       Tip of the triangle to form.
+ */
+static void addStitchTriangle(Rasterizer& rasterizer, const Vector2& accw, const Vector2& acw, const Vector2& p)
+{
+    if (isCCW(p - accw, acw - accw))
+    {
+        // p "below"
+        rasterizer.addEdge(accw, p);
+        rasterizer.addEdge(p, acw);
+        rasterizer.addEdge(acw, accw);
+    }
+    else
+    {
+        rasterizer.addEdge(accw, acw);
+        rasterizer.addEdge(acw, p);
+        rasterizer.addEdge(p, accw);
+    }
+}
+
+/**
+ * \brief   Add a (ccw-closed) segment to path. See the naming of parameters for input order:
+ *          pp = previous, nn = next
+ */
+static void addStrokeSegment(Rasterizer& rasterizer, const Vector2& ppccw, const Vector2& ppcw, const Vector2& nnccw, const Vector2& nncw)
+{
+    RIfloat d = dot(nnccw-ppccw, nncw-ppcw);
+    if(d < 0)
+    {
+        Vector2 ip;
+        intersectLines(ppccw, ppcw, nnccw, nncw, ip);
+
+        // Create two triangles from the self-intersecting part
+        if (isCCW(ppccw - nnccw, ip - nnccw))
+        {
+            rasterizer.addEdge(nnccw, ppccw);
+            rasterizer.addEdge(ppccw, ip);
+            rasterizer.addEdge(ip, nnccw);
+
+            rasterizer.addEdge(nncw, ppcw);
+            rasterizer.addEdge(ppcw, ip);
+            rasterizer.addEdge(ip, nncw);
+        }
+        else
+        {
+            rasterizer.addEdge(nnccw, ip);
+            rasterizer.addEdge(ip, ppccw);
+            rasterizer.addEdge(ppccw, nnccw);
+
+            rasterizer.addEdge(nncw, ip);
+            rasterizer.addEdge(ip, ppcw);
+            rasterizer.addEdge(ppcw, nncw);
+        }
+        // Final stitch (not necessary if done in the rasterizer)
+        addStitchTriangle(rasterizer, ppccw, ppcw, ip);
+        addStitchTriangle(rasterizer, nnccw, nncw, ip);
+    }
+    else
+    {
+        rasterizer.addEdge(ppccw, ppcw);	//throws bad_alloc
+        rasterizer.addEdge(ppcw, nncw);	//throws bad_alloc
+        rasterizer.addEdge(nncw, nnccw);		//throws bad_alloc
+        rasterizer.addEdge(nnccw, ppccw);	//throws bad_alloc
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Smoothly interpolates between two StrokeVertices. Positions
+*           are interpolated linearly, while tangents are interpolated
+*           on a unit circle. Stroking is implemented so that overlapping
+*           geometry doesnt cancel itself when filled with nonzero rule.
+*           The resulting polygons are closed.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::interpolateStroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth) const
+{
+    Vector2 ppccw, endccw;
+    Vector2 ppcw, endcw;
+    
+    if (m_mirror)
+    {
+        ppccw = affineTransform(pathToSurface, v0.cw);
+        ppcw = affineTransform(pathToSurface, v0.ccw);
+        endccw = affineTransform(pathToSurface, v1.cw);
+        endcw = affineTransform(pathToSurface, v1.ccw);
+    }
+    else
+    {
+        ppccw = affineTransform(pathToSurface, v0.ccw);
+        ppcw = affineTransform(pathToSurface, v0.cw);
+        endccw = affineTransform(pathToSurface, v1.ccw);
+        endcw = affineTransform(pathToSurface, v1.cw);
+    }
+
+	const RIfloat tessellationAngle = 5.0f;
+
+	RIfloat angle = RI_RAD_TO_DEG((RIfloat)acos(RI_CLAMP(dot(v0.t, v1.t), -1.0f, 1.0f))) / tessellationAngle;
+	int samples = RI_INT_MAX((int)ceil(angle), 1);
+	Vector2 prev = v0.p;
+	Vector2 prevt = v0.t;
+	Vector2 position = v0.p;
+	for(int j=0;j<samples-1;j++)
+	{
+		RIfloat t = (RIfloat)(j+1) / (RIfloat)samples;
+		position = v0.p * (1.0f - t) + v1.p * t;
+		Vector2 tangent = circularLerp(v0.t, v1.t, t);
+		Vector2 n = normalize(perpendicularCCW(tangent)) * strokeWidth * 0.5f;
+
+		Vector2 nnccw = affineTransform(pathToSurface, position + n);
+		Vector2 nncw = affineTransform(pathToSurface, position - n);
+
+        addStrokeSegment(rasterizer, ppccw, ppcw, nnccw, nncw);
+
+		ppccw = nnccw;
+		ppcw = nncw;
+		prev = position;
+		prevt = tangent;
+	}
+
+	//connect the last segment to the end coordinates
+	//Vector2 n = affineTangentTransform(pathToSurface, perpendicularCCW(v1.t));
+    Vector2 nncw = endcw;
+    Vector2 nnccw = endccw;
+
+    addStrokeSegment(rasterizer, ppccw, ppcw, nnccw, nncw);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Generate edges for stroke caps. Resulting polygons are closed.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::doCap(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v, RIfloat strokeWidth, VGCapStyle capStyle) const
+{
+    const bool mirror = m_mirror;
+    Vector2 ccwt, cwt, p;
+    if (mirror)
+    {
+        ccwt = affineTransform(pathToSurface, v.cw);
+        cwt = affineTransform(pathToSurface, v.ccw);
+        p = affineTransform(pathToSurface, v.p);
+    }
+    else
+    {
+        ccwt = affineTransform(pathToSurface, v.ccw);
+        cwt = affineTransform(pathToSurface, v.cw);
+        p = affineTransform(pathToSurface, v.p);
+    }
+
+    //rasterizer.clear();
+    switch(capStyle)
+    {
+    case VG_CAP_BUTT:
+        break;
+
+    case VG_CAP_ROUND:
+    {
+        const RIfloat tessellationAngle = 5.0f;
+
+        RIfloat angle = 180.0f / tessellationAngle;
+
+        int samples = (int)ceil(angle);
+        RIfloat step = 1.0f / samples;
+        RIfloat t = step;
+        Vector2 u0, u1;
+        if (!mirror)
+        {
+            u0 = normalize(v.cw - v.p);
+            u1 = normalize(v.ccw - v.p);
+        } else
+        {
+            u0 = normalize(v.ccw - v.p);
+            u1 = normalize(v.cw - v.p);
+        }
+        Vector2 prev = cwt;
+        rasterizer.addEdge(p, cwt);    //throws bad_alloc
+        for(int j=1;j<samples;j++)
+        {
+            Vector2 next = v.p + circularLerp(u0, u1, t, mirror) * strokeWidth * 0.5f;
+            next = affineTransform(pathToSurface, next);
+
+            rasterizer.addEdge(prev, next); //throws bad_alloc
+            prev = next;
+            t += step;
+        }
+        rasterizer.addEdge(prev, ccwt);  //throws bad_alloc
+        rasterizer.addEdge(ccwt, p);     //throws bad_alloc
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(capStyle == VG_CAP_SQUARE);
+        Vector2 t = v.t;
+        t.normalize();
+        Vector2 ccws, cws;
+        if (!mirror)
+        {
+            ccws = affineTransform(pathToSurface, v.ccw + t * strokeWidth * 0.5f);
+            cws = affineTransform(pathToSurface, v.cw + t * strokeWidth * 0.5f);
+        }
+        else
+        {
+            ccws = affineTransform(pathToSurface, v.cw + t * strokeWidth * 0.5f);
+            cws = affineTransform(pathToSurface, v.ccw + t * strokeWidth * 0.5f);
+        }
+        rasterizer.addEdge(p, cwt);    //throws bad_alloc
+        rasterizer.addEdge(cwt, cws); //throws bad_alloc
+        rasterizer.addEdge(cws, ccws);  //throws bad_alloc
+        rasterizer.addEdge(ccws, ccwt);   //throws bad_alloc
+        rasterizer.addEdge(ccwt, p);     //throws bad_alloc
+        break;
+    }
+    }
+    //rasterizer.fill();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Generate edges for stroke joins. Resulting polygons are closed.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::doJoin(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth, VGJoinStyle joinStyle, RIfloat miterLimit) const
+{
+    const bool mirror = m_mirror;
+    Vector2 ccw0t, ccw1t;
+    Vector2 cw0t, cw1t;
+    Vector2 m0t, m1t;
+    Vector2 tt0, tt1;
+
+    if(mirror)
+    {
+        ccw0t = affineTransform(pathToSurface, v0.cw);
+        cw0t = affineTransform(pathToSurface, v0.ccw);
+        m0t = affineTransform(pathToSurface, v0.p);
+        tt0 = affineTangentTransform(pathToSurface, v0.t);
+        ccw1t = affineTransform(pathToSurface, v1.cw);
+        cw1t = affineTransform(pathToSurface, v1.ccw);
+        m1t = affineTransform(pathToSurface, v1.p);
+        tt1 = affineTangentTransform(pathToSurface, v1.t);
+    } else
+    {
+        ccw0t = affineTransform(pathToSurface, v0.ccw);
+        cw0t = affineTransform(pathToSurface, v0.cw);
+        m0t = affineTransform(pathToSurface, v0.p);
+        tt0 = affineTangentTransform(pathToSurface, v0.t);
+        ccw1t = affineTransform(pathToSurface, v1.ccw);
+        cw1t = affineTransform(pathToSurface, v1.cw);
+        m1t = affineTransform(pathToSurface, v1.p);
+        tt1 = affineTangentTransform(pathToSurface, v1.t);
+    }
+
+    Vector2 tccw = v1.ccw - v0.ccw;
+    Vector2 s, e, m, st, et;
+    bool cw = true;
+
+    // \todo Uses addStrokeSegment, which is wasteful in several cases
+    // (but should be pretty robust)
+    // Round or miter to cw-side?
+    
+    if (dot(tt1, ccw0t - m0t) >= 0)
+        cw = false;
+        
+    // Add the bevel (which is part of all the other joins also)
+    // This would be a "consistent" way to handle joins (in addition
+    // to creating rounding to _both_ side of the join). However,
+    // the conformance test currently invalidates this case.
+    // \note Causes some extra geometry.
+    if (cw)
+        addStrokeSegment(rasterizer, ccw0t, m0t, ccw1t, m1t);
+    else
+        addStrokeSegment(rasterizer, m0t, cw0t, m1t, cw1t);
+
+    switch (joinStyle)
+    {
+    case VG_JOIN_BEVEL:
+        break;
+    case VG_JOIN_MITER:
+    {
+        RIfloat theta = (RIfloat)acos(RI_CLAMP(dot(v0.t, -v1.t), -1.0f, 1.0f));
+        RIfloat miterLengthPerStrokeWidth = 1.0f / (RIfloat)sin(theta*0.5f);
+        if (miterLengthPerStrokeWidth < miterLimit)
+        {   
+            // Miter
+            if (cw)
+            {
+                m = !mirror ? v0.ccw : v0.cw;
+                s = ccw1t;
+                e = ccw0t;
+            } else
+            {
+                m = !mirror ? v0.cw : v0.ccw;
+                s = cw0t;
+                e = cw1t;
+            }
+
+            RIfloat l = (RIfloat)cos(theta*0.5f) * miterLengthPerStrokeWidth * (strokeWidth * 0.5f);
+            l = RI_MIN(l, RI_FLOAT_MAX);    //force finite
+            Vector2 c = m + v0.t * l;
+            c = affineTransform(pathToSurface, c);
+
+            rasterizer.addEdge(s, c);
+            rasterizer.addEdge(c, e);
+            rasterizer.addEdge(e, s);
+        }
+        break;
+    }
+    default:
+    {
+        RI_ASSERT(joinStyle == VG_JOIN_ROUND);
+
+        Vector2 sp, ep;
+
+        const RIfloat tessellationAngle = 5.0f;
+            
+        if (cw)
+        {
+            s = ccw1t;
+            st = -v1.t;
+            e = ccw0t;
+            et = -v0.t;
+            sp = v1.p;
+            ep = v0.p;
+        } else
+        {
+            s = cw0t;
+            st = v0.t;
+            e = cw1t;
+            et = v1.t;
+            sp = v0.p;
+            ep = v1.p;
+        }
+
+        Vector2 prev = s;
+        RIfloat angle = RI_RAD_TO_DEG((RIfloat)acos(RI_CLAMP(dot(st, et), -1.0f, 1.0f))) / tessellationAngle;
+        int samples = (int)ceil(angle);
+        if( samples )
+        {
+            RIfloat step = 1.0f / samples;
+            RIfloat t = step;
+            for(int j=1;j<samples;j++)
+            {
+                Vector2 position = sp * (1.0f - t) + ep * t;
+                Vector2 tangent = circularLerp(st, et, t, mirror);
+
+                Vector2 next = position + normalize(perpendicular(tangent, !mirror)) * strokeWidth * 0.5f;
+                next = affineTransform(pathToSurface, next);
+
+                rasterizer.addEdge(prev, next); //throws bad_alloc
+                prev = next;
+                t += step;
+            }
+        }
+        rasterizer.addEdge(prev, e);    //throws bad_alloc
+        rasterizer.addEdge(e, s);
+        break;
+    }
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellate a path, apply stroking, dashing, caps and joins, and
+*           append resulting edges to a rasterizer.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::stroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const Array<RIfloat>& dashPattern, RIfloat dashPhase, bool dashPhaseReset, RIfloat strokeWidth, VGCapStyle capStyle, VGJoinStyle joinStyle, RIfloat miterLimit)
+{
+    RI_ASSERT(pathToSurface.isAffine());
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(strokeWidth >= 0.0f);
+    RI_ASSERT(miterLimit >= 1.0f);
+
+    tessellate(pathToSurface, strokeWidth); //throws bad_alloc
+
+    m_mirror = pathToSurface[0][0]*pathToSurface[1][1] < 0 ? true : false;
+
+    if(!m_vertices.size())
+        return;
+
+    bool dashing = true;
+    int dashPatternSize = dashPattern.size();
+    if( dashPattern.size() & 1 )
+        dashPatternSize--;  //odd number of dash pattern entries, discard the last one
+    RIfloat dashPatternLength = 0.0f;
+    for(int i=0;i<dashPatternSize;i++)
+        dashPatternLength += RI_MAX(dashPattern[i], 0.0f);
+    if(!dashPatternSize || dashPatternLength == 0.0f )
+        dashing = false;
+    dashPatternLength = RI_MIN(dashPatternLength, RI_FLOAT_MAX);
+
+    //walk along the path
+    //stop at the next event which is either:
+    //-path vertex
+    //-dash stop
+    //for robustness, decisions based on geometry are done only once.
+    //inDash keeps track whether the last point was in dash or not
+
+    //loop vertex events
+    try
+    {
+        RIfloat nextDash = 0.0f;
+        int d = 0;
+        bool inDash = true;
+        StrokeVertex v0, v1, vs;
+        for(int i=0;i<m_vertices.size();i++)
+        {
+            //read the next vertex
+            Vertex& v = m_vertices[i];
+            v1.p = v.userPosition;
+            v1.t = v.userTangent;
+            RI_ASSERT(!isZero(v1.t));   //don't allow zero tangents
+
+            v1.ccw = v1.p + normalize(perpendicularCCW(v1.t)) * strokeWidth * 0.5f;
+            v1.cw = v1.p + normalize(perpendicularCW(v1.t)) * strokeWidth * 0.5f;
+
+            v1.pathLength = v.pathLength;
+            v1.flags = v.flags;
+            v1.inDash = dashing ? inDash : true;    //NOTE: for other than START_SEGMENT vertices inDash will be updated after dashing
+
+            //process the vertex event
+            if(v.flags & START_SEGMENT)
+            {
+                if(v.flags & START_SUBPATH)
+                {
+                    if( dashing )
+                    {   //initialize dashing by finding which dash or gap the first point of the path lies in
+                        if(dashPhaseReset || i == 0)
+                        {
+                            d = 0;
+                            inDash = true;
+                            nextDash = v1.pathLength - RI_MOD(dashPhase, dashPatternLength);
+                            for(;;)
+                            {
+                                RIfloat prevDash = nextDash;
+                                nextDash = prevDash + RI_MAX(dashPattern[d], 0.0f);
+                                if(nextDash >= v1.pathLength)
+                                    break;
+
+                                if( d & 1 )
+                                    inDash = true;
+                                else
+                                    inDash = false;
+                                d = (d+1) % dashPatternSize;
+                            }
+                            v1.inDash = inDash;
+                            //the first point of the path lies between prevDash and nextDash
+                            //d in the index of the next dash stop
+                            //inDash is true if the first point is in a dash
+                        }
+                    }
+                    vs = v1;    //save the subpath start point
+                }
+                else
+                {
+                    if( v.flags & IMPLICIT_CLOSE_SUBPATH )
+                    {   //do caps for the start and end of the current subpath
+                        if( v0.inDash )
+                            doCap(pathToSurface, rasterizer, v0, strokeWidth, capStyle);    //end cap   //throws bad_alloc
+                        if( vs.inDash )
+                        {
+                            StrokeVertex vi = vs;
+                            vi.t = -vi.t;
+                            RI_SWAP(vi.ccw.x, vi.cw.x);
+                            RI_SWAP(vi.ccw.y, vi.cw.y);
+                            doCap(pathToSurface, rasterizer, vi, strokeWidth, capStyle);    //start cap //throws bad_alloc
+                        }
+                    }
+                    else
+                    {   //join two segments
+                        RI_ASSERT(v0.inDash == v1.inDash);
+                        if( v0.inDash )
+                            doJoin(pathToSurface, rasterizer, v0, v1, strokeWidth, joinStyle, miterLimit);  //throws bad_alloc
+                    }
+                }
+            }
+            else
+            {   //in the middle of a segment
+                if( !(v.flags & IMPLICIT_CLOSE_SUBPATH) )
+                {   //normal segment, do stroking
+                    if( dashing )
+                    {
+                        StrokeVertex prevDashVertex = v0;   //dashing of the segment starts from the previous vertex
+
+                        if(nextDash + 10000.0f * dashPatternLength < v1.pathLength)
+                            throw std::bad_alloc();     //too many dashes, throw bad_alloc
+
+                        //loop dash events until the next vertex event
+                        //zero length dashes are handled as a special case since if they hit the vertex,
+                        //we want to include their starting point to this segment already in order to generate a join
+                        int numDashStops = 0;
+                        while(nextDash < v1.pathLength || (nextDash <= v1.pathLength && dashPattern[(d+1) % dashPatternSize] == 0.0f))
+                        {
+                            RIfloat edgeLength = v1.pathLength - v0.pathLength;
+                            RIfloat ratio = 0.0f;
+                            if(edgeLength > 0.0f)
+                                ratio = (nextDash - v0.pathLength) / edgeLength;
+                            StrokeVertex nextDashVertex;
+                            nextDashVertex.p = v0.p * (1.0f - ratio) + v1.p * ratio;
+                            nextDashVertex.t = circularLerp(v0.t, v1.t, ratio);
+                            nextDashVertex.ccw = nextDashVertex.p + normalize(perpendicularCCW(nextDashVertex.t)) * strokeWidth * 0.5f;
+                            nextDashVertex.cw = nextDashVertex.p + normalize(perpendicularCW(nextDashVertex.t)) * strokeWidth * 0.5f;
+
+                            if( inDash )
+                            {   //stroke from prevDashVertex -> nextDashVertex
+                                if( numDashStops )
+                                {   //prevDashVertex is not the start vertex of the segment, cap it (start vertex has already been joined or capped)
+                                    StrokeVertex vi = prevDashVertex;
+                                    vi.t = -vi.t;
+                                    RI_SWAP(vi.ccw.x, vi.cw.x);
+                                    RI_SWAP(vi.ccw.y, vi.cw.y);
+                                    doCap(pathToSurface, rasterizer, vi, strokeWidth, capStyle);    //throws bad_alloc
+                                }
+                                interpolateStroke(pathToSurface, rasterizer, prevDashVertex, nextDashVertex, strokeWidth);  //throws bad_alloc
+                                doCap(pathToSurface, rasterizer, nextDashVertex, strokeWidth, capStyle);    //end cap   //throws bad_alloc
+                            }
+                            prevDashVertex = nextDashVertex;
+
+                            if( d & 1 )
+                            {   //dash starts
+                                RI_ASSERT(!inDash);
+                                inDash = true;
+                            }
+                            else
+                            {   //dash ends
+                                RI_ASSERT(inDash);
+                                inDash = false;
+                            }
+                            d = (d+1) % dashPatternSize;
+                            nextDash += RI_MAX(dashPattern[d], 0.0f);
+                            numDashStops++;
+                        }
+                        
+                        if( inDash )
+                        {   //stroke prevDashVertex -> v1
+                            if( numDashStops )
+                            {   //prevDashVertex is not the start vertex of the segment, cap it (start vertex has already been joined or capped)
+                                StrokeVertex vi = prevDashVertex;
+                                vi.t = -vi.t;
+                                RI_SWAP(vi.ccw.x, vi.cw.x);
+                                RI_SWAP(vi.ccw.y, vi.cw.y);
+                                doCap(pathToSurface, rasterizer, vi, strokeWidth, capStyle);    //throws bad_alloc
+                            }
+                            interpolateStroke(pathToSurface, rasterizer, prevDashVertex, v1, strokeWidth);  //throws bad_alloc
+                            //no cap, leave path open
+                        }
+
+                        v1.inDash = inDash; //update inDash status of the segment end point
+                    }
+                    else    //no dashing, just interpolate segment end points
+                        interpolateStroke(pathToSurface, rasterizer, v0, v1, strokeWidth);  //throws bad_alloc
+                }
+            }
+
+            if((v.flags & END_SEGMENT) && (v.flags & CLOSE_SUBPATH))
+            {   //join start and end of the current subpath
+                if( v1.inDash && vs.inDash )
+                    doJoin(pathToSurface, rasterizer, v1, vs, strokeWidth, joinStyle, miterLimit);  //throws bad_alloc
+                else
+                {   //both start and end are not in dash, cap them
+                    if( v1.inDash )
+                        doCap(pathToSurface, rasterizer, v1, strokeWidth, capStyle);    //end cap   //throws bad_alloc
+                    if( vs.inDash )
+                    {
+                        StrokeVertex vi = vs;
+                        vi.t = -vi.t;
+                        RI_SWAP(vi.ccw.x, vi.cw.x);
+                        RI_SWAP(vi.ccw.y, vi.cw.y);
+                        doCap(pathToSurface, rasterizer, vi, strokeWidth, capStyle);    //start cap //throws bad_alloc
+                    }
+                }
+            }
+
+            v0 = v1;
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        rasterizer.clear(); //remove the unfinished path
+        throw;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path, and returns a position and a tangent on the path
+*           given a distance along the path.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::getPointAlong(int startIndex, int numSegments, RIfloat distance, Vector2& p, Vector2& t)
+{
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size() && numSegments > 0);
+
+    Matrix3x3 identity;
+    identity.identity();
+    tessellate(identity, 0.0f); //throws bad_alloc
+
+    RI_ASSERT(startIndex >= 0 && startIndex < m_segmentToVertex.size());
+    RI_ASSERT(startIndex + numSegments >= 0 && startIndex + numSegments <= m_segmentToVertex.size());
+
+    // ignore move segments at the start of the path
+    while (numSegments && (m_segments[startIndex] & ~VG_RELATIVE) == VG_MOVE_TO)
+    {
+        startIndex++;
+        numSegments--;
+    }
+
+    // ignore move segments at the end of the path
+    while (numSegments && (m_segments[startIndex + numSegments - 1] & ~VG_RELATIVE) == VG_MOVE_TO)
+        numSegments--;
+
+    // empty path?
+    if (!m_vertices.size() || !numSegments)
+    {
+        p.set(0,0);
+        t.set(1,0);
+        return;
+    }
+
+    int startVertex = m_segmentToVertex[startIndex].start;
+    int endVertex = m_segmentToVertex[startIndex + numSegments - 1].end;
+
+    if(startVertex == -1)
+        startVertex = 0;
+
+    // zero length?
+    if (startVertex >= endVertex)
+    {
+        p = m_vertices[startVertex].userPosition;
+        t.set(1,0);
+        return;
+    }
+
+    RI_ASSERT(startVertex >= 0 && startVertex < m_vertices.size());
+    RI_ASSERT(endVertex >= 0 && endVertex < m_vertices.size());
+
+    distance += m_vertices[startVertex].pathLength; //map distance to the range of the whole path
+
+    if(distance <= m_vertices[startVertex].pathLength)
+    {   //return the first point of the path
+        p = m_vertices[startVertex].userPosition;
+        t = m_vertices[startVertex].userTangent;
+        return;
+    }
+
+    if(distance >= m_vertices[endVertex].pathLength)
+    {   //return the last point of the path
+        p = m_vertices[endVertex].userPosition;
+        t = m_vertices[endVertex].userTangent;
+        return;
+    }
+
+    //search for the segment containing the distance
+    for(int s=startIndex;s<startIndex+numSegments;s++)
+    {
+        int start = m_segmentToVertex[s].start;
+        int end = m_segmentToVertex[s].end;
+        if(start < 0)
+            start = 0;
+        if(end < 0)
+            end = 0;
+        RI_ASSERT(start >= 0 && start < m_vertices.size());
+        RI_ASSERT(end >= 0 && end < m_vertices.size());
+
+        if(distance >= m_vertices[start].pathLength && distance < m_vertices[end].pathLength)
+        {   //segment contains the queried distance
+            for(int i=start;i<end;i++)
+            {
+                const Vertex& v0 = m_vertices[i];
+                const Vertex& v1 = m_vertices[i+1];
+                if(distance >= v0.pathLength && distance < v1.pathLength)
+                {   //segment found, interpolate linearly between its end points
+                    RIfloat edgeLength = v1.pathLength - v0.pathLength;
+                    RI_ASSERT(edgeLength > 0.0f);
+                    RIfloat r = (distance - v0.pathLength) / edgeLength;
+                    p = (1.0f - r) * v0.userPosition + r * v1.userPosition;
+                    t = (1.0f - r) * v0.userTangent + r * v1.userTangent;
+                    return;
+                }
+            }
+        }
+    }
+
+    RI_ASSERT(0);   //point not found (should never get here)
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path, and computes its length.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+RIfloat Path::getPathLength(int startIndex, int numSegments)
+{
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size() && numSegments > 0);
+
+    Matrix3x3 identity;
+    identity.identity();
+    tessellate(identity, 0.0f); //throws bad_alloc
+
+    RI_ASSERT(startIndex >= 0 && startIndex < m_segmentToVertex.size());
+    RI_ASSERT(startIndex + numSegments >= 0 && startIndex + numSegments <= m_segmentToVertex.size());
+
+    int startVertex = m_segmentToVertex[startIndex].start;
+    int endVertex = m_segmentToVertex[startIndex + numSegments - 1].end;
+
+    if(!m_vertices.size())
+        return 0.0f;
+
+    RIfloat startPathLength = 0.0f;
+    if(startVertex >= 0)
+    {
+        RI_ASSERT(startVertex >= 0 && startVertex < m_vertices.size());
+        startPathLength = m_vertices[startVertex].pathLength;
+    }
+    RIfloat endPathLength = 0.0f;
+    if(endVertex >= 0)
+    {
+        RI_ASSERT(endVertex >= 0 && endVertex < m_vertices.size());
+        endPathLength = m_vertices[endVertex].pathLength;
+    }
+
+    return endPathLength - startPathLength;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path, and computes its bounding box in user space.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::getPathBounds(RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy)
+{
+    RI_ASSERT(m_referenceCount > 0);
+
+    Matrix3x3 identity;
+    identity.identity();
+    tessellate(identity, 0.0f); //throws bad_alloc
+
+    if(m_vertices.size())
+    {
+        minx = m_userMinx;
+        miny = m_userMiny;
+        maxx = m_userMaxx;
+        maxy = m_userMaxy;
+    }
+    else
+    {
+        minx = miny = 0;
+        maxx = maxy = -1;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path, and computes its bounding box in surface space.
+* \param    
+* \return   
+* \note     if runs out of memory, throws bad_alloc and leaves the path as it was
+*//*-------------------------------------------------------------------*/
+
+void Path::getPathTransformedBounds(const Matrix3x3& pathToSurface, RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy)
+{
+    RI_ASSERT(m_referenceCount > 0);
+    RI_ASSERT(pathToSurface.isAffine());
+
+    Matrix3x3 identity;
+    identity.identity();
+    tessellate(identity, 0.0f); //throws bad_alloc
+
+    if(m_vertices.size())
+    {
+        Vector3 p0(m_userMinx, m_userMiny, 1.0f);
+        Vector3 p1(m_userMinx, m_userMaxy, 1.0f);
+        Vector3 p2(m_userMaxx, m_userMaxy, 1.0f);
+        Vector3 p3(m_userMaxx, m_userMiny, 1.0f);
+        p0 = pathToSurface * p0;
+        p1 = pathToSurface * p1;
+        p2 = pathToSurface * p2;
+        p3 = pathToSurface * p3;
+
+        minx = RI_MIN(RI_MIN(RI_MIN(p0.x, p1.x), p2.x), p3.x);
+        miny = RI_MIN(RI_MIN(RI_MIN(p0.y, p1.y), p2.y), p3.y);
+        maxx = RI_MAX(RI_MAX(RI_MAX(p0.x, p1.x), p2.x), p3.x);
+        maxy = RI_MAX(RI_MAX(RI_MAX(p0.y, p1.y), p2.y), p3.y);
+    }
+    else
+    {
+        minx = miny = 0;
+        maxx = maxy = -1;
+    }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Adds a vertex to a tessellated path.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::addVertex(const Vector2& p, const Vector2& t, RIfloat pathLength, unsigned int flags)
+{
+    RI_ASSERT(!isZero(t));
+
+    Vertex v;
+    v.pathLength = pathLength;
+    v.userPosition = p;
+    v.userTangent = t;
+    v.flags = flags;
+    m_vertices.push_back(v);    //throws bad_alloc
+    m_numTessVertices++;
+
+    m_userMinx = RI_MIN(m_userMinx, v.userPosition.x);
+    m_userMiny = RI_MIN(m_userMiny, v.userPosition.y);
+    m_userMaxx = RI_MAX(m_userMaxx, v.userPosition.x);
+    m_userMaxy = RI_MAX(m_userMaxy, v.userPosition.y);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Adds an edge to a tessellated path.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::addEdge(const Vector2& p0, const Vector2& p1, const Vector2& t0, const Vector2& t1, unsigned int startFlags, unsigned int endFlags)
+{
+    Vertex v;
+    RIfloat pathLength = 0.0f;
+
+    RI_ASSERT(!isZero(t0) && !isZero(t1));
+
+    //segment midpoints are shared between edges
+    if(!m_numTessVertices)
+    {
+        if(m_vertices.size() > 0)
+            pathLength = m_vertices[m_vertices.size()-1].pathLength;
+
+        addVertex(p0, t0, pathLength, startFlags);  //throws bad_alloc
+    }
+
+    //other than implicit close paths (caused by a MOVE_TO) add to path length
+    if( !(endFlags & IMPLICIT_CLOSE_SUBPATH) )
+    {
+        //NOTE: with extremely large coordinates the floating point path length is infinite
+        RIfloat l = (p1 - p0).length();
+        pathLength = m_vertices[m_vertices.size()-1].pathLength + l;
+        pathLength = RI_MIN(pathLength, RI_FLOAT_MAX);
+    }
+
+    addVertex(p1, t1, pathLength, endFlags);    //throws bad_alloc
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a close-path segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+void Path::addEndPath(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry, unsigned int flags)
+{
+    RI_UNREF(pathToSurface);
+    m_numTessVertices = 0;
+    if(!subpathHasGeometry)
+    {   //single vertex
+        Vector2 t(1.0f,0.0f);
+        addEdge(p0, p1, t, t, START_SEGMENT | START_SUBPATH, END_SEGMENT | END_SUBPATH);    //throws bad_alloc
+        m_numTessVertices = 0;
+        addEdge(p0, p1, -t, -t, IMPLICIT_CLOSE_SUBPATH | START_SEGMENT, IMPLICIT_CLOSE_SUBPATH | END_SEGMENT);  //throws bad_alloc
+        return;
+    }
+    //the subpath contains segment commands that have generated geometry
+
+    //add a close path segment to the start point of the subpath
+    RI_ASSERT(m_vertices.size() > 0);
+    m_vertices[m_vertices.size()-1].flags |= END_SUBPATH;
+
+    Vector2 t = normalize(p1 - p0);
+    if(isZero(t))
+        t = m_vertices[m_vertices.size()-1].userTangent;    //if the segment is zero-length, use the tangent of the last segment end point so that proper join will be generated
+    RI_ASSERT(!isZero(t));
+
+    addEdge(p0, p1, t, t, flags | START_SEGMENT, flags | END_SEGMENT);  //throws bad_alloc
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a line-to segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+bool Path::addLineTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry)
+{
+    RI_UNREF(pathToSurface);
+    if(p0 == p1)
+        return false;   //discard zero-length segments
+
+    //compute end point tangents
+    Vector2 t = normalize(p1 - p0);
+    RI_ASSERT(!isZero(t));
+
+    m_numTessVertices = 0;
+    unsigned int startFlags = START_SEGMENT;
+    if(!subpathHasGeometry)
+        startFlags |= START_SUBPATH;
+    addEdge(p0, p1, t, t, startFlags, END_SEGMENT); //throws bad_alloc
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a quad-to segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+bool Path::addQuadTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, bool subpathHasGeometry, float strokeWidth)
+{
+    RI_UNREF(pathToSurface);
+    RI_UNREF(strokeWidth);
+    if(p0 == p1 && p0 == p2)
+    {
+        RI_ASSERT(p1 == p2);
+        return false;   //discard zero-length segments
+    }
+
+    //compute end point tangents
+
+    Vector2 incomingTangent = normalize(p1 - p0);
+    Vector2 outgoingTangent = normalize(p2 - p1);
+    if(p0 == p1)
+        incomingTangent = normalize(p2 - p0);
+    if(p1 == p2)
+        outgoingTangent = normalize(p2 - p0);
+    RI_ASSERT(!isZero(incomingTangent) && !isZero(outgoingTangent));
+
+    m_numTessVertices = 0;
+    unsigned int startFlags = START_SEGMENT;
+    if(!subpathHasGeometry)
+        startFlags |= START_SUBPATH;
+
+    const int segments = RI_NUM_TESSELLATED_SEGMENTS_QUAD;
+    Vector2 pp = p0;
+    Vector2 tp = incomingTangent;
+    unsigned int prevFlags = startFlags;
+    for(int i=1;i<segments;i++)
+    {
+        RIfloat t = (RIfloat)i / (RIfloat)segments;
+        RIfloat u = 1.0f-t;
+        Vector2 pn = u*u * p0 + 2.0f*t*u * p1 + t*t * p2;
+        Vector2 tn = (-1.0f+t) * p0 + (1.0f-2.0f*t) * p1 + t * p2;
+        tn = normalize(tn);
+        if(isZero(tn))
+            tn = tp;
+
+        addEdge(pp, pn, tp, tn, prevFlags, 0);  //throws bad_alloc
+
+        pp = pn;
+        tp = tn;
+        prevFlags = 0;
+    }
+    addEdge(pp, p2, tp, outgoingTangent, prevFlags, END_SEGMENT);   //throws bad_alloc
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a cubic-to segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+bool Path::addCubicTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3, bool subpathHasGeometry, float strokeWidth)
+{
+    RI_UNREF(pathToSurface);
+    RI_UNREF(strokeWidth);
+
+    if(p0 == p1 && p0 == p2 && p0 == p3)
+    {
+        RI_ASSERT(p1 == p2 && p1 == p3 && p2 == p3);
+        return false;   //discard zero-length segments
+    }
+
+    //compute end point tangents
+    Vector2 incomingTangent = normalize(p1 - p0);
+    Vector2 outgoingTangent = normalize(p3 - p2);
+    if(p0 == p1)
+    {
+        incomingTangent = normalize(p2 - p0);
+        if(p1 == p2)
+            incomingTangent = normalize(p3 - p0);
+    }
+    if(p2 == p3)
+    {
+        outgoingTangent = normalize(p3 - p1);
+        if(p1 == p2)
+            outgoingTangent = normalize(p3 - p0);
+    }
+    RI_ASSERT(!isZero(incomingTangent) && !isZero(outgoingTangent));
+
+    m_numTessVertices = 0;
+    unsigned int startFlags = START_SEGMENT;
+    if(!subpathHasGeometry)
+        startFlags |= START_SUBPATH;
+
+    const int segments = RI_NUM_TESSELLATED_SEGMENTS_CUBIC;
+    Vector2 pp = p0;
+    Vector2 tp = incomingTangent;
+    unsigned int prevFlags = startFlags;
+    for(int i=1;i<segments;i++)
+    {
+        RIfloat t = (RIfloat)i / (RIfloat)segments;
+        Vector2 pn = (1.0f - 3.0f*t + 3.0f*t*t - t*t*t) * p0 + (3.0f*t - 6.0f*t*t + 3.0f*t*t*t) * p1 + (3.0f*t*t - 3.0f*t*t*t) * p2 + t*t*t * p3;
+        Vector2 tn = (-3.0f + 6.0f*t - 3.0f*t*t) * p0 + (3.0f - 12.0f*t + 9.0f*t*t) * p1 + (6.0f*t - 9.0f*t*t) * p2 + 3.0f*t*t * p3;
+
+        tn = normalize(tn);
+        if(isZero(tn))
+            tn = tp;
+
+        addEdge(pp, pn, tp, tn, prevFlags, 0);  //throws bad_alloc
+
+        pp = pn;
+        tp = tn;
+        prevFlags = 0;
+    }
+    addEdge(pp, p3, tp, outgoingTangent, prevFlags, END_SEGMENT);   //throws bad_alloc
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Finds an ellipse center and transformation from the unit circle to
+*           that ellipse.
+* \param    rh Length of the horizontal axis
+*           rv Length of the vertical axis
+*           rot Rotation angle
+*           p0,p1 User space end points of the arc
+*           c0,c1 (Return value) Unit circle space center points of the two ellipses
+*           u0,u1 (Return value) Unit circle space end points of the arc
+*           unitCircleToEllipse (Return value) A matrix mapping from unit circle space to user space
+* \return   true if ellipse exists, false if doesn't
+* \note     
+*//*-------------------------------------------------------------------*/
+
+static bool findEllipses(RIfloat rh, RIfloat rv, RIfloat rot, const Vector2& p0, const Vector2& p1, VGPathSegment segment, Vector2& c0, Vector2& c1, Vector2& u0, Vector2& u1, Matrix3x3& unitCircleToEllipse, bool& cw)
+{
+    rh = RI_ABS(rh);
+    rv = RI_ABS(rv);
+    if(rh == 0.0f || rv == 0.0f || p0 == p1)
+        return false;   //degenerate ellipse
+
+    rot = RI_DEG_TO_RAD(rot);
+    unitCircleToEllipse.set((RIfloat)cos(rot)*rh, -(RIfloat)sin(rot)*rv,  0,
+                            (RIfloat)sin(rot)*rh,  (RIfloat)cos(rot)*rv,  0,
+                            0,                   0,                   1);
+    Matrix3x3 ellipseToUnitCircle = invert(unitCircleToEllipse);
+    //force affinity
+    ellipseToUnitCircle[2][0] = 0.0f;
+    ellipseToUnitCircle[2][1] = 0.0f;
+    ellipseToUnitCircle[2][2] = 1.0f;
+
+    // Transform p0 and p1 into unit space
+    u0 = affineTransform(ellipseToUnitCircle, p0);
+    u1 = affineTransform(ellipseToUnitCircle, p1);
+
+    Vector2 m = 0.5f * (u0 + u1);
+    Vector2 d = u0 - u1;
+
+    RIfloat lsq = (RIfloat)dot(d,d);
+    if(lsq <= 0.0f)
+        return false;   //the points are coincident
+
+    RIfloat disc = (1.0f / lsq) - 0.25f;
+    if(disc < 0.0f)
+    {   //the points are too far apart for a solution to exist, scale the axes so that there is a solution
+        RIfloat l = (RIfloat)sqrt(lsq);
+        rh *= 0.5f * l;
+        rv *= 0.5f * l;
+
+        //redo the computation with scaled axes
+        unitCircleToEllipse.set((RIfloat)cos(rot)*rh, -(RIfloat)sin(rot)*rv,  0,
+                                (RIfloat)sin(rot)*rh,  (RIfloat)cos(rot)*rv,  0,
+                                0,                   0,                   1);
+        ellipseToUnitCircle = invert(unitCircleToEllipse);
+        //force affinity
+        ellipseToUnitCircle[2][0] = 0.0f;
+        ellipseToUnitCircle[2][1] = 0.0f;
+        ellipseToUnitCircle[2][2] = 1.0f;
+
+        // Transform p0 and p1 into unit space
+        u0 = affineTransform(ellipseToUnitCircle, p0);
+        u1 = affineTransform(ellipseToUnitCircle, p1);
+
+        // Solve for intersecting unit circles
+        d = u0 - u1;
+        m = 0.5f * (u0 + u1);
+
+        lsq = dot(d,d);
+        if(lsq <= 0.0f)
+            return false;   //the points are coincident
+
+        disc = RI_MAX(0.0f, 1.0f / lsq - 0.25f);
+    }
+
+    if(u0 == u1)
+        return false;
+
+    Vector2 sd = d * (RIfloat)sqrt(disc);
+    Vector2 sp = perpendicularCW(sd);
+    c0 = m + sp;
+    c1 = m - sp;
+
+    //choose the center point and direction
+    Vector2 cp = c0;
+    if(segment == VG_SCWARC_TO || segment == VG_LCCWARC_TO)
+        cp = c1;
+    cw = false;
+    if(segment == VG_SCWARC_TO || segment == VG_LCWARC_TO)
+        cw = true;
+
+    //move the unit circle origin to the chosen center point
+    u0 -= cp;
+    u1 -= cp;
+
+    if(u0 == u1 || isZero(u0) || isZero(u1))
+        return false;
+
+    //transform back to the original coordinate space
+    cp = affineTransform(unitCircleToEllipse, cp);
+    unitCircleToEllipse[0][2] = cp.x;
+    unitCircleToEllipse[1][2] = cp.y;
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates an arc-to segment.
+* \param    
+* \return   
+* \note     
+*//*-------------------------------------------------------------------*/
+
+bool Path::addArcTo(const Matrix3x3& pathToSurface, const Vector2& p0, RIfloat rh, RIfloat rv, RIfloat rot, const Vector2& p1, const Vector2& p1r, VGPathSegment segment, bool subpathHasGeometry, float strokeWidth)
+{
+    RI_UNREF(pathToSurface);
+    RI_UNREF(strokeWidth);
+
+    if(p0 == p1)
+        return false;   //discard zero-length segments
+    
+    // Check NaNs
+    // \todo Make a general vec2 function?
+    if (RI_ISNAN(p0.x) || RI_ISNAN(p0.y))
+        return false;
+
+    if (RI_ISNAN(p1.x) || RI_ISNAN(p1.y))
+        return false;
+
+    Vector2 c0, c1, u0, u1;
+    Matrix3x3 unitCircleToEllipse;
+    bool cw;
+
+    m_numTessVertices = 0;
+    unsigned int startFlags = START_SEGMENT;
+    if(!subpathHasGeometry)
+        startFlags |= START_SUBPATH;
+
+    if(!findEllipses(rh, rv, rot, Vector2(), p1r, segment, c0, c1, u0, u1, unitCircleToEllipse, cw))
+    {   //ellipses don't exist, add line instead
+        Vector2 t = normalize(p1r);
+        RI_ASSERT(!isZero(t));
+        addEdge(p0, p1, t, t, startFlags, END_SEGMENT); //throws bad_alloc
+        return true;
+    }
+
+    //compute end point tangents
+    Vector2 incomingTangent = perpendicular(u0, cw);
+    incomingTangent = affineTangentTransform(unitCircleToEllipse, incomingTangent);
+    incomingTangent = normalize(incomingTangent);
+    Vector2 outgoingTangent = perpendicular(u1, cw);
+    outgoingTangent = affineTangentTransform(unitCircleToEllipse, outgoingTangent);
+    outgoingTangent = normalize(outgoingTangent);
+    RI_ASSERT(!isZero(incomingTangent) && !isZero(outgoingTangent));
+
+    const int segments = RI_NUM_TESSELLATED_SEGMENTS_ARC;
+    Vector2 pp = p0;
+    Vector2 tp = incomingTangent;
+    unsigned int prevFlags = startFlags;
+    for(int i=1;i<segments;i++)
+    {
+        RIfloat t = (RIfloat)i / (RIfloat)segments;
+        Vector2 pn = circularLerp(u0, u1, t, cw);
+        Vector2 tn = perpendicular(pn, cw);
+        tn = affineTangentTransform(unitCircleToEllipse, tn);
+        pn = affineTransform(unitCircleToEllipse, pn) + p0;
+        tn = normalize(tn);
+        if(isZero(tn))
+            tn = tp;
+
+        addEdge(pp, pn, tp, tn, prevFlags, 0);  //throws bad_alloc
+
+        pp = pn;
+        tp = tn;
+        prevFlags = 0;
+    }
+    addEdge(pp, p1, tp, outgoingTangent, prevFlags, END_SEGMENT);   //throws bad_alloc
+    return true;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Tessellates a path.
+* \param    
+* \return   
+* \note     tessellation output format: A list of vertices describing the
+*           path tessellated into line segments and relevant aspects of the
+*           input data. Each path segment has a start vertex, a number of
+*           internal vertices (possibly zero), and an end vertex. The start
+*           and end of segments and subpaths have been flagged, as well as
+*           implicit and explicit close subpath segments.
+*//*-------------------------------------------------------------------*/
+
+void Path::tessellate(const Matrix3x3& pathToSurface, float strokeWidth)
+{
+    m_vertices.clear();
+
+    m_userMinx = RI_FLOAT_MAX;
+    m_userMiny = RI_FLOAT_MAX;
+    m_userMaxx = -RI_FLOAT_MAX;
+    m_userMaxy = -RI_FLOAT_MAX;
+    
+    try
+    {
+        m_segmentToVertex.resize(m_segments.size());
+
+        int coordIndex = 0;
+        Vector2 s(0,0);     //the beginning of the current subpath
+        Vector2 o(0,0);     //the last point of the previous segment
+        Vector2 p(0,0);     //the last internal control point of the previous segment, if the segment was a (regular or smooth) quadratic or cubic Bezier, or else the last point of the previous segment
+
+        //tessellate the path segments
+        coordIndex = 0;
+        s.set(0,0);
+        o.set(0,0);
+        p.set(0,0);
+        bool subpathHasGeometry = false;
+        VGPathSegment prevSegment = VG_MOVE_TO;
+        for(int i=0;i<m_segments.size();i++)
+        {
+            VGPathSegment segment = getPathSegment(m_segments[i]);
+            VGPathAbsRel absRel = getPathAbsRel(m_segments[i]);
+            int coords = segmentToNumCoordinates(segment);
+            m_segmentToVertex[i].start = m_vertices.size();
+
+            switch(segment)
+            {
+            case VG_CLOSE_PATH:
+            {
+                RI_ASSERT(coords == 0);
+                addEndPath(pathToSurface, o, s, subpathHasGeometry, CLOSE_SUBPATH);
+                p = s;
+                o = s;
+                subpathHasGeometry = false;
+                break;
+            }
+
+            case VG_MOVE_TO:
+            {
+                RI_ASSERT(coords == 2);
+                Vector2 c(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                if(absRel == VG_RELATIVE)
+                    c += o;
+                if(prevSegment != VG_MOVE_TO && prevSegment != VG_CLOSE_PATH)
+                    addEndPath(pathToSurface, o, s, subpathHasGeometry, IMPLICIT_CLOSE_SUBPATH);
+                s = c;
+                p = c;
+                o = c;
+                subpathHasGeometry = false;
+                break;
+            }
+
+            case VG_LINE_TO:
+            {
+                RI_ASSERT(coords == 2);
+                Vector2 c(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                if(absRel == VG_RELATIVE)
+                    c += o;
+                if(addLineTo(pathToSurface, o, c, subpathHasGeometry))
+                    subpathHasGeometry = true;
+                p = c;
+                o = c;
+                break;
+            }
+
+            case VG_HLINE_TO:
+            {
+                RI_ASSERT(coords == 1);
+                Vector2 c(getCoordinate(coordIndex+0), o.y);
+                if(absRel == VG_RELATIVE)
+                    c.x += o.x;
+                if(addLineTo(pathToSurface, o, c, subpathHasGeometry))
+                    subpathHasGeometry = true;
+                p = c;
+                o = c;
+                break;
+            }
+
+            case VG_VLINE_TO:
+            {
+                RI_ASSERT(coords == 1);
+                Vector2 c(o.x, getCoordinate(coordIndex+0));
+                if(absRel == VG_RELATIVE)
+                    c.y += o.y;
+                if(addLineTo(pathToSurface, o, c, subpathHasGeometry))
+                    subpathHasGeometry = true;
+                p = c;
+                o = c;
+                break;
+            }
+
+            case VG_QUAD_TO:
+            {
+                RI_ASSERT(coords == 4);
+                Vector2 c0(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                Vector2 c1(getCoordinate(coordIndex+2), getCoordinate(coordIndex+3));
+                if(absRel == VG_RELATIVE)
+                {
+                    c0 += o;
+                    c1 += o;
+                }
+                if(addQuadTo(pathToSurface, o, c0, c1, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c0;
+                o = c1;
+                break;
+            }
+
+            case VG_SQUAD_TO:
+            {
+                RI_ASSERT(coords == 2);
+                Vector2 c0 = 2.0f * o - p;
+                Vector2 c1(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                if(absRel == VG_RELATIVE)
+                    c1 += o;
+                if(addQuadTo(pathToSurface, o, c0, c1, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c0;
+                o = c1;
+                break;
+            }
+
+            case VG_CUBIC_TO:
+            {
+                RI_ASSERT(coords == 6);
+                Vector2 c0(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                Vector2 c1(getCoordinate(coordIndex+2), getCoordinate(coordIndex+3));
+                Vector2 c2(getCoordinate(coordIndex+4), getCoordinate(coordIndex+5));
+                if(absRel == VG_RELATIVE)
+                {
+                    c0 += o;
+                    c1 += o;
+                    c2 += o;
+                }
+                if(addCubicTo(pathToSurface, o, c0, c1, c2, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c1;
+                o = c2;
+                break;
+            }
+
+            case VG_SCUBIC_TO:
+            {
+                RI_ASSERT(coords == 4);
+                Vector2 c0 = 2.0f * o - p;
+                Vector2 c1(getCoordinate(coordIndex+0), getCoordinate(coordIndex+1));
+                Vector2 c2(getCoordinate(coordIndex+2), getCoordinate(coordIndex+3));
+                if(absRel == VG_RELATIVE)
+                {
+                    c1 += o;
+                    c2 += o;
+                }
+                if(addCubicTo(pathToSurface, o, c0, c1, c2, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c1;
+                o = c2;
+                break;
+            }
+
+            default:
+            {
+                RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO ||
+                          segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO);
+                RI_ASSERT(coords == 5);
+                RIfloat rh = getCoordinate(coordIndex+0);
+                RIfloat rv = getCoordinate(coordIndex+1);
+                RIfloat rot = getCoordinate(coordIndex+2);
+                Vector2 c(getCoordinate(coordIndex+3), getCoordinate(coordIndex+4));
+
+                Vector2 cr = c;
+                if(absRel == VG_ABSOLUTE)
+                    cr -= o;
+                else
+                    c += o;
+
+                if(addArcTo(pathToSurface, o, rh, rv, rot, c, cr, segment, subpathHasGeometry, strokeWidth))
+                    subpathHasGeometry = true;
+                p = c;
+                o = c;
+                break;
+            }
+            }
+
+            if(m_vertices.size() > m_segmentToVertex[i].start)
+            {   //segment produced vertices
+                m_segmentToVertex[i].end = m_vertices.size() - 1;
+            }
+            else
+            {   //segment didn't produce vertices (zero-length segment). Ignore it.
+                m_segmentToVertex[i].start = m_segmentToVertex[i].end = m_vertices.size()-1;
+            }
+            prevSegment = segment;
+            coordIndex += coords;
+        }
+
+        //add an implicit MOVE_TO to the end to close the last subpath.
+        //if the subpath contained only zero-length segments, this produces the necessary geometry to get it stroked
+        // and included in path bounds. The geometry won't be included in the pointAlongPath query.
+        if(prevSegment != VG_MOVE_TO && prevSegment != VG_CLOSE_PATH)
+            addEndPath(pathToSurface, o, s, subpathHasGeometry, IMPLICIT_CLOSE_SUBPATH);
+
+        //check that the flags are correct
+#ifdef RI_DEBUG
+        int prev = -1;
+        bool subpathStarted = false;
+        bool segmentStarted = false;
+        for(int i=0;i<m_vertices.size();i++)
+        {
+            Vertex& v = m_vertices[i];
+
+            if(v.flags & START_SUBPATH)
+            {
+                RI_ASSERT(!subpathStarted);
+                RI_ASSERT(v.flags & START_SEGMENT);
+                RI_ASSERT(!(v.flags & END_SUBPATH));
+                RI_ASSERT(!(v.flags & END_SEGMENT));
+                RI_ASSERT(!(v.flags & CLOSE_SUBPATH));
+                RI_ASSERT(!(v.flags & IMPLICIT_CLOSE_SUBPATH));
+                subpathStarted = true;
+            }
+            
+            if(v.flags & START_SEGMENT)
+            {
+                RI_ASSERT(subpathStarted || (v.flags & CLOSE_SUBPATH) || (v.flags & IMPLICIT_CLOSE_SUBPATH));
+                RI_ASSERT(!segmentStarted);
+                RI_ASSERT(!(v.flags & END_SUBPATH));
+                RI_ASSERT(!(v.flags & END_SEGMENT));
+                segmentStarted = true;
+            }
+            
+            if( v.flags & CLOSE_SUBPATH )
+            {
+                RI_ASSERT(segmentStarted);
+                RI_ASSERT(!subpathStarted);
+                RI_ASSERT((v.flags & START_SEGMENT) || (v.flags & END_SEGMENT));
+                RI_ASSERT(!(v.flags & IMPLICIT_CLOSE_SUBPATH));
+                RI_ASSERT(!(v.flags & START_SUBPATH));
+                RI_ASSERT(!(v.flags & END_SUBPATH));
+            }
+            if( v.flags & IMPLICIT_CLOSE_SUBPATH )
+            {
+                RI_ASSERT(segmentStarted);
+                RI_ASSERT(!subpathStarted);
+                RI_ASSERT((v.flags & START_SEGMENT) || (v.flags & END_SEGMENT));
+                RI_ASSERT(!(v.flags & CLOSE_SUBPATH));
+                RI_ASSERT(!(v.flags & START_SUBPATH));
+                RI_ASSERT(!(v.flags & END_SUBPATH));
+            }
+            
+            if( prev >= 0 )
+            {
+                RI_ASSERT(segmentStarted);
+                RI_ASSERT(subpathStarted || ((m_vertices[prev].flags & CLOSE_SUBPATH) && (m_vertices[i].flags & CLOSE_SUBPATH)) ||
+                          ((m_vertices[prev].flags & IMPLICIT_CLOSE_SUBPATH) && (m_vertices[i].flags & IMPLICIT_CLOSE_SUBPATH)));
+            }
+
+            prev = i;
+            if(v.flags & END_SEGMENT)
+            {
+                RI_ASSERT(subpathStarted || (v.flags & CLOSE_SUBPATH) || (v.flags & IMPLICIT_CLOSE_SUBPATH));
+                RI_ASSERT(segmentStarted);
+                RI_ASSERT(!(v.flags & START_SUBPATH));
+                RI_ASSERT(!(v.flags & START_SEGMENT));
+                segmentStarted = false;
+                prev = -1;
+            }
+            
+            if(v.flags & END_SUBPATH)
+            {
+                RI_ASSERT(subpathStarted);
+                RI_ASSERT(v.flags & END_SEGMENT);
+                RI_ASSERT(!(v.flags & START_SUBPATH));
+                RI_ASSERT(!(v.flags & START_SEGMENT));
+                RI_ASSERT(!(v.flags & CLOSE_SUBPATH));
+                RI_ASSERT(!(v.flags & IMPLICIT_CLOSE_SUBPATH));
+                subpathStarted = false;
+            }
+        }
+#endif  //RI_DEBUG
+    }
+    catch(std::bad_alloc)
+    {
+        m_vertices.clear();
+        throw;
+    }
+}
+
+//==============================================================================================
+
+}       //namespace OpenVGRI
+
+//==============================================================================================
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riPath.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,192 @@
+#ifndef __RIPATH_H
+#define __RIPATH_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Path class.
+ * \note	
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _OPENVG_H
+#include "openvg.h"
+#endif
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#ifndef __RIRASTERIZER_H
+#include "riRasterizer.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Storage and operations for VGPath.
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+class Path
+{
+public:
+	Path(VGint format, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int segmentCapacityHint, int coordCapacityHint, VGbitfield caps);	//throws bad_alloc
+	~Path();
+
+	VGint				getFormat() const						{ return m_format; }
+	VGPathDatatype		getDatatype() const						{ return m_datatype; }
+	RIfloat				getScale() const						{ return m_scale; }
+	RIfloat				getBias() const							{ return m_bias; }
+	VGbitfield			getCapabilities() const					{ return m_capabilities; }
+	void				setCapabilities(VGbitfield caps)		{ m_capabilities = caps; }
+	int					getNumSegments() const					{ return m_segments.size(); }
+	int					getNumCoordinates() const				{ return m_data.size() / getBytesPerCoordinate(m_datatype); }
+	void				addReference()							{ m_referenceCount++; }
+	int					removeReference()						{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+
+	void				clear(VGbitfield capabilities);
+	void				appendData(const RIuint8* segments, int numSegments, const RIuint8* data);	//throws bad_alloc
+	void				append(const Path* srcPath);	//throws bad_alloc
+	void				modifyCoords(int startIndex, int numSegments, const RIuint8* data);
+	void				transform(const Path* srcPath, const Matrix3x3& matrix);	//throws bad_alloc
+	//returns true if interpolation succeeds, false if start and end paths are not compatible
+	bool				interpolate(const Path* startPath, const Path* endPath, RIfloat amount);	//throws bad_alloc
+	void				fill(const Matrix3x3& pathToSurface, Rasterizer& rasterizer);	//throws bad_alloc
+	void				stroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const Array<RIfloat>& dashPattern, RIfloat dashPhase, bool dashPhaseReset, RIfloat strokeWidth, VGCapStyle capStyle, VGJoinStyle joinStyle, RIfloat miterLimit);	//throws bad_alloc
+
+	void				getPointAlong(int startIndex, int numSegments, RIfloat distance, Vector2& p, Vector2& t);	//throws bad_alloc
+	RIfloat				getPathLength(int startIndex, int numSegments);	//throws bad_alloc
+	void				getPathBounds(RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy);	//throws bad_alloc
+	void				getPathTransformedBounds(const Matrix3x3& pathToSurface, RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy);	//throws bad_alloc
+    int                 coordsSizeInBytes( int startIndex, int numSegments );
+
+private:
+	enum VertexFlags
+	{
+		START_SUBPATH			= (1<<0),
+		END_SUBPATH				= (1<<1),
+		START_SEGMENT			= (1<<2),
+		END_SEGMENT				= (1<<3),
+		CLOSE_SUBPATH			= (1<<4),
+		IMPLICIT_CLOSE_SUBPATH	= (1<<5)
+	};
+	struct Vertex
+	{
+		Vertex() : userPosition(), userTangent(), pathLength(0.0f), flags(0) {}
+		Vector2			userPosition;
+		Vector2			userTangent;
+		RIfloat			pathLength;
+		unsigned int	flags;
+	};
+	struct StrokeVertex
+	{
+		StrokeVertex() : p(), t(), ccw(), cw(), pathLength(0.0f), flags(0), inDash(false) {}
+		Vector2			p;
+		Vector2			t;
+		Vector2			ccw;
+		Vector2			cw;
+		RIfloat			pathLength;
+		unsigned int	flags;
+		bool			inDash;
+	};
+
+	Path(const Path&);						//!< Not allowed.
+	const Path& operator=(const Path&);		//!< Not allowed.
+
+	static VGPathSegment getPathSegment(RIuint8 data)				{ return (VGPathSegment)(data & 0x1e); }
+	static VGPathAbsRel	getPathAbsRel(RIuint8 data)					{ return (VGPathAbsRel)(data & 0x1); }
+	static int			segmentToNumCoordinates(VGPathSegment segment);
+	static int			countNumCoordinates(const RIuint8* segments, int numSegments);
+	static int			getBytesPerCoordinate(VGPathDatatype datatype);
+
+	static void			setCoordinate(Array<RIuint8>& data, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int i, RIfloat c);
+
+	RIfloat				getCoordinate(int i) const;
+	void				setCoordinate(int i, RIfloat c)				{ setCoordinate(m_data, m_datatype, m_scale, m_bias, i, c); }
+
+	void				addVertex(const Vector2& p, const Vector2& t, RIfloat pathLength, unsigned int flags);	//throws bad_alloc
+	void				addEdge(const Vector2& p0, const Vector2& p1, const Vector2& t0, const Vector2& t1, unsigned int startFlags, unsigned int endFlags);	//throws bad_alloc
+
+	void				addEndPath(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry, unsigned int flags);	//throws bad_alloc
+	bool				addLineTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry);	//throws bad_alloc
+	bool				addQuadTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, bool subpathHasGeometry, float strokeWidth);	//throws bad_alloc
+	bool				addCubicTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3, bool subpathHasGeometry, float strokeWidth);	//throws bad_alloc
+	bool				addArcTo(const Matrix3x3& pathToSurface, const Vector2& p0, RIfloat rh, RIfloat rv, RIfloat rot, const Vector2& p1, const Vector2& p1r, VGPathSegment segment, bool subpathHasGeometry, float strokeWidth);	//throws bad_alloc
+
+	void				tessellate(const Matrix3x3& pathToSurface, float strokeWidth);	//throws bad_alloc
+
+	void				normalizeForInterpolation(const Path* srcPath);	//throws bad_alloc
+
+	void				interpolateStroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth) const;	//throws bad_alloc
+	void				doCap(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v, RIfloat strokeWidth, VGCapStyle capStyle) const;	//throws bad_alloc
+	void				doJoin(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth, VGJoinStyle joinStyle, RIfloat miterLimit) const;	//throws bad_alloc
+
+	//input data
+	VGint				m_format;
+	VGPathDatatype		m_datatype;
+	RIfloat				m_scale;
+	RIfloat				m_bias;
+	VGbitfield			m_capabilities;
+	int					m_referenceCount;
+	Array<RIuint8>		m_segments;
+	Array<RIuint8>		m_data;
+
+	//data produced by tessellation
+	struct VertexIndex
+	{
+		int		start;
+		int		end;
+	};
+	Array<Vertex>		m_vertices;
+    int                 m_numTessVertices;
+	Array<VertexIndex>	m_segmentToVertex;
+	RIfloat				m_userMinx;
+	RIfloat				m_userMiny;
+	RIfloat				m_userMaxx;
+	RIfloat				m_userMaxy;
+
+    bool                m_mirror;
+};
+
+//==============================================================================================
+
+}	//namespace OpenVGRI
+
+//==============================================================================================
+
+#endif /* __RIPATH_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riPixelPipe.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1440 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief   Implementation of Paint and pixel pipe functionality.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+#ifndef __RIRASTERIZER_H
+#   include "riRasterizer.h"
+#endif
+#ifndef __SFDYNAMICPIXELPIPE_H
+#   include "sfDynamicPixelPipe.h"
+#endif
+#ifndef __SFCOMPILER_H
+#   include "sfCompiler.h"
+#endif
+
+//==============================================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Paint constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Paint::Paint() :
+    m_paintType(VG_PAINT_TYPE_COLOR),
+    m_paintColor(0,0,0,1,Color::sRGBA_PRE),
+    m_inputPaintColor(0,0,0,1,Color::sRGBA),
+    m_colorRampSpreadMode(VG_COLOR_RAMP_SPREAD_PAD),
+    m_colorRampStops(),
+    m_inputColorRampStops(),
+    m_colorRampPremultiplied(VG_TRUE),
+    m_inputLinearGradientPoint0(0,0),
+    m_inputLinearGradientPoint1(1,0),
+    m_inputRadialGradientCenter(0,0),
+    m_inputRadialGradientFocalPoint(0,0),
+    m_inputRadialGradientRadius(1.0f),
+    m_linearGradientPoint0(0,0),
+    m_linearGradientPoint1(1,0),
+    m_radialGradientCenter(0,0),
+    m_radialGradientFocalPoint(0,0),
+    m_radialGradientRadius(1.0f),
+    m_patternTilingMode(VG_TILE_FILL),
+    m_pattern(NULL),
+    m_referenceCount(0),
+    m_lutFormat((VGImageFormat)-1),
+    m_gradientStopsChanged(true)
+{
+    Paint::GradientStop gs;
+    gs.offset = 0.0f;
+    gs.color.set(0,0,0,1,Color::sRGBA);
+    m_colorRampStops.push_back(gs); //throws bad_alloc
+    gs.offset = 1.0f;
+    gs.color.set(1,1,1,1,Color::sRGBA);
+    m_colorRampStops.push_back(gs); //throws bad_alloc
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Paint destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Paint::~Paint()
+{
+    RI_ASSERT(m_referenceCount == 0);
+    if(m_pattern)
+    {
+        m_pattern->removeInUse();
+        if(!m_pattern->removeReference())
+            RI_DELETE(m_pattern);
+    }
+}
+
+static Color readStopColor(const Array<Paint::GradientStop>& colorRampStops, int i, VGboolean colorRampPremultiplied)
+{
+    RI_ASSERT(i >= 0 && i < colorRampStops.size());
+    Color c = colorRampStops[i].color;
+    RI_ASSERT(c.getInternalFormat() == Color::sRGBA);
+    if(colorRampPremultiplied)
+        c.premultiply();
+    return c;
+}
+
+void Paint::setGradientStops(Array<GradientStop>& inputStops, Array<GradientStop>& stops)
+{
+    m_colorRampStops.swap(stops);
+    m_inputColorRampStops.swap(inputStops);
+    m_gradientStopsChanged = true;
+}
+
+void Paint::setLinearGradient(const Vector2& p0, const Vector2& p1)
+{
+    m_linearGradientPoint0 = p0;
+    m_linearGradientPoint1 = p1;
+}
+
+void Paint::setRadialGradient(const Vector2& c, const Vector2& f, VGfloat r)
+{
+    m_radialGradientCenter = c;
+    m_radialGradientFocalPoint = f;
+    m_radialGradientRadius = r;
+}
+
+bool Paint::linearDegenerate() const
+{
+    return m_linearGradientPoint0 == m_linearGradientPoint1 ? true : false;
+}
+
+bool Paint::radialDegenerate() const
+{
+    return m_radialGradientRadius == 0.0f ? true : false;
+}
+
+/**
+ * \brief   Returns either the VG_PAINT_COLOR, or evaluated gradient value when the
+ *          gradient is degenerate.
+ */
+Color Paint::getSolidColor() const
+{
+    if (m_paintType == VG_PAINT_TYPE_PATTERN)
+    {
+        RI_ASSERT(m_pattern == NULL);
+        return m_paintColor;
+    }
+
+    if (m_paintType == VG_PAINT_TYPE_COLOR)
+        return m_paintColor;
+
+    RI_ASSERT(linearDegenerate() || radialDegenerate());
+
+    // Determine the color at the end of the gradient
+    RIfloat gs, ge;
+    if (m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_PAD)
+    {
+        gs = 1.0f - 1/256.0f;
+        ge = 1.0f;
+    } else if (m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT)
+    {
+        gs = 0.0f;
+        ge = 1/256.0f;
+    } else
+    {
+        gs = 1.0f - 1/256.0f;
+        ge = 1.0f;
+    }
+    Color c = integrateColorRamp(gs, ge);
+    return c * 256.0f;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Returns the average color within an offset range in the color ramp.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Paint::integrateColorRamp(RIfloat gmin, RIfloat gmax) const
+{
+    RI_ASSERT(gmin <= gmax);
+    RI_ASSERT(gmin >= 0.0f && gmin <= 1.0f);
+    RI_ASSERT(gmax >= 0.0f && gmax <= 1.0f);
+    RI_ASSERT(m_colorRampStops.size() >= 2);   //there are at least two stops
+
+    Color currC(0,0,0,0,m_colorRampPremultiplied ? Color::sRGBA_PRE : Color::sRGBA);
+
+    if(gmin == 1.0f || gmax == 0.0f)
+        return currC;
+
+    int i = 0;
+
+    for(; i < m_colorRampStops.size()-1; i++)
+    {
+        if(gmin >= m_colorRampStops[i].offset && gmin < m_colorRampStops[i+1].offset)
+        {
+            RIfloat s = m_colorRampStops[i].offset;
+            RIfloat e = m_colorRampStops[i+1].offset;
+            RI_ASSERT(s < e);
+            RIfloat g = (gmin - s) / (e - s);
+
+            Color sc = readStopColor(m_colorRampStops, i, m_colorRampPremultiplied);
+            Color ec = readStopColor(m_colorRampStops, i+1, m_colorRampPremultiplied);
+            Color rc = (1.0f-g) * sc + g * ec;
+
+            //subtract the average color from the start of the stop to gmin
+            Color dc = 0.5f*(gmin - s)*(sc + rc);
+            currC -= dc; 
+            break;
+        }
+    }
+
+    for(;i < m_colorRampStops.size()-1; i++)
+    {
+        RIfloat s = m_colorRampStops[i].offset;
+        RIfloat e = m_colorRampStops[i+1].offset;
+        RI_ASSERT(s <= e);
+
+        Color sc = readStopColor(m_colorRampStops, i, m_colorRampPremultiplied);
+        Color ec = readStopColor(m_colorRampStops, i+1, m_colorRampPremultiplied);
+
+        //average of the stop
+        Color dc = 0.5f*(e-s)*(sc + ec);
+        currC += dc; 
+
+        if(gmax >= m_colorRampStops[i].offset && gmax < m_colorRampStops[i+1].offset)
+        {
+            RIfloat g = (gmax - s) / (e - s);
+            Color rc = (1.0f-g) * sc + g * ec;
+
+            //subtract the average color from gmax to the end of the stop
+            dc = 0.5f*(e - gmax)*(rc + ec);
+            currC -= dc;
+            break;
+        }
+    }
+
+    return currC;
+}
+
+/**
+ * \brief   Generates gradient color-ramp lookup values.
+ *
+ * \param   targetFormat    Destination or image format to associate LUT with.
+ * \patam   drawImage       true if paint is evaluated along drawImage.
+ *
+ * \note    Must be called prior to rendering, and after the destination
+ *          format is known. The destination format is either destination 
+ *          surface format, or the image format in case of image rendering
+ *          operation.
+ */
+void Paint::generateLUT(PixelPipe& pipe, VGImageFormat preferredFormat)
+{
+    const RIfloat gstep = 1.0f / (GRADIENT_LUT_COUNT);
+    const RIfloat rcp = (RIfloat)(GRADIENT_LUT_COUNT);
+    RIfloat gsx;
+    gsx = 0.0f;
+    
+    if (!pipe.colorTransformChanged() && !m_gradientStopsChanged && (preferredFormat == m_lutFormat))
+        return; // Already in correct format
+
+    const bool inputPremultiplied = m_colorRampPremultiplied == VG_TRUE ? true : false;
+
+    // Colortransform premultiplies color.
+    const Color::Descriptor srcDesc = Color::formatToDescriptorConst(
+        inputPremultiplied || pipe.hasColorTransform() ? VG_sRGBA_8888_PRE : VG_sRGBA_8888);
+
+    const Color::Descriptor dstDesc = Color::formatToDescriptorConst(preferredFormat);
+
+    // Create a pre-calculated LUT.
+    for (int i = 0; i < GRADIENT_LUT_COUNT; i++)
+    {
+        // \todo Open up the integrator and/or use also integers.
+        Color c = integrateColorRamp(gsx, gsx + gstep);
+        c *= rcp;
+
+        // \todo Changing the mode must be tracked somehow!
+        if (pipe.getImageMode() != VG_DRAW_IMAGE_MULTIPLY)
+            pipe.colorTransform(c);
+
+        IntegerColor ic = IntegerColor(c);
+        ic.convertToFrom(dstDesc, srcDesc, false);
+        m_gradientLUT[i] = ic;
+
+        gsx += gstep;
+    }
+
+    m_gradientStopsChanged = false;
+    m_lutFormat = Color::descriptorToVGImageFormat(dstDesc);
+    pipe.setColorTransformChanged(false);
+
+    RI_ASSERT(m_lutFormat == preferredFormat);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    PixelPipe constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+PixelPipe::PixelPipe() :
+    m_drawable(NULL),
+    m_image(NULL),
+    m_paint(NULL),
+    m_defaultPaint(),
+    m_blendMode(VG_BLEND_SRC_OVER),
+    m_imageMode(VG_DRAW_IMAGE_NORMAL),
+    m_imageQuality(VG_IMAGE_QUALITY_FASTER),
+    m_tileFillColor(0,0,0,0,Color::sRGBA),
+    m_colorTransform(false),
+    m_colorTransformValues(),
+    m_iColorTransformValues(),
+    m_surfaceToPaintMatrix(),
+    m_surfaceToImageMatrix(),
+    m_paintToSurfaceMatrix(),
+    m_maskOperation(VG_SET_MASK),
+    m_renderToMask(false),
+    m_colorTransformChanged(true)
+{
+    for(int i=0;i<8;i++)
+    {
+        m_colorTransformValues[i] = (i < 4) ? 1.0f : 0.0f;
+        m_iColorTransformValues[i] = (i < 4) ? (COLOR_TRANSFORM_ONE) : 0;
+    }
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief    PixelPipe destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+PixelPipe::~PixelPipe()
+{
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the rendering surface.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setDrawable(Drawable* drawable)
+{
+    RI_ASSERT(drawable);
+    m_drawable = drawable;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the blend mode.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setBlendMode(VGBlendMode blendMode)
+{
+    RI_ASSERT(blendMode >= VG_BLEND_SRC && blendMode <= VG_BLEND_ADDITIVE);
+    m_blendMode = blendMode;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the mask image. NULL disables masking.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setMask(bool masking)
+{
+    m_masking = masking;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the image to be drawn. NULL disables image drawing.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setImage(Image* image, VGImageMode imageMode)
+{
+    RI_ASSERT(imageMode == VG_DRAW_IMAGE_NORMAL || imageMode == VG_DRAW_IMAGE_MULTIPLY || imageMode == VG_DRAW_IMAGE_STENCIL);
+    m_image = image;
+    m_imageMode = imageMode;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the surface-to-paint matrix.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setSurfaceToPaintMatrix(const Matrix3x3& surfaceToPaintMatrix)
+{
+    m_surfaceToPaintMatrix = surfaceToPaintMatrix;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets the surface-to-image matrix.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setSurfaceToImageMatrix(const Matrix3x3& surfaceToImageMatrix)
+{
+    m_surfaceToImageMatrix = surfaceToImageMatrix;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets image quality.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setImageQuality(VGImageQuality imageQuality)
+{
+    RI_ASSERT(imageQuality == VG_IMAGE_QUALITY_NONANTIALIASED || imageQuality == VG_IMAGE_QUALITY_FASTER || imageQuality == VG_IMAGE_QUALITY_BETTER);
+    m_imageQuality = imageQuality;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets fill color for VG_TILE_FILL tiling mode (pattern only).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setTileFillColor(const Color& c)
+{
+    m_tileFillColor = c;
+    m_tileFillColor.clamp();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Sets paint.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setPaint(Paint* paint)
+{
+    // \temp Only call this right before filling a polygon.
+    m_paint = paint;
+
+    if(!m_paint)
+        m_paint = &m_defaultPaint;
+
+    if(m_paint->m_pattern)
+        m_tileFillColor.convert(m_paint->m_pattern->getDescriptor().internalFormat);
+
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Color transform.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::setColorTransform(bool enable, RIfloat values[8])
+{
+    m_colorTransform = enable;
+    for(int i=0;i<4;i++)
+    {
+        m_colorTransformValues[i] = RI_CLAMP(values[i], -127.0f, 127.0f);
+        m_colorTransformValues[i+4] = RI_CLAMP(values[i+4], -1.0f, 1.0f);
+        m_iColorTransformValues[i] = RI_ROUND_TO_INT(m_colorTransformValues[i]*(RIfloat)COLOR_TRANSFORM_ONE);
+        m_iColorTransformValues[i+4] = RI_ROUND_TO_INT(m_colorTransformValues[i+4]*255.0f);
+    }
+    m_colorTransformChanged = true;
+}
+
+const Image* PixelPipe::getRenderTargetImage() const
+{
+    if (m_renderToMask)
+        return m_drawable->getMaskBuffer()->getImage();
+
+    return m_drawable->getColorBuffer()->getImage();
+}
+
+/**
+ * \brief   Determine an appropriate VGImageFormat to use for lookup tables.
+ * \todo    Should return descriptor instead?
+ */
+VGImageFormat PixelPipe::getPreferredLUTFormat() const
+{
+    const Image* target = getRenderTargetImage();
+    const Color::Descriptor& targetDesc = target->getDescriptor();
+
+    if (m_renderToMask)
+    {
+        RI_ASSERT(!m_image);
+        if (targetDesc.isNonlinear())
+            return VG_sRGBA_8888_PRE;
+        else
+            return VG_lRGBA_8888_PRE;
+    }
+
+    if (m_image && m_imageMode == VG_DRAW_IMAGE_MULTIPLY)
+        return VG_sRGBA_8888_PRE; // ?
+
+    // Prefer premultiplied formats
+    // \note Can also generate non-premultiplied if no sampling/other operation and destination
+    // is in linear format.
+    // \note Do not use VGImageFormat, because using (s/l)LA88 is possible with
+    // luminance destination formats.
+    if (targetDesc.isNonlinear())
+        return VG_sRGBA_8888_PRE;
+    else
+        return VG_lRGBA_8888_PRE;
+}
+
+void PixelPipe::prepareSolidFill()
+{
+    if (!(m_drawable && m_paint))
+        return;
+        
+    Color c = m_paint->getSolidColor();
+    //Color c = m_paint->m_paintColor;
+    
+    if (!m_image || m_imageMode != VG_DRAW_IMAGE_MULTIPLY)
+        colorTransform(c); // Output will be premultiplied
+    // Generate internal color
+    Color::Descriptor blendDesc = getRenderTargetImage()->getDescriptor();
+
+    // MULTIPLY uses the color as-is.
+    if (m_imageMode != VG_DRAW_IMAGE_MULTIPLY) c.convert(blendDesc.internalFormat);
+
+    IntegerColor ic = IntegerColor(c);
+    blendDesc.internalFormat = (Color::InternalFormat)(blendDesc.internalFormat | (Color::PREMULTIPLIED));
+
+    if (m_imageMode != VG_DRAW_IMAGE_MULTIPLY) c.convert(blendDesc.internalFormat);
+    
+    IntegerColor blendColor = IntegerColor(c);
+
+    if (m_imageMode == VG_DRAW_IMAGE_STENCIL)
+        blendColor.asFixedPoint(c); // Enhance the precision a bit
+    
+    // \todo No need to pack the color if solid fill is not possible
+    if (!m_renderToMask)
+        ic.truncateColor(getRenderTargetImage()->getDescriptor());
+    else
+        ic.truncateMask(getRenderTargetImage()->getDescriptor());
+
+    RIuint32 p = ic.getPackedColor(getRenderTargetImage()->getDescriptor());
+
+    m_spanUniforms.solidColor = blendColor; // This must be premultiplied
+    m_spanUniforms.packedSolidColor = p; // This must be exactly the dst color
+}
+
+void PixelPipe::prepareCoverageFill()
+{
+    IntegerColor ic = IntegerColor(255, 255, 255, 255);
+    RIuint32 p = ic.getPackedColor(m_drawable->getMaskBuffer()->getDescriptor());
+
+    m_spanUniforms.solidColor = ic;
+    m_spanUniforms.packedSolidColor = p;
+}
+
+void PixelPipe::prepareLinearGradient()
+{
+    const Matrix3x3& s2p = m_surfaceToPaintMatrix;
+
+    Vector2 zero(0,0);
+    Vector2 p0 = m_paint->m_linearGradientPoint0;
+    Vector2 p1 = m_paint->m_linearGradientPoint1;
+    Vector2 delta = p1 - p0;
+
+    zero = affineTransform(s2p, zero);
+
+    RIfloat d = (delta.x * delta.x) + (delta.y * delta.y);
+    RIfloat gdx = (s2p[0][0] * delta.x + s2p[1][0] * delta.y) / d;
+    RIfloat gdy = (s2p[0][1] * delta.x + s2p[1][1] * delta.y) / d;
+    RIfloat cx = (zero.x-p0.x) * (delta.x);
+    RIfloat cy = (zero.y-p0.y) * (delta.y);
+    RIfloat c = (cx + cy) / d;
+
+    m_spanUniforms.dgdx = RI_FLOAT_TO_FX(gdx, PixelPipe::GRADIENT_BITS);
+    m_spanUniforms.dgdy = RI_FLOAT_TO_FX(gdy, PixelPipe::GRADIENT_BITS);
+    m_spanUniforms.lgc = RI_FLOAT_TO_FX(c + 0.5*(gdx + gdy), PixelPipe::GRADIENT_BITS);
+
+    m_spanUniforms.gradientLookup = m_paint->getGradientLUT();
+}
+
+void PixelPipe::prepareRadialGradient()
+{
+    const Matrix3x3& s2p = m_surfaceToPaintMatrix;
+
+    Vector2 c = m_paint->m_radialGradientCenter;
+    Vector2 f = m_paint->m_radialGradientFocalPoint;
+    RGScalar r = m_paint->m_radialGradientRadius;
+
+    Vector2 zero(0,0);
+    Vector2 pzero = affineTransform(s2p, zero);
+
+    Vector2 fp = f - c;
+
+    RGScalar q = fp.length();
+
+    if (q > r)
+    {
+        const RIfloat scale = 0.99f;
+        fp.normalize();
+        fp *= r * scale;
+        f = fp + c;
+    } 
+
+    RGScalar r1sqr = RI_SQR(r);
+    RGScalar d = r1sqr - dot(fp, fp);
+
+    m_spanUniforms.rdxdx = s2p[0][0];
+    m_spanUniforms.rdxdy = s2p[0][1];
+    m_spanUniforms.rdydx = s2p[1][0];
+    m_spanUniforms.rdydy = s2p[1][1];
+
+    m_spanUniforms.rsqrp = r1sqr / RI_SQR(d);
+    m_spanUniforms.rfxp = fp.x / d;
+    m_spanUniforms.rfyp = fp.y / d;
+    m_spanUniforms.rx0 = pzero.x - f.x + 0.5f*(m_spanUniforms.rdxdx + m_spanUniforms.rdxdy);
+    m_spanUniforms.ry0 = pzero.y - f.y + 0.5f*(m_spanUniforms.rdydy + m_spanUniforms.rdydx);
+
+    m_spanUniforms.gradientLookup = m_paint->getGradientLUT();
+}
+
+void PixelPipe::preparePattern()
+{
+    // Patterns only support affine transforms
+    const Matrix3x3& s2p = m_surfaceToPaintMatrix;
+    const RIfloat patternWidth = (RIfloat)m_paint->m_pattern->getWidth();
+    const RIfloat patternHeight = (RIfloat)m_paint->m_pattern->getHeight();
+    const Vector2 zero(0, 0);
+    Vector2 pzero = affineTransform(s2p, zero); 
+
+    m_spanUniforms.paint_x0 = RI_ROUND_TO_INT((pzero.x/patternWidth)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_y0 = RI_ROUND_TO_INT((pzero.y/patternHeight)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_dxdx = RI_ROUND_TO_INT((s2p[0][0]/patternWidth)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_dxdy = RI_ROUND_TO_INT((s2p[0][1]/patternHeight)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_dydx = RI_ROUND_TO_INT((s2p[1][0]/patternWidth)*(1<<GRADIENT_BITS));
+    m_spanUniforms.paint_dydy = RI_ROUND_TO_INT((s2p[1][1]/patternHeight)*(1<<GRADIENT_BITS));
+
+    m_spanUniforms.paint_x0 += (m_spanUniforms.paint_dxdx + m_spanUniforms.paint_dxdy) / 2;
+    m_spanUniforms.paint_y0 += (m_spanUniforms.paint_dydy + m_spanUniforms.paint_dydx) / 2;
+
+    m_spanUniforms.patternPtr = m_paint->m_pattern->getData(); 
+    m_spanUniforms.patternStride = m_paint->m_pattern->getStride();
+    m_spanUniforms.paint_width = m_paint->m_pattern->getWidth();
+    m_spanUniforms.paint_height = m_paint->m_pattern->getHeight();
+
+    m_signatureState.patternDesc = m_paint->m_pattern->getDescriptor();
+
+    m_spanUniforms.tileFillColor = IntegerColor(m_tileFillColor);
+    // The tile fill-color must be shifted down to same bit-depth (see integer samplers)
+    m_spanUniforms.tileFillColor.truncateColor(m_signatureState.patternDesc);
+
+}
+
+RI_INLINE static RIfloat floatEqu(RIfloat a, RIfloat b, RIfloat e)
+{
+    // \note This should be sufficient for our use-cases;
+    return (RI_ABS(a - b) < e);
+}
+
+RI_INLINE static RIfloat distToInt(RIfloat f)
+{
+    const RIfloat intF = RI_ROUND_TO_INT(f);
+    return RI_ABS(intF - f);
+}
+
+/**
+ * \brief   Check if transform is 90 degree rotation, or flip and nothing else.
+ */
+RI_INLINE static bool orthoNormalCoAxialTransform(const Matrix3x3& t, bool aa)
+{
+    const RIfloat epsilonCoord = 1/255.0f; // 1/127.0f;
+    const RIfloat epsilonGradient = epsilonCoord * epsilonCoord; // \todo Too strict?
+    const RIfloat absPatterns[2][4] = {
+        {1.0f, 0.0f, 0.0f, 1.0f},
+        {0.0f, 1.0f, 1.0f, 0.0f} };
+
+    if (!t.isAffine())
+        return false;
+
+    // \todo This rule only applies if filtering is in use?
+    if (aa)
+        if (!floatEqu(distToInt(t[0][2]), 0.0f, epsilonCoord) || !floatEqu(distToInt(t[1][2]), 0.0f, epsilonCoord))
+            return false;
+
+    Matrix3x3 u = t;
+    
+    for (int j = 0; j < 2; j++)
+        for (int i = 0; i < 2; i++)
+            u[j][i] = RI_ABS(u[j][i]);
+
+    bool found;
+
+    for (int m = 0; m < 2; m++)
+    {
+        found = true;
+        for (int j = 0; j < 2; j++)
+        {
+            for (int i = 0; i < 2; i++)
+            {
+                //if (u[j][i] != absPatterns[m][i+j*2])
+                if (!floatEqu(u[j][i], absPatterns[m][i+j*2], epsilonGradient))
+                {
+                    found = false;
+                    break;
+                }
+            }
+            if (!found) break;
+        }
+        if (found) break;
+    }
+
+    return found;
+}
+
+void PixelPipe::prepareImage(bool aa)
+{
+    if (!m_image)
+    {
+        m_signatureState.imageGradientType = GRADIENT_TYPE_INTEGER;
+        return;
+    }
+
+    RI_ASSERT(m_image);
+    m_spanUniforms.imagePtr = m_image->getData();
+    m_spanUniforms.imageStride = m_image->getStride();
+    
+    if (m_image->getParent() != NULL)
+    {
+        // Adjust the pointer.
+        int x, y;
+        m_image->getStorageOffset(x, y);
+        m_spanUniforms.imagePtr = Image::calculateAddress(
+            m_spanUniforms.imagePtr, m_image->getDescriptor().bitsPerPixel, x, y, m_spanUniforms.imageStride);
+    }
+
+    // \todo This function writes to derived state also.
+    // \todo Plenty of fast-paths possible!
+    const Matrix3x3& s2i = m_surfaceToImageMatrix;
+    
+    Vector3 zero(0,0,1);
+    Vector3 pzero;
+
+    bool fastImage = orthoNormalCoAxialTransform(s2i, aa);
+    
+    pzero = s2i * zero;
+
+    if (fastImage)
+    {
+        RI_ASSERT(pzero.z == 1.0f);
+        m_spanUniforms.image_idxdx = RI_ROUND_TO_INT(s2i[0][0]);
+        m_spanUniforms.image_idxdy = RI_ROUND_TO_INT(s2i[0][1]);
+        m_spanUniforms.image_idydx = RI_ROUND_TO_INT(s2i[1][0]);
+        m_spanUniforms.image_idydy = RI_ROUND_TO_INT(s2i[1][1]);
+        m_spanUniforms.image_ix0 = RI_FLOOR(pzero.x + 0.5f*(s2i[0][0]+s2i[0][1]));
+        m_spanUniforms.image_iy0 = RI_FLOOR(pzero.y + 0.5f*(s2i[1][1]+s2i[1][0]));
+
+        // Adjust sample-center when using (exactly) integer coordinates.
+        
+#if 0
+        if (m_spanUniforms.image_idxdx < 0 || m_spanUniforms.image_idxdy < 0)
+            m_spanUniforms.image_ix0--;
+    
+        if (m_spanUniforms.image_idydy < 0 || m_spanUniforms.image_idydx < 0)
+            m_spanUniforms.image_iy0--;
+#endif
+
+        m_signatureState.imageGradientType = GRADIENT_TYPE_INTEGER;
+    } 
+    else if (s2i.isAffine())
+    {
+        RI_ASSERT(pzero.z == 1.0f); 
+        const RIfloat imageWidth = m_image->getWidth();
+        const RIfloat imageHeight = m_image->getHeight();
+        
+        m_spanUniforms.image_idxdx = RI_ROUND_TO_INT((s2i[0][0]/imageWidth)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_idxdy = RI_ROUND_TO_INT((s2i[0][1]/imageHeight)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_idydx = RI_ROUND_TO_INT((s2i[1][0]/imageWidth)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_idydy = RI_ROUND_TO_INT((s2i[1][1]/imageHeight)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_ix0 = RI_ROUND_TO_INT((pzero.x/imageWidth)*(1<<GRADIENT_BITS));
+        m_spanUniforms.image_iy0 = RI_ROUND_TO_INT((pzero.y/imageHeight)*(1<<GRADIENT_BITS));
+
+        m_spanUniforms.image_ix0 += (m_spanUniforms.image_idxdx + m_spanUniforms.image_idxdy)/2;
+        m_spanUniforms.image_iy0 += (m_spanUniforms.image_idydy + m_spanUniforms.image_idydx)/2;
+
+        m_spanUniforms.image_iWidth = (RIint32)imageWidth;
+        m_spanUniforms.image_iHeight = (RIint32)imageHeight;
+
+        m_signatureState.imageGradientType = GRADIENT_TYPE_FIXED;
+    } 
+    else
+    {
+        // Use floats.
+        m_spanUniforms.image_fx0 = pzero.x;
+        m_spanUniforms.image_fy0 = pzero.y;
+        m_spanUniforms.image_fw0 = pzero.z;
+        m_spanUniforms.image_fdxdx = s2i[0][0];
+        m_spanUniforms.image_fdxdy = s2i[0][1];
+        m_spanUniforms.image_fdydx = s2i[1][0];
+        m_spanUniforms.image_fdydy = s2i[1][1];
+        m_spanUniforms.image_fdwdx = s2i[2][0];
+        m_spanUniforms.image_fdwdy = s2i[2][1];
+
+        m_spanUniforms.image_fx0 += 0.5f * (m_spanUniforms.image_fdxdx + m_spanUniforms.image_fdxdy);
+        m_spanUniforms.image_fy0 += 0.5f * (m_spanUniforms.image_fdydy + m_spanUniforms.image_fdydx);
+        m_spanUniforms.image_fw0 += 0.5f * (m_spanUniforms.image_fdwdx + m_spanUniforms.image_fdwdy);
+
+        m_spanUniforms.image_fWidth = (RIfloat)m_image->getWidth();
+        m_spanUniforms.image_fHeight = (RIfloat)m_image->getHeight();
+
+        m_signatureState.imageGradientType = GRADIENT_TYPE_FLOAT;
+    }
+
+    m_signatureState.imageDesc = m_image->getDescriptor();
+}
+
+static PixelPipe::TilingMode tilingModeOfImageTilingMode(VGTilingMode it)
+{
+    switch(it)
+    {
+    case VG_TILE_PAD:
+        return PixelPipe::TILING_MODE_PAD;
+    case VG_TILE_REPEAT:
+        return PixelPipe::TILING_MODE_REPEAT;
+    case VG_TILE_REFLECT:
+        return PixelPipe::TILING_MODE_REFLECT;
+    default:
+        RI_ASSERT(it == VG_TILE_FILL);
+        return PixelPipe::TILING_MODE_FILL;
+    }
+}
+
+static PixelPipe::TilingMode tilingModeOfSpreadMode(VGColorRampSpreadMode sm)
+{
+    switch(sm)
+    {
+    case VG_COLOR_RAMP_SPREAD_PAD:
+        return PixelPipe::TILING_MODE_PAD;
+    case VG_COLOR_RAMP_SPREAD_REPEAT:
+        return PixelPipe::TILING_MODE_REPEAT;
+    default:
+        RI_ASSERT(sm == VG_COLOR_RAMP_SPREAD_REFLECT);
+        return PixelPipe::TILING_MODE_REFLECT;
+    }
+}
+
+static PixelPipe::TilingMode tilingModeOfPaint(const Paint* paint)
+{
+    switch(paint->m_paintType)
+    {
+    case VG_PAINT_TYPE_COLOR:
+        return PixelPipe::TILING_MODE_PAD;
+    case VG_PAINT_TYPE_LINEAR_GRADIENT:
+    case VG_PAINT_TYPE_RADIAL_GRADIENT:
+        return tilingModeOfSpreadMode(paint->m_colorRampSpreadMode);
+    default:
+        RI_ASSERT(paint->m_paintType == VG_PAINT_TYPE_PATTERN);
+        return tilingModeOfImageTilingMode(paint->m_patternTilingMode);
+    }
+}
+
+void PixelPipe::prepareRenderToMask()
+{
+    RI_ASSERT(m_drawable->getMaskBuffer());
+
+    m_signatureState.dstDesc = m_drawable->getMaskBuffer()->getDescriptor();
+    //RI_ASSERT(m_signatureState.dstFormat >= 0 && m_signatureState.dstFormat <= VG_lABGR_8888_PRE);
+
+    m_signatureState.maskOperation = m_maskOperation;
+}
+
+void PixelPipe::prepareSignatureState()
+{
+    m_signatureState.isRenderToMask = m_renderToMask;
+
+    if (m_signatureState.isRenderToMask)
+    {
+        prepareRenderToMask();
+        return;
+    }
+
+    m_signatureState.blendMode = getBlendMode();
+
+    m_signatureState.hasColorTransform = this->m_colorTransform;
+
+    m_signatureState.paintType = getPaintType();
+    
+    m_signatureState.paintTilingMode = tilingModeOfPaint(m_paint);
+    // \todo Derive these from the quality settings somehow.
+    // Linear and nearest should work atm.
+    m_signatureState.paintSampler = SAMPLER_TYPE_NEAREST;
+    m_signatureState.imageSampler = SAMPLER_TYPE_NEAREST;
+
+    m_signatureState.hasMasking = isMasking() && (m_drawable->getMaskBuffer() != NULL);
+    
+    m_signatureState.hasImage = m_image ? true : false;
+    m_signatureState.unsafeImageInput = !m_image ? false : m_image->isUnsafe();
+    m_signatureState.imageMode = m_imageMode;
+
+    // Formats. Note that fields that are not filled in / used get set to a derived state in a 
+    // separate function!
+
+    if (m_signatureState.paintType == (RIuint32)VG_PAINT_TYPE_COLOR)
+    {
+        RI_ASSERT(m_paint);
+        if (m_paint->getSolidColor().a == 1.0)
+            m_signatureState.fillColorTransparent = false;
+        else
+            m_signatureState.fillColorTransparent = true;
+    }
+
+    m_signatureState.dstDesc = m_drawable->getColorBuffer()->getDescriptor();
+
+    // \todo Why isn't the imagedescriptor set here?
+    if (m_signatureState.hasMasking)
+    {
+        m_signatureState.maskDesc = m_drawable->getMaskBuffer()->getDescriptor();
+    }
+
+}
+
+/**
+ * \brief   Remove redundancy from the pixel-pipeline state so that less
+ *          pipelines are generated.
+ */
+static void determineDerivedState(PixelPipe::SignatureState& derivedState, const PixelPipe::SignatureState& originalState)
+{
+    derivedState = originalState;
+
+    if (derivedState.isRenderToMask)
+    {
+        // Set a lot of defaults:
+        derivedState.blendMode = VG_BLEND_SRC;
+        derivedState.imageMode = VG_DRAW_IMAGE_NORMAL;
+        derivedState.paintType = VG_PAINT_TYPE_COLOR;
+
+        derivedState.hasImage = false;
+        derivedState.hasMasking = false;
+        derivedState.hasColorTransform = false;
+    }
+
+    if (derivedState.paintType == VG_PAINT_TYPE_COLOR)
+    {
+        derivedState.paintTilingMode = PixelPipe::TILING_MODE_PAD;
+        derivedState.paintSampler = PixelPipe::SAMPLER_TYPE_NEAREST;
+        // \todo Opaque solid colors can benefit from simpler coverage-blending
+        // becase SRC_OVER == SRC. This information has to be present in
+        // the derivedState (and not just uniform).
+    }
+
+    if (!derivedState.hasImage)
+    {
+        derivedState.imageMode = VG_DRAW_IMAGE_NORMAL;
+        derivedState.imageSampler = PixelPipe::SAMPLER_TYPE_NEAREST;
+        derivedState.imageGradientType = PixelPipe::GRADIENT_TYPE_INTEGER;
+        derivedState.imageDesc = Color::Descriptor::getDummyDescriptor();
+    } else if (derivedState.imageMode == VG_DRAW_IMAGE_NORMAL)
+    {
+        // If paint is not generated, use a common enum
+        derivedState.paintType = VG_PAINT_TYPE_COLOR;
+    }
+
+    if (derivedState.paintType != VG_PAINT_TYPE_PATTERN)
+    {
+        derivedState.patternDesc = Color::Descriptor::getDummyDescriptor();
+    }
+
+    if (!derivedState.isRenderToMask)
+        derivedState.maskOperation = VG_CLEAR_MASK;
+
+    if (!derivedState.hasMasking)
+    {
+        derivedState.maskDesc = Color::Descriptor::getDummyDescriptor();
+    }
+}
+
+
+/**
+ * \brief   Determine per-scanconversion constant state.
+ * \todo    NOTE! This also prepares the derived state at the moment.
+ */
+void PixelPipe::prepareSpanUniforms(bool aa)
+{
+    prepareSignatureState();
+
+    if (m_signatureState.hasColorTransform)
+        m_spanUniforms.colorTransformValues = m_iColorTransformValues;
+
+    RI_ASSERT(m_drawable->getColorBuffer());
+
+    const Image* dst;
+
+    if (!m_signatureState.isRenderToMask)
+        dst = m_drawable->getColorBuffer()->getImage();
+    else
+        dst = m_drawable->getMaskBuffer()->getImage();
+    
+    m_spanUniforms.dstPtr = dst->getData();
+    m_spanUniforms.dstStride = dst->getStride();
+
+    if (m_drawable->getMaskBuffer())
+    {
+        m_spanUniforms.maskPtr = m_drawable->getMaskBuffer()->m_image->getData();
+        m_spanUniforms.maskStride = m_drawable->getMaskBuffer()->m_image->getStride();
+    }
+    else
+    {
+        m_spanUniforms.maskPtr = NULL;
+        m_spanUniforms.maskStride = 0;
+    }
+
+    if (!m_renderToMask)
+    {
+        VGImageFormat prefPaintFormat = getPreferredLUTFormat();
+
+        switch (getPaintType())
+        {
+            case VG_PAINT_TYPE_COLOR:
+                prepareSolidFill();
+                break;
+            case VG_PAINT_TYPE_LINEAR_GRADIENT:
+                m_paint->generateLUT(*this, prefPaintFormat);
+                prepareLinearGradient(); 
+                break;
+            case VG_PAINT_TYPE_RADIAL_GRADIENT:
+                m_paint->generateLUT(*this, prefPaintFormat);
+                prepareRadialGradient();
+                break;
+            default:
+                RI_ASSERT(getPaintType() == VG_PAINT_TYPE_PATTERN);
+                preparePattern();
+                break;
+        }
+    }
+    else
+    {
+        prepareCoverageFill();
+    }
+
+    prepareImage(aa);
+
+    // Must be done last:
+    determineDerivedState(m_derivedState, m_signatureState);
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Computes the linear gradient function at (x,y).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+void PixelPipe::linearGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const
+{
+    RI_ASSERT(m_paint);
+    Vector2 u = m_paint->m_linearGradientPoint1 - m_paint->m_linearGradientPoint0;
+    RIfloat usq = dot(u,u);
+    if( usq <= 0.0f )
+    {   //points are equal, gradient is always 1.0f
+        g = 1.0f;
+        rho = 0.0f;
+        return;
+    }
+    RIfloat oou = 1.0f / usq;
+
+    Vector2 p(x, y);
+    p = affineTransform(m_surfaceToPaintMatrix, p);
+    p -= m_paint->m_linearGradientPoint0;
+    RI_ASSERT(usq >= 0.0f);
+    g = dot(p, u) * oou;
+    RIfloat dgdx = oou * u.x * m_surfaceToPaintMatrix[0][0] + oou * u.y * m_surfaceToPaintMatrix[1][0];
+    RIfloat dgdy = oou * u.x * m_surfaceToPaintMatrix[0][1] + oou * u.y * m_surfaceToPaintMatrix[1][1];
+    rho = (RIfloat)sqrt(dgdx*dgdx + dgdy*dgdy);
+    RI_ASSERT(rho >= 0.0f);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Computes the radial gradient function at (x,y).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::radialGradient(RIfloat &g, RIfloat &rho, RIfloat x, RIfloat y) const
+{
+    RI_ASSERT(m_paint);
+    if( m_paint->m_radialGradientRadius <= 0.0f )
+    {
+        g = 1.0f;
+        rho = 0.0f;
+        return;
+    }
+
+    RIfloat r = m_paint->m_radialGradientRadius;
+    Vector2 c = m_paint->m_radialGradientCenter;
+    Vector2 f = m_paint->m_radialGradientFocalPoint;
+    Vector2 gx(m_surfaceToPaintMatrix[0][0], m_surfaceToPaintMatrix[1][0]);
+    Vector2 gy(m_surfaceToPaintMatrix[0][1], m_surfaceToPaintMatrix[1][1]);
+
+    Vector2 fp = f - c;
+
+    //clamp the focal point inside the gradient circle
+    RIfloat fpLen = fp.length();
+    if( fpLen > 0.999f * r )
+        fp *= 0.999f * r / fpLen;
+
+    RIfloat D = -1.0f / (dot(fp,fp) - r*r);
+    Vector2 p(x, y);
+    p = affineTransform(m_surfaceToPaintMatrix, p) - c;
+    Vector2 d = p - fp;
+    RIfloat s = (RIfloat)sqrt(r*r*dot(d,d) - RI_SQR(p.x*fp.y - p.y*fp.x));
+    g = (dot(fp,d) + s) * D;
+    if(RI_ISNAN(g))
+        g = 0.0f;
+    RIfloat dgdx = D*dot(fp,gx) + (r*r*dot(d,gx) - (gx.x*fp.y - gx.y*fp.x)*(p.x*fp.y - p.y*fp.x)) * (D / s);
+    RIfloat dgdy = D*dot(fp,gy) + (r*r*dot(d,gy) - (gy.x*fp.y - gy.y*fp.x)*(p.x*fp.y - p.y*fp.x)) * (D / s);
+    rho = (RIfloat)sqrt(dgdx*dgdx + dgdy*dgdy);
+    if(RI_ISNAN(rho))
+        rho = 0.0f;
+    RI_ASSERT(rho >= 0.0f);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Maps a gradient function value to a color.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color PixelPipe::colorRamp(RIfloat gradient, RIfloat rho) const
+{
+    RI_ASSERT(m_paint);
+    RI_ASSERT(rho >= 0.0f);
+
+    Color c(0,0,0,0,m_paint->m_colorRampPremultiplied ? Color::sRGBA_PRE : Color::sRGBA);
+    Color avg;
+
+    if(rho == 0.0f)
+    {   //filter size is zero or gradient is degenerate
+        switch(m_paint->m_colorRampSpreadMode)
+        {
+        case VG_COLOR_RAMP_SPREAD_PAD:
+            gradient = RI_CLAMP(gradient, 0.0f, 1.0f);
+            break;
+        case VG_COLOR_RAMP_SPREAD_REFLECT:
+        {
+            RIfloat g = RI_MOD(gradient, 2.0f);
+            gradient = (g < 1.0f) ? g : 2.0f - g;
+            break;
+        }
+        default:
+            RI_ASSERT(m_paint->m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT);
+            gradient = gradient - (RIfloat)floor(gradient);
+            break;
+        }
+        RI_ASSERT(gradient >= 0.0f && gradient <= 1.0f);
+
+        for(int i=0;i<m_paint->m_colorRampStops.size()-1;i++)
+        {
+            if(gradient >= m_paint->m_colorRampStops[i].offset && gradient < m_paint->m_colorRampStops[i+1].offset)
+            {
+                RIfloat s = m_paint->m_colorRampStops[i].offset;
+                RIfloat e = m_paint->m_colorRampStops[i+1].offset;
+                RI_ASSERT(s < e);
+                RIfloat g = RI_CLAMP((gradient - s) / (e - s), 0.0f, 1.0f); //clamp needed due to numerical inaccuracies
+
+                Color sc = readStopColor(m_paint->m_colorRampStops, i, m_paint->m_colorRampPremultiplied);
+                Color ec = readStopColor(m_paint->m_colorRampStops, i+1, m_paint->m_colorRampPremultiplied);
+                return (1.0f-g) * sc + g * ec;  //return interpolated value
+            }
+        }
+        return readStopColor(m_paint->m_colorRampStops, m_paint->m_colorRampStops.size()-1, m_paint->m_colorRampPremultiplied);
+    }
+
+    RIfloat gmin = gradient - rho*0.5f;         //filter starting from the gradient point (if starts earlier, radial gradient center will be an average of the first and the last stop, which doesn't look good)
+    RIfloat gmax = gradient + rho*0.5f;
+
+    switch(m_paint->m_colorRampSpreadMode)
+    {
+    case VG_COLOR_RAMP_SPREAD_PAD:
+    {
+        if(gmin < 0.0f)
+            c += (RI_MIN(gmax, 0.0f) - gmin) * readStopColor(m_paint->m_colorRampStops, 0, m_paint->m_colorRampPremultiplied);
+        if(gmax > 1.0f)
+            c += (gmax - RI_MAX(gmin, 1.0f)) * readStopColor(m_paint->m_colorRampStops, m_paint->m_colorRampStops.size()-1, m_paint->m_colorRampPremultiplied);
+        gmin = RI_CLAMP(gmin, 0.0f, 1.0f);
+        gmax = RI_CLAMP(gmax, 0.0f, 1.0f);
+        c += m_paint->integrateColorRamp(gmin, gmax);
+        c *= 1.0f/rho;
+        c.clamp();  //clamp needed due to numerical inaccuracies
+        return c;
+    }
+
+    case VG_COLOR_RAMP_SPREAD_REFLECT:
+    {
+        avg = m_paint->integrateColorRamp(0.0f, 1.0f);
+        RIfloat gmini = (RIfloat)floor(gmin);
+        RIfloat gmaxi = (RIfloat)floor(gmax);
+        c = (gmaxi + 1.0f - gmini) * avg;       //full ramps
+
+        //subtract beginning
+        if(((int)gmini) & 1)
+            c -= m_paint->integrateColorRamp(RI_CLAMP(1.0f - (gmin - gmini), 0.0f, 1.0f), 1.0f);
+        else
+            c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(gmin - gmini, 0.0f, 1.0f));
+
+        //subtract end
+        if(((int)gmaxi) & 1)
+            c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(1.0f - (gmax - gmaxi), 0.0f, 1.0f));
+        else
+            c -= m_paint->integrateColorRamp(RI_CLAMP(gmax - gmaxi, 0.0f, 1.0f), 1.0f);
+        break;
+    }
+
+    default:
+    {
+        RI_ASSERT(m_paint->m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT);
+        avg = m_paint->integrateColorRamp(0.0f, 1.0f);
+        RIfloat gmini = (RIfloat)floor(gmin);
+        RIfloat gmaxi = (RIfloat)floor(gmax);
+        c = (gmaxi + 1.0f - gmini) * avg;       //full ramps
+        c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(gmin - gmini, 0.0f, 1.0f));  //subtract beginning
+        c -= m_paint->integrateColorRamp(RI_CLAMP(gmax - gmaxi, 0.0f, 1.0f), 1.0f);  //subtract end
+        break;
+    }
+    }
+
+    //divide color by the length of the range
+    c *= 1.0f / rho;
+    c.clamp();  //clamp needed due to numerical inaccuracies
+
+    //hide aliasing by fading to the average color
+    const RIfloat fadeStart = 0.5f;
+    const RIfloat fadeMultiplier = 2.0f;    //the larger, the earlier fade to average is done
+
+    if(rho < fadeStart)
+        return c;
+
+    RIfloat ratio = RI_MIN((rho - fadeStart) * fadeMultiplier, 1.0f);
+    return ratio * avg + (1.0f - ratio) * c;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Computes blend.
+* \param
+* \return
+* \note     premultiplied blending formulas
+            //src
+            a = asrc
+            r = rsrc
+            //src over
+            a = asrc + adst * (1-asrc)
+            r = rsrc + rdst * (1-asrc)
+            //dst over
+            a = asrc * (1-adst) + adst
+            r = rsrc * (1-adst) + adst
+            //src in
+            a = asrc * adst
+            r = rsrc * adst
+            //dst in
+            a = adst * asrc
+            r = rdst * asrc
+            //multiply
+            a = asrc + adst * (1-asrc)
+            r = rsrc * (1-adst) + rdst * (1-asrc) + rsrc * rdst
+            //screen
+            a = asrc + adst * (1-asrc)
+            r = rsrc + rdst - rsrc * rdst
+            //darken
+            a = asrc + adst * (1-asrc)
+            r = MIN(rsrc + rdst * (1-asrc), rdst + rsrc * (1-adst))
+            //lighten
+            a = asrc + adst * (1-asrc)
+            r = MAX(rsrc + rdst * (1-asrc), rdst + rsrc * (1-adst))
+            //additive
+            a = MIN(asrc+adst,1)
+            r = rsrc + rdst
+*//*-------------------------------------------------------------------*/
+
+
+
+Color PixelPipe::blend(const Color& s, RIfloat ar, RIfloat ag, RIfloat ab, const Color& d, VGBlendMode blendMode) const
+{
+    //apply blending in the premultiplied format
+    Color r(0,0,0,0,d.getInternalFormat());
+    RI_ASSERT(s.a >= 0.0f && s.a <= 1.0f);
+    RI_ASSERT(s.r >= 0.0f && s.r <= s.a && s.r <= ar);
+    RI_ASSERT(s.g >= 0.0f && s.g <= s.a && s.g <= ag);
+    RI_ASSERT(s.b >= 0.0f && s.b <= s.a && s.b <= ab);
+    RI_ASSERT(d.a >= 0.0f && d.a <= 1.0f);
+    RI_ASSERT(d.r >= 0.0f && d.r <= d.a);
+    RI_ASSERT(d.g >= 0.0f && d.g <= d.a);
+    RI_ASSERT(d.b >= 0.0f && d.b <= d.a);
+    switch(blendMode)
+    {
+    case VG_BLEND_SRC:
+        r = s;
+        break;
+
+    case VG_BLEND_SRC_OVER:
+        r.r = s.r + d.r * (1.0f - ar);
+        r.g = s.g + d.g * (1.0f - ag);
+        r.b = s.b + d.b * (1.0f - ab);
+        r.a = s.a + d.a * (1.0f - s.a);
+        break;
+
+    case VG_BLEND_DST_OVER:
+        r.r = s.r * (1.0f - d.a) + d.r;
+        r.g = s.g * (1.0f - d.a) + d.g;
+        r.b = s.b * (1.0f - d.a) + d.b;
+        r.a = s.a * (1.0f - d.a) + d.a;
+        break;
+
+    case VG_BLEND_SRC_IN:
+        r.r = s.r * d.a;
+        r.g = s.g * d.a;
+        r.b = s.b * d.a;
+        r.a = s.a * d.a;
+        break;
+
+    case VG_BLEND_DST_IN:
+        r.r = d.r * ar;
+        r.g = d.g * ag;
+        r.b = d.b * ab;
+        r.a = d.a * s.a;
+        break;
+
+    case VG_BLEND_MULTIPLY:
+        r.r = s.r * (1.0f - d.a + d.r) + d.r * (1.0f - ar);
+        r.g = s.g * (1.0f - d.a + d.g) + d.g * (1.0f - ag);
+        r.b = s.b * (1.0f - d.a + d.b) + d.b * (1.0f - ab);
+        r.a = s.a + d.a * (1.0f - s.a);
+        break;
+
+    case VG_BLEND_SCREEN:
+        r.r = s.r + d.r * (1.0f - s.r);
+        r.g = s.g + d.g * (1.0f - s.g);
+        r.b = s.b + d.b * (1.0f - s.b);
+        r.a = s.a + d.a * (1.0f - s.a);
+        break;
+
+    case VG_BLEND_DARKEN:
+        r.r = RI_MIN(s.r + d.r * (1.0f - ar), d.r + s.r * (1.0f - d.a));
+        r.g = RI_MIN(s.g + d.g * (1.0f - ag), d.g + s.g * (1.0f - d.a));
+        r.b = RI_MIN(s.b + d.b * (1.0f - ab), d.b + s.b * (1.0f - d.a));
+        r.a = s.a + d.a * (1.0f - s.a);
+        break;
+
+    case VG_BLEND_LIGHTEN:
+        r.r = RI_MAX(s.r + d.r * (1.0f - ar), d.r + s.r * (1.0f - d.a));
+        r.g = RI_MAX(s.g + d.g * (1.0f - ag), d.g + s.g * (1.0f - d.a));
+        r.b = RI_MAX(s.b + d.b * (1.0f - ab), d.b + s.b * (1.0f - d.a));
+        //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a)
+        //in practice there can be a very slight difference because
+        //of the max operation in the blending formula that may cause color to exceed alpha.
+        //Because of this, we compute the result both ways and return the maximum.
+        r.a = RI_MAX(s.a + d.a * (1.0f - s.a), d.a + s.a * (1.0f - d.a));
+        break;
+
+    default:
+        RI_ASSERT(blendMode == VG_BLEND_ADDITIVE);
+        r.r = RI_MIN(s.r + d.r, 1.0f);
+        r.g = RI_MIN(s.g + d.g, 1.0f);
+        r.b = RI_MIN(s.b + d.b, 1.0f);
+        r.a = RI_MIN(s.a + d.a, 1.0f);
+        break;
+    }
+    return r;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Applies color transform.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void PixelPipe::colorTransform(Color& c) const
+{
+    if(m_colorTransform)
+    {
+        c.unpremultiply();
+        c.luminanceToRGB();
+        c.r = c.r * m_colorTransformValues[0] + m_colorTransformValues[4];
+        c.g = c.g * m_colorTransformValues[1] + m_colorTransformValues[5];
+        c.b = c.b * m_colorTransformValues[2] + m_colorTransformValues[6];
+        c.a = c.a * m_colorTransformValues[3] + m_colorTransformValues[7];
+        c.clamp();
+        c.premultiply();
+    }
+}
+
+void PixelPipe::fillSpans(PPVariants& variants, const Span* spans, int nSpans) const
+{
+#if 1
+    PPCompiler& compiler = PPCompiler::getCompiler();
+
+    PPCompiler::PixelPipeHandle handle = compiler.compilePixelPipeline(m_derivedState);
+    if (handle)
+    {
+        PixelPipeFunction func = compiler.getPixelPipePtr(handle);
+        RI_ASSERT(func);
+        func(m_spanUniforms, variants, spans, nSpans);
+        compiler.releasePixelPipeline(handle);
+    } else
+#endif
+    {
+        executePixelPipeline(m_derivedState, m_spanUniforms, variants, spans, nSpans);
+    }
+}
+
+//=======================================================================
+
+}   //namespace OpenVGRI
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riPixelPipe.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,428 @@
+#ifndef __RIPIXELPIPE_H
+#define __RIPIXELPIPE_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Paint and PixelPipe classes.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#include "riImage.h"
+#endif
+
+//=======================================================================
+
+namespace OpenVGRI
+{
+
+struct Span;
+class PPCompiler;
+class PixelPipe;
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Storage and operations for VGPaint.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Paint
+{
+public:
+    enum { GRADIENT_LUT_BITS = 8 };
+    enum { GRADIENT_LUT_COUNT = 1 << GRADIENT_LUT_BITS };
+    enum { GRADIENT_LUT_MASK = (1<<GRADIENT_LUT_BITS)-1 };
+
+    struct GradientStop
+    {
+        GradientStop() : offset(0.0f), color(0.0f, 0.0f, 0.0f, 0.0f, Color::sRGBA) {}
+        RIfloat		offset;
+        Color		color;
+    };
+
+public:
+    Paint();
+    ~Paint();
+    void					addReference()							{ m_referenceCount++; }
+    int						removeReference()						{ m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+    void                    setColor(const Color& color) {m_paintColor = color; m_paintColor.clamp(); m_paintColor.premultiply(); }
+    void                    setGradientStops(Array<GradientStop>& inputStops, Array<GradientStop>& stops);
+    void                    generateLUT(PixelPipe& pipe, VGImageFormat targetFormat);
+    const IntegerColor*     getGradientLUT() const { return m_gradientLUT; }
+    void                    setLinearGradient(const Vector2& p0, const Vector2& p1);
+    void                    setRadialGradient(const Vector2& c, const Vector2& f, VGfloat r);
+    bool                    linearDegenerate() const;
+    bool                    radialDegenerate() const;
+    Color                   getSolidColor() const;
+    
+    Color integrateColorRamp(RIfloat gmin, RIfloat gmax) const; // \todo Private after modifications.
+    
+public:
+    VGPaintType				m_paintType;
+    Color					m_paintColor;
+    Color					m_inputPaintColor;
+    VGColorRampSpreadMode	m_colorRampSpreadMode;
+    Array<GradientStop>		m_colorRampStops;
+    Array<GradientStop>		m_inputColorRampStops;
+    VGboolean				m_colorRampPremultiplied;
+    Vector2					m_inputLinearGradientPoint0;
+    Vector2					m_inputLinearGradientPoint1;
+    Vector2					m_inputRadialGradientCenter;
+    Vector2					m_inputRadialGradientFocalPoint;
+    RIfloat					m_inputRadialGradientRadius;
+    Vector2					m_linearGradientPoint0;
+    Vector2					m_linearGradientPoint1;
+    Vector2					m_radialGradientCenter;
+    Vector2					m_radialGradientFocalPoint;
+    RIfloat					m_radialGradientRadius;
+    VGTilingMode			m_patternTilingMode;
+    Image*					m_pattern;
+private:
+    Paint(const Paint&);						//!< Not allowed.
+    const Paint& operator=(const Paint&);		//!< Not allowed.
+
+    int						m_referenceCount;
+    IntegerColor            m_gradientLUT[GRADIENT_LUT_COUNT];
+    VGImageFormat           m_lutFormat;
+    bool                    m_gradientStopsChanged;
+    bool                    m_gradientDegenerate;
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Encapsulates all information needed for painting a pixel.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define RGRAD_FLOATS
+#if defined(RGRAD_FLOATS)
+typedef RIfloat RGScalar;
+#else
+typedef double RGScalar;
+#endif
+
+class PixelPipe
+{
+public:
+    enum SamplerType 
+    {
+        SAMPLER_TYPE_NEAREST    = 0,
+        SAMPLER_TYPE_LINEAR     = 1,
+        SAMPLER_TYPE_SIZE
+    };
+    
+    enum TilingMode 
+    {
+        TILING_MODE_PAD         = 0,
+        TILING_MODE_REPEAT      = 1,
+        TILING_MODE_REFLECT     = 2,
+        TILING_MODE_FILL        = 3,
+        TILING_MODE_SIZE
+    };
+    
+    // Span per-pixel variants:
+    struct PPVariants
+    {
+        void*       dst;
+        void*       src;
+        void*       maskPtr;
+        int         coverage;
+
+        RIuint32    dstX;
+
+        RIint32     sx;
+        RIint32     sy;
+
+        RGScalar    rx;
+        RGScalar    ry;
+
+        // \todo Image sampling coordinates will be in fixed point if transform is affine,
+        // in floating point if not.
+        RGScalar    ix;
+        RGScalar    iy;
+
+        RIint32     iImageX;  
+        RIint32     iImageY;
+        RIfloat     fImageX;
+        RIfloat     fImageY;
+        RIfloat     fImageW;
+    };
+    
+    // Uniform state per-pixel
+    // \todo Organize into sub-structures?
+    struct PPUniforms
+    {
+        // \todo Do not store pointers to classes, only atoms! It should make the
+        // dynamic compilation a lot easier.
+        void*           srcPtr;
+        RIint32         srcStride;
+        void*           dstPtr;
+        RIint32         dstStride;
+        void*           maskPtr;
+        int             maskStride;
+        void*           imagePtr;
+        int             imageStride;
+        void*           patternPtr;
+        int             patternStride;
+        const IntegerColor*   gradientLookup;
+        const RIint32*        colorTransformValues;
+
+        // Linear gradient
+        RIint32         dgdx;
+        RIint32         dgdy;
+        RIint32         lgc;
+
+        // Radial gradient
+        RGScalar        rsqrp;
+        RGScalar        rfxp;
+        RGScalar        rfyp;
+        RGScalar        rx0;
+        RGScalar        ry0;
+        RGScalar        rdxdx;
+        RGScalar        rdxdy;
+        RGScalar        rdydx;
+        RGScalar        rdydy;
+
+        // Pattern. Note that pattern and image may be used at the same time.
+        RIint32         paint_width;
+        RIint32         paint_height;
+        RIint32         paint_x0;
+        RIint32         paint_y0;
+        RIint32         paint_dxdx;
+        RIint32         paint_dxdy;
+        RIint32         paint_dydx;
+        RIint32         paint_dydy;
+
+        // Image
+        RIint32         image_iWidth;
+        RIint32         image_iHeight;
+        RIint32         image_ix0;
+        RIint32         image_iy0;
+        RIint32         image_idxdx;
+        RIint32         image_idxdy;
+        RIint32         image_idydx;
+        RIint32         image_idydy;
+
+
+        RIfloat         image_fWidth;
+        RIfloat         image_fHeight;
+        RIfloat         image_fx0;
+        RIfloat         image_fy0;
+        RIfloat         image_fw0;
+        RIfloat         image_fdxdx;
+        RIfloat         image_fdxdy;
+        RIfloat         image_fdydx;
+        RIfloat         image_fdydy;
+        RIfloat         image_fdwdx;
+        RIfloat         image_fdwdy;
+
+        IntegerColor    tileFillColor;
+        IntegerColor    solidColor;
+        RIuint32        packedSolidColor;
+    };
+
+    enum ImageGradientType {
+        GRADIENT_TYPE_INTEGER   = 0,
+        GRADIENT_TYPE_FIXED     = 1,
+        GRADIENT_TYPE_FLOAT     = 2,
+        GRADIENT_TYPE_SIZE
+    };
+
+    // Signature state contains all the information necessary to compile
+    // a pixel-pipeline. Note that some of these are actually derived.
+    // \note REMEMBER TO UPDATE THE COMPILER. For now, there is now
+    // automatic mechanism to propagate changes to that component!
+    struct SignatureState
+    {
+        VGBlendMode         blendMode;
+        VGImageMode         imageMode;
+        VGPaintType         paintType;
+        VGMaskOperation     maskOperation;
+        TilingMode          paintTilingMode;
+        SamplerType         paintSampler;
+        SamplerType         imageSampler;
+
+        ImageGradientType   imageGradientType;
+
+        Color::Descriptor   dstDesc;
+        Color::Descriptor   maskDesc;
+        Color::Descriptor   imageDesc;
+        Color::Descriptor   patternDesc;
+
+        bool                hasMasking;
+        bool                hasImage;
+        bool                hasColorTransform;
+        bool                isRenderToMask;
+        bool                fillColorTransparent;
+        // When using external data for rendering an image: This is the only case
+        // where the data can be invalid in the pixel-pipe.
+        bool                unsafeImageInput; 
+
+    };
+
+public:
+    PixelPipe();	//throws bad_alloc
+    ~PixelPipe();
+
+    void	pixelPipe(int x, int y, RIuint32 coverage) const;	//rasterizer calls this function for each pixel
+    void 	fillSolidSpan(int startX, int y, int nPixels) const;
+    void	setDrawable(Drawable* drawable);
+    void	setBlendMode(VGBlendMode blendMode);
+    RI_INLINE VGBlendMode getBlendMode() const { return m_blendMode; }
+    void    setRenderToMask(bool renderToMask) { m_renderToMask = renderToMask; }
+    void    setMaskOperation(VGMaskOperation maskOperation) { m_maskOperation = maskOperation; }
+    void	setMask(bool masking);
+    void	setImage(Image* image, VGImageMode imageMode);	//image = NULL disables drawImage functionality
+    void	setSurfaceToPaintMatrix(const Matrix3x3& surfaceToPaintMatrix);
+    void	setSurfaceToImageMatrix(const Matrix3x3& surfaceToImageMatrix);
+    void	setImageQuality(VGImageQuality imageQuality);
+    void	setTileFillColor(const Color& c);
+    void	setPaint(Paint* paint);
+    void    setColorTransform(bool enable, RIfloat values[8]);
+    bool    hasColorTransform() const { return m_colorTransform; }
+    RI_INLINE const SignatureState& getSignatureState() const { return m_signatureState; }
+
+    // Functions that determine parts of derived state.
+    void    prepareSpanUniforms(bool aa);
+
+    RI_INLINE VGPaintType getPaintType() const;
+    RI_INLINE bool isMasking() const;
+    void fillSpans(PPVariants& variants, const Span* spans, int nSpans) const;
+
+    void    colorTransform(Color& c) const;
+    void    setColorTransformChanged(bool changed) { m_colorTransformChanged = changed; } // make paint friend and this private!
+    bool    colorTransformChanged() const { return m_colorTransformChanged; }
+    RI_INLINE VGImageMode getImageMode() const { return m_imageMode; }
+
+    RI_INLINE static bool isImageOnly(const SignatureState& state);
+
+private:
+
+    const Image*    getRenderTargetImage() const;
+    VGImageFormat   getPreferredLUTFormat() const;
+
+    void	prepareSolidFill();
+    void    prepareCoverageFill();
+    void    prepareLinearGradient();
+    void    prepareRadialGradient();
+    void    preparePattern();
+    void    prepareImage(bool aa);
+    void    prepareSignatureState();
+    void    prepareRenderToMask();
+    void	linearGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const;
+    void	radialGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const;
+    Color	colorRamp(RIfloat gradient, RIfloat rho) const;
+    Color	blend(const Color& s, RIfloat ar, RIfloat ag, RIfloat ab, const Color& d, VGBlendMode blendMode) const;
+
+    PixelPipe(const PixelPipe&);						//!< Not allowed.
+    const PixelPipe& operator=(const PixelPipe&);		//!< Not allowed.
+
+    Drawable*               m_drawable;
+    bool					m_masking;
+    Image*					m_image;
+    // \todo LUT within the paint class broke constness of paint.
+    Paint*			        m_paint;
+    Paint					m_defaultPaint;
+    VGBlendMode				m_blendMode;
+    VGImageMode				m_imageMode;
+    VGImageQuality			m_imageQuality;
+    Color					m_tileFillColor;
+    bool                    m_colorTransform;
+    RIfloat                 m_colorTransformValues[8];
+    RIint32                 m_iColorTransformValues[8];
+    Matrix3x3				m_surfaceToPaintMatrix;
+    Matrix3x3				m_surfaceToImageMatrix;
+    Matrix3x3               m_paintToSurfaceMatrix;
+    VGMaskOperation         m_maskOperation;
+    bool                    m_renderToMask;
+    bool                    m_colorTransformChanged;
+
+public:
+
+    enum { COLOR_TRANSFORM_BITS = 8 };
+    enum { COLOR_TRANSFORM_ONE = (1<<COLOR_TRANSFORM_BITS) };
+    enum { COLOR_TRANSFORM_MASK = (COLOR_TRANSFORM_ONE - 1) };
+    enum { GRADIENT_BITS = 16 };
+    enum { GRADIENT_MASK = (1<<GRADIENT_BITS)-1 };
+    enum { SAMPLE_BITS = 8 };
+    enum { SAMPLE_MASK = (1<<SAMPLE_BITS)-1 };
+
+private:
+
+
+    SignatureState          m_signatureState;
+    SignatureState          m_derivedState;
+
+    PPUniforms  m_spanUniforms;
+};
+
+RI_INLINE VGPaintType PixelPipe::getPaintType() const
+{
+    if (m_paint->m_paintType == VG_PAINT_TYPE_COLOR)
+        return VG_PAINT_TYPE_COLOR;
+
+    if (m_paint->m_paintType == VG_PAINT_TYPE_PATTERN && !m_paint->m_pattern)
+        return VG_PAINT_TYPE_COLOR;
+
+    if (m_paint->m_paintType == VG_PAINT_TYPE_LINEAR_GRADIENT && m_paint->linearDegenerate())
+        return VG_PAINT_TYPE_COLOR;
+
+    if (m_paint->m_paintType == VG_PAINT_TYPE_RADIAL_GRADIENT && m_paint->radialDegenerate())
+        return VG_PAINT_TYPE_COLOR;
+
+    return m_paint->m_paintType;
+}
+
+RI_INLINE bool PixelPipe::isMasking() const
+{
+    return m_masking;
+}
+
+RI_INLINE /*static*/ bool PixelPipe::isImageOnly(const SignatureState& state)
+{
+    if (state.hasImage)
+        return (state.imageMode == VG_DRAW_IMAGE_NORMAL) ? true : false;
+    else
+        return false;
+}
+
+//=======================================================================
+
+}	//namespace OpenVGRI
+
+//=======================================================================
+
+#endif /* __RIPIXELPIPE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riRasterizer.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1073 @@
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of polygon rasterizer.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "riRasterizer.h"
+
+// TEMP!
+#ifndef __SFCOMPILER_H
+#   include "sfCompiler.h"
+#endif
+
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Rasterizer constructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Rasterizer::Rasterizer() :
+    m_covBuffer(NULL),
+    m_covBufferSz(0),
+    m_edges(),
+    m_scissorEdges(),
+    m_scissor(false),
+    m_aa(true),
+    m_vpx(0),
+    m_vpy(0),
+    m_vpwidth(0),
+    m_vpheight(0),
+    m_fillRule(VG_EVEN_ODD),
+    m_pixelPipe(NULL),
+    m_nSpans(0)
+{}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Rasterizer destructor.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Rasterizer::~Rasterizer()
+{
+    if(m_covBuffer)
+        RI_DELETE_ARRAY(m_covBuffer);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Removes all appended edges.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define EDGE_TERMINATOR 0xFFFFFFFFu
+
+void Rasterizer::clear()
+{
+    //m_edges.clear();
+    for (int i = 0; i < m_edges.size(); i++)
+        m_edges[i] = EDGE_TERMINATOR;
+
+    m_edgePool.clear();
+
+    m_edgeMin.set(0x7fffffffu, 0x7fffffffu);
+    m_edgeMax.set(0x80000000, 0x80000000);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Appends an edge to the rasterizer.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Rasterizer::addBBox(const IVector2& v)
+{
+    if(v.x < m_edgeMin.x) m_edgeMin.x = v.x;
+    if(v.y < m_edgeMin.y) m_edgeMin.y = v.y;
+    if(v.x > m_edgeMax.x) m_edgeMax.x = v.x;
+    if(v.y > m_edgeMax.y) m_edgeMax.y = v.y;
+}
+
+void Rasterizer::pushEdge(const Edge& edge)
+{
+    addBBox(edge.v0);
+    addBBox(edge.v1);
+
+    // Only add processed edges.
+
+    RI_ASSERT(edge.v0.y >= 0);
+    RI_ASSERT(edge.v0.y < edge.v1.y);	//horizontal edges should have been dropped already
+
+    ActiveEdge ae;
+    ae.direction = edge.direction;
+
+    // \todo Adjust for non-AA cases
+    // \todo verySteep is temporary. Either clip to right edge also, or validate that a proper slope can be
+    // calculated here.
+    const int slope	= RI_SAT_SHL((edge.v1.x - edge.v0.x), RASTERIZER_BITS - X_BITS) / (edge.v1.y - edge.v0.y);
+    //const bool verySteep = RI_INT_ABS(edge.v1.x - edge.v0.x) > (1 << (30-RASTERIZER_BITS)) ? true : false;
+    //const int slope	= verySteep ? 1 << 30 : RI_SHL((edge.v1.x - edge.v0.x), RASTERIZER_BITS - X_BITS) / (edge.v1.y - edge.v0.y);
+    // slope: SI.(RASTERIZER_BITS - Y_BITS)
+    const int yF 	= edge.v0.y & Y_MASK;
+    // \todo See verySteep note for this hack also. (Clip to right edge?)
+    const int xRef 	= RI_SAT_SHL(edge.v0.x, RASTERIZER_BITS - X_BITS) - (yF * slope);
+    //const int xRef 	= edge.v0.x > (1<<(30-RASTERIZER_BITS)) ? 1<<30 : RI_SHL(edge.v0.x, RASTERIZER_BITS - X_BITS) - (yF * slope);
+
+    RI_ASSERT(RI_INT_ABS(edge.v0.y <= 32767));
+    RI_ASSERT(RI_INT_ABS(edge.v1.y <= 32767));
+
+    ae.yStart 		= (RIint16)edge.v0.y;
+    ae.yEnd 	  	= (RIint16)edge.v1.y;
+    ae.xRef 		= xRef;
+    ae.slope 		= slope;
+    // Scanline range.
+    ae.minx         = xRef >> RASTERIZER_BITS;
+    ae.maxx         = (xRef + slope * (1<<Y_BITS)) >> RASTERIZER_BITS;
+
+    if (ae.minx > ae.maxx)
+        RI_ANY_SWAP(ActiveEdge::XCoord, ae.minx, ae.maxx);
+
+    if (ae.maxx < 0)
+        ae.minx = ae.maxx = LEFT_DISCARD_SHORT;
+
+    if (m_edges[ae.yStart>>Y_BITS] == EDGE_TERMINATOR)
+        ae.next = EDGE_TERMINATOR;
+    else
+        ae.next = m_edges[ae.yStart>>Y_BITS];
+
+    m_edgePool.push_back(ae);	//throws bad_alloc
+
+    RI_ASSERT(m_edgePool.size() > 0);
+    m_edges[ae.yStart>>Y_BITS] = m_edgePool.size()-1;
+}
+
+/**
+ * \brief   Clips an edge and if something remains, adds it to the list of edges.
+ * \todo    Enhance precision: Currently this just uses doubles and gets away with
+ *          it in most cases.
+ */
+void Rasterizer::clipAndAddEdge(Edge& edge)
+{
+    //if (m_edges.size() > 48)
+        //return;
+    // Check y-clips
+    // \todo Reduce amount of clips.
+    bool outLeft[2] = {(edge.v0.x < m_vpMinx), (edge.v1.x < m_vpMinx)};
+    bool outRight[2] = {(edge.v0.x > m_vpMaxx), (edge.v1.x > m_vpMaxx)};
+    bool outTop[2] = {(edge.v0.y < m_vpMiny), (edge.v1.y < m_vpMiny)};
+    bool outBottom[2] = {(edge.v0.y > m_vpMaxy), (edge.v1.y > m_vpMaxy)};
+
+    if (!(outLeft[0] || outLeft[1] || outRight[0] || outRight[1] || outTop[0] || outTop[1] || outBottom[0] || outBottom[1]))
+    {
+        pushEdge(edge);
+        return;
+    }
+
+    // \todo Make sure that checking out-of-right works with the scanconverter.
+    if ((outBottom[0] && outBottom[1]) || (outTop[0] && outTop[1]))
+        return; // Out of bounds
+
+    // \todo Clip to right edge of screen.
+    // \todo Make slope-calculation and signs consistent.
+    //
+    if (outTop[0] || outBottom[1])
+    {
+        // Clip to top/bottom.
+        double slope = (double)(edge.v1.x - edge.v0.x)/(edge.v1.y - edge.v0.y);
+
+        if (outTop[0])
+        {
+            RI_ASSERT(-(RIint64)edge.v0.y >= 0);
+            RIint32 dx = RI_ROUND_TO_INT(-slope * edge.v0.y);
+            edge.v0.y = 0;
+            edge.v0.x += dx;
+        }
+
+        if (outBottom[1])
+        {
+            RIint32 dy = edge.v1.y - m_vpMaxy;
+            RI_ASSERT(dy >= 0);
+            RIint32 dx = -RI_ROUND_TO_INT(slope * dy);
+            edge.v1.y = m_vpMaxy;
+            edge.v1.x += dx;
+        }
+
+    }
+
+    if (edge.v0.y >= edge.v1.y)
+        return;
+
+    // \todo Recheck left/right.
+    outLeft[0] = (edge.v0.x < m_vpMinx); outLeft[1] = (edge.v1.x < m_vpMinx);
+    outRight[1] = (edge.v0.x > m_vpMaxx); outRight[1] = (edge.v1.x > m_vpMaxx);
+
+    if (outLeft[0] && outLeft[1])
+    {
+        edge.v0.x = m_vpMinx;
+        edge.v1.x = m_vpMinx;
+        pushEdge(edge);
+        return;
+    }
+    if (outRight[0] && outRight[1])
+    {
+        edge.v0.x = m_vpMaxx;
+        edge.v1.x = m_vpMaxx;
+        pushEdge(edge);
+        return;
+    }
+
+    // From outside -> screen
+    if (outLeft[0] || outRight[1])
+    {
+        // infinite slope?
+        double slope = (double)((RIint64)edge.v1.y - edge.v0.y)/((RIint64)edge.v1.x - edge.v0.x);
+
+        if (outLeft[0])
+        {
+            RIint32 dx = edge.v0.x;
+            //RI_ASSERT(dx >= 0);
+            // Note the sign.
+            RIint32 dy = RI_ROUND_TO_INT(-slope * dx);
+
+            Edge vpart = edge;
+            vpart.v1.y = edge.v0.y + dy;
+            //vpart.v1.x = edge.v0.x; // = 0?
+            // \note This should be flagged instead of setting the smallest possible
+            // value because of extremely gentle slopes may cause bugs:
+            vpart.v1.x = vpart.v0.x = -0x100000;
+
+            if (vpart.v1.y > vpart.v0.y)
+                pushEdge(vpart);
+
+            edge.v0.y += dy;
+            edge.v0.x = 0;
+        }
+    }
+    // From screen -> outside
+    if (outLeft[1] || outRight[0])
+    {
+        // infinite slope?
+        double slope = (double)((RIint64)edge.v1.y - edge.v0.y)/((RIint64)edge.v1.x - edge.v0.x);
+
+        if (outLeft[1])
+        {
+            RIint32 dx = edge.v0.x;
+            RI_ASSERT(dx >= 0);
+            RIint32 dy = RI_ROUND_TO_INT(-slope * dx);
+
+            Edge vpart = edge;
+            vpart.v0.y = edge.v0.y + dy;
+            vpart.v1.x = vpart.v0.x = LEFT_DISCARD;
+
+            if (vpart.v1.y > vpart.v0.y)
+                pushEdge(vpart);
+
+            edge.v1.y = edge.v0.y + dy;
+            edge.v1.x = 0;
+        }
+    }
+
+    if (edge.v0.y >= edge.v1.y)
+        return;
+
+    // Finally, add the edge:
+    pushEdge(edge);
+}
+
+void Rasterizer::addEdge(const Vector2& v0, const Vector2& v1)
+{
+    if( m_edges.size() >= RI_MAX_EDGES )
+        throw std::bad_alloc();	//throw an out of memory error if there are too many edges
+
+    Edge e;
+
+    {
+        IVector2 i0(RI_ROUND_TO_INT(v0.x * (1<<X_BITS)), RI_ROUND_TO_INT(v0.y * (1<<Y_BITS)));
+        IVector2 i1(RI_ROUND_TO_INT(v1.x * (1<<X_BITS)), RI_ROUND_TO_INT(v1.y * (1<<Y_BITS)));
+
+        if(i0.y == i1.y)
+            return;	//skip horizontal edges (they don't affect rasterization since we scan horizontally)
+
+        if (i0.y < i1.y)
+        {
+            // Edge is going upward
+            e.v0 = i0;
+            e.v1 = i1;
+            e.direction = 1;
+        }
+        else
+        {
+            // Edge is going downward
+            e.v0 = i1;
+            e.v1 = i0;
+            e.direction = -1;
+        }
+    }
+
+    // Clip and insert.
+
+    clipAndAddEdge(e);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Set up rasterizer
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Rasterizer::setup(int vpx, int vpy, int vpwidth, int vpheight, VGFillRule fillRule, const PixelPipe* pixelPipe)
+{
+    RI_ASSERT(vpwidth >= 0 && vpheight >= 0);
+    RI_ASSERT(vpx + vpwidth >= vpx && vpy + vpheight >= vpy);
+    RI_ASSERT(fillRule == VG_EVEN_ODD || fillRule == VG_NON_ZERO);
+    RI_ASSERT(pixelPipe);
+
+    clear();
+
+    m_vpx = vpx;
+    m_vpy = vpy;
+    m_vpwidth = vpwidth;
+    m_vpheight = vpheight;
+
+    if (m_vpheight > m_edges.size())
+    {
+        int os = m_edges.size();
+        m_edges.resize(m_vpheight);
+        for (int i = os; i < m_edges.size(); i++)
+            m_edges[i] = EDGE_TERMINATOR;
+    }
+
+    m_vpMinx = RI_SHL(vpx, X_BITS);
+    m_vpMiny = RI_SHL(vpy, Y_BITS);
+    m_vpMaxx = RI_SHL(vpx + vpwidth, X_BITS);
+    m_vpMaxy = RI_SHL(vpy + vpheight, Y_BITS);
+
+    m_fillRule = fillRule;
+
+    RIuint32 fillRuleMask = fillRule == VG_NON_ZERO ? 0xffffffffu : 1;
+    m_fillRuleMask = fillRuleMask;
+
+    m_pixelPipe = pixelPipe;
+    m_covMinx = vpx+vpwidth;
+    m_covMiny = vpy+vpheight;
+    m_covMaxx = vpx;
+    m_covMaxy = vpy;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Sets scissor rectangles.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Rasterizer::setScissor(const Array<Rectangle>& scissors)
+{
+    try
+    {
+        m_scissorEdges.clear();
+        for(int i=0;i<scissors.size();i++)
+        {
+            if(scissors[i].width > 0 && scissors[i].height > 0)
+            {
+                ScissorEdge e;
+                e.miny = scissors[i].y;
+                e.maxy = RI_INT_ADDSATURATE(scissors[i].y, scissors[i].height);
+
+                e.x = scissors[i].x;
+                e.direction = 1;
+                m_scissorEdges.push_back(e);	//throws bad_alloc
+                e.x = RI_INT_ADDSATURATE(scissors[i].x, scissors[i].width);
+                e.direction = -1;
+                m_scissorEdges.push_back(e);	//throws bad_alloc
+            }
+        }
+    }
+    catch(std::bad_alloc)
+    {
+        m_scissorEdges.clear();
+        throw;
+    }
+}
+
+void Rasterizer::setScissoring(bool enabled)
+{
+    m_scissor = enabled;
+}
+
+static RI_INLINE void small_memcpy32(void* dst, const void* src, size_t n)
+{
+    RIuint32 *d = (RIuint32*)dst;
+    const RIuint32 *s = (const RIuint32*)src;
+    while(n)
+    {
+        *d++ = *s++;
+        n-=4;
+    }
+}
+
+// \todo Move this to some debug file or remove.
+#if defined(USE_SSE2) && !defined(_WIN32)
+RI_INLINE static void print128(__m128i ll)
+{
+#if defined(RI_DEBUG)
+    unsigned long long v[2];
+    _mm_storeu_pd((double*)v, (__m128d)ll);
+    RI_PRINTF("0x%016llx %016llx\n", v[0], v[1]);
+#else
+    (void)ll;
+#endif
+}
+#endif
+
+#if defined(USE_SSE2)
+RI_INLINE static __m128i mm_mul4x32(const __m128i a, const __m128i b) {
+     __m128i res;
+#if (_MSC_VER > 1400 )
+     // \todo Simpler way to do this on intel?
+     __m128i m0 = _mm_mul_epu32(a, _mm_shuffle_epi32(b, _MM_SHUFFLE(1, 1, 0, 0)));
+     __m128i m1 = _mm_mul_epu32(a, _mm_shuffle_epi32(b, _MM_SHUFFLE(3, 3, 2, 2)));
+
+     res = _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(m0), _mm_castsi128_ps(m1), _MM_SHUFFLE(2, 0, 2, 0)));
+#else
+     __asm {
+         movdqa xmm1, a;
+         movdqa xmm2, b;
+         pshufd xmm3, xmm2, 80;
+         movdqa xmm0, xmm1;
+
+         pshufd xmm2, xmm2, 250;
+         pmuludq xmm0, xmm3;
+         pmuludq xmm1, xmm2;
+
+         shufps xmm0, xmm1, 136;
+         movdqa res, xmm0;
+     }
+#endif
+     return res;
+}
+#endif
+
+#if defined(USE_SSE2)
+RI_INLINE static void mm_get_xmasks(const __m128i& coords, const __m128i& sampleCoords, __m128i& slWindMask, __m128i& pxWindMask)
+{
+    const __m128i z = _mm_setzero_si128();
+    const __m128i xMask = _mm_cmpeq_epi16(_mm_srai_epi16(coords, Rasterizer::RASTERIZER_BITS), z);
+    const __m128i sCmp = _mm_or_si128(_mm_cmpgt_epi16(sampleCoords, coords), _mm_cmpeq_epi16(sampleCoords, coords));
+    //const __m128i sCmp = _mm_cmplt_epi16(coords, sampleCoords);
+    slWindMask = xMask;
+    pxWindMask = _mm_and_si128(xMask, sCmp);
+}
+#endif
+
+RI_INLINE static void getVerticalSubpixels(int iY, int yStart, int yEnd, int& py0, int& py1)
+{
+    const int cy = iY << Rasterizer::Y_BITS;
+    py0 = cy > yStart ? 0 : yStart & Rasterizer::Y_MASK;
+    py1 = (RI_INT_MIN(yEnd, cy + (1<<Rasterizer::Y_BITS)) - 1) & Rasterizer::Y_MASK;
+}
+
+RI_INLINE static void applyLeftEdge(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& scanline, int intY)
+{
+    // Applies the whole edge at a time. Make sure xRight < x for all y.
+    // \todo Remove duplicate code for determining the active samples
+#if defined(USE_SSE2)
+    int py0, py1;
+
+    getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1);
+
+    const __m128i csteps = _mm_set_epi16(7,6,5,4,3,2,1,0);
+
+    const __m128i ssePy0 = _mm_set1_epi16(py0-1);
+    const __m128i ssePy1 = _mm_set1_epi16(py1+1);
+
+    const __m128i yMask = _mm_and_si128(_mm_cmpgt_epi16(csteps, ssePy0), _mm_cmplt_epi16(csteps, ssePy1));
+    const __m128i dir = _mm_set1_epi16(currAe.direction);
+
+    scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(yMask, dir));
+
+#else
+    RI_ASSERT(false); // Not implemented yet.
+#endif
+}
+
+RI_INLINE static void applyLeftEdgeNoAA(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& scanline, int intY)
+{
+    // Applies the whole edge at a time. Make sure xRight < x for all y.
+    // \todo Remove duplicate code for determining the active samples?
+#if defined(USE_SSE2)
+    int py0, py1;
+
+    getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1);
+
+    //const __m128i csteps = _mm_set_epi16(4,4,4,4,4,4,4,4);
+
+    __m128i yMask;
+
+    if (py0 <= 4 && py1 >= 4)
+        yMask = _mm_set1_epi8(-1);
+    else
+        yMask = _mm_set1_epi8(0);
+
+    const __m128i dir = _mm_set1_epi16(currAe.direction);
+
+    scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(yMask, dir));
+    //scanline.sseWinding = _mm_add_epi32(scanline.sseWinding, dir);
+
+#else
+    RI_ASSERT(false); // Not implemented yet.
+#endif
+}
+
+RI_INLINE void calculateAEWinding(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& pixel, Rasterizer::Windings& scanline, int intY, int pixelX)
+{
+#define QUEEN_COORD(Y) ((Y<<(Rasterizer::RASTERIZER_BITS - Rasterizer::SAMPLE_BITS)) + (1<<(Rasterizer::RASTERIZER_BITS-Rasterizer::SAMPLE_BITS-1)))
+
+#if !defined(USE_SSE2)
+    static const int queenCoords[(1<<Rasterizer::SAMPLE_BITS)] = {
+        QUEEN_COORD(3), QUEEN_COORD(7), QUEEN_COORD(0), QUEEN_COORD(2),
+        QUEEN_COORD(5), QUEEN_COORD(1), QUEEN_COORD(6), QUEEN_COORD(4)
+    };
+
+    const int ix = pixelX >> Rasterizer::RASTERIZER_BITS;
+    const int cy = intY << Rasterizer::Y_BITS;
+
+    const int py0 = cy > currAe.yStart ? 0 : currAe.yStart & Rasterizer::Y_MASK;
+    const int py1 = (RI_INT_MIN(currAe.yEnd, cy + (1<<Rasterizer::Y_BITS)) - 1) & Rasterizer::Y_MASK;
+
+    int edgeX = currAe.xRef + (cy + py0 - (currAe.yStart & ~Rasterizer::Y_MASK)) * currAe.slope;
+
+    RI_ASSERT(py1 >= py0);
+
+    for (int s = py0; s <= py1; s++)
+    {
+        const int sampleX = pixelX + queenCoords[s];
+
+        //compute winding number by evaluating the edge functions of edges to the left of the sampling point
+        if(((edgeX >> Rasterizer::RASTERIZER_BITS) == ix))
+        {
+            if (sampleX >= edgeX)
+            {
+                pixel.winding[s] += currAe.direction;
+            }
+            scanline.winding[s] += currAe.direction;
+        }
+
+        edgeX += currAe.slope;
+    }
+#else
+
+    __m128i qCoords = _mm_set_epi16(
+        QUEEN_COORD(4), QUEEN_COORD(6), QUEEN_COORD(1), QUEEN_COORD(5),
+        QUEEN_COORD(2), QUEEN_COORD(0), QUEEN_COORD(7), QUEEN_COORD(3));
+
+    RI_ASSERT(Rasterizer::RASTERIZER_BITS <= 14);
+
+    // TEROP: Optimize conditions.
+    int py0, py1;
+    getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1);
+
+    const int cy = intY << Rasterizer::Y_BITS;
+
+    const __m128i csteps0 = _mm_set_epi32(3,2,1,0);
+    const __m128i csteps1 = _mm_set_epi32(7,6,5,4);
+
+    const __m128i ssePy0 = _mm_set1_epi32(py0-1);
+    const __m128i ssePy1 = _mm_set1_epi32(py1+1);
+
+    const __m128i yMask0 = _mm_and_si128(_mm_cmpgt_epi32(csteps0, ssePy0), _mm_cmplt_epi32(csteps0, ssePy1));
+    const __m128i yMask1 = _mm_and_si128(_mm_cmpgt_epi32(csteps1, ssePy0), _mm_cmplt_epi32(csteps1, ssePy1));
+
+    const int edgeX = currAe.xRef + (cy - (currAe.yStart & ~Rasterizer::Y_MASK)) * currAe.slope;
+    const __m128i xStart = _mm_set1_epi32(edgeX - pixelX);
+
+    const __m128i xs0 = _mm_set1_epi32(currAe.slope);
+
+    __m128i xAdd0 = mm_mul4x32(xs0, csteps0);
+    __m128i xAdd1 = mm_mul4x32(xs0, csteps1);
+    __m128i coords0 = _mm_add_epi32(xStart, xAdd0);
+    __m128i coords1 = _mm_add_epi32(xStart, xAdd1);
+    __m128i coords = _mm_packs_epi32(coords0, coords1);
+
+    __m128i dir = _mm_set1_epi16(currAe.direction);
+    __m128i yMask = _mm_packs_epi32(yMask0, yMask1);
+    __m128i mDir = _mm_and_si128(dir, yMask);
+
+    __m128i sampleCoords = qCoords;
+
+    __m128i sw, pw;
+    mm_get_xmasks(coords, sampleCoords, sw, pw);
+
+    pixel.sseWinding = _mm_add_epi16(pixel.sseWinding, _mm_and_si128(pw, mDir));
+    scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(sw, mDir));
+#endif
+
+#undef QUEEN_COORD
+
+}
+
+/**
+ * \brief   Calculate winding using one sample only.
+ * \note    This uses most of the same code as the AA-case even though it is not
+ *          necessary (one sample would be enough).
+ */
+RI_INLINE void calculateAEWindingNoAA(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& pixel, Rasterizer::Windings& scanline, int intY, int pixelX)
+{
+#if defined(USE_SSE2)
+
+#define QUEEN_COORD(Y) ((Y<<(Rasterizer::RASTERIZER_BITS - Rasterizer::SAMPLE_BITS)) + (1<<(Rasterizer::RASTERIZER_BITS-Rasterizer::SAMPLE_BITS-1)))
+    const int half = 1<<(Rasterizer::RASTERIZER_BITS-1);
+
+    __m128i sampleCoords = _mm_set1_epi16(half);
+
+    RI_ASSERT(Rasterizer::RASTERIZER_BITS <= 14);
+
+    const int cy = intY << Rasterizer::Y_BITS;
+
+    int py0, py1;
+    getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1);
+
+    __m128i yMask;
+
+    if (py0 <= 4 && py1 >= 4)
+        yMask = _mm_set1_epi8(-1);
+    else
+        yMask = _mm_set1_epi8(0);
+
+    const __m128i csteps0 = _mm_set_epi32(4,4,4,4);
+    const __m128i csteps1 = _mm_set_epi32(4,4,4,4);
+
+    const int edgeX = currAe.xRef + (cy - (currAe.yStart & ~Rasterizer::Y_MASK)) * currAe.slope;
+    const __m128i xStart = _mm_set1_epi32(edgeX - pixelX);
+
+    const __m128i xs0 = _mm_set1_epi32(currAe.slope);
+
+    __m128i xAdd0 = mm_mul4x32(xs0, csteps0);
+    __m128i xAdd1 = mm_mul4x32(xs0, csteps1);
+    __m128i coords0 = _mm_add_epi32(xStart, xAdd0);
+    __m128i coords1 = _mm_add_epi32(xStart, xAdd1);
+    __m128i coords = _mm_packs_epi32(coords0, coords1);
+
+    __m128i dir = _mm_set1_epi16(currAe.direction);
+    __m128i mDir = _mm_and_si128(dir, yMask);
+    //__m128i mDir = dir;
+
+    __m128i sw, pw;
+    mm_get_xmasks(coords, sampleCoords, sw, pw);
+
+    pixel.sseWinding = _mm_add_epi16(pixel.sseWinding, _mm_and_si128(pw, mDir));
+    scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(sw, mDir));
+
+#undef QUEEN_COORD
+
+#else
+    RI_ASSERT(false); // Not implemented.
+#endif
+}
+
+#if defined(USE_SSE2)
+RI_INLINE static int mm_winding_to_coverage(const Rasterizer::Windings& pixel, int fillRuleMask)
+{
+    // This version uses SSE2 counters.
+    __m128i mask = _mm_set1_epi16(fillRuleMask);
+    __m128i t = _mm_and_si128(mask, pixel.sseWinding);
+    __m128i z = _mm_setzero_si128();
+    __m128i isz = _mm_cmpeq_epi16(t, z);
+    __m128i ones = _mm_set1_epi16(1);
+    __m128i res = _mm_add_epi16(ones, isz);
+    __m128i add0 = _mm_add_epi16(res, _mm_shuffle_epi32(res, _MM_SHUFFLE(2, 3, 2, 3)));
+    __m128i add1 = _mm_add_epi16(add0, _mm_shuffle_epi32(add0, _MM_SHUFFLE(1, 1, 1, 1)));
+    __m128i add2 = _mm_add_epi16(add1, _mm_shufflelo_epi16(add1, _MM_SHUFFLE(1, 1, 1, 1)));
+
+    int nSamples = _mm_cvtsi128_si32(add2) & 0xff;
+    return nSamples;
+}
+#endif
+
+#define RI_DEBUG
+#if defined(RI_DEBUG)
+void maybeDumpEdges(Array<Rasterizer::ActiveEdge> &edgePool)
+{
+    return;
+    // \note This gives an idea about the edges at the rasterization stage.
+    // Input edges must be output at a different stage.
+    RI_PRINTF("lines = []\n");
+    for (int i = 0 ; i < edgePool.size(); i++)
+    {
+        const int slope = edgePool[i].slope;
+        int x0, x1, y0, y1;
+        y0 = edgePool[i].yStart;
+        y1 = edgePool[i].yEnd;
+        x0 = edgePool[i].xRef + (slope * (y0 & Rasterizer::Y_MASK));
+        x1 = (edgePool[i].xRef + (slope * (y1 - (y0 & ~Rasterizer::Y_MASK))))>>(Rasterizer::RASTERIZER_BITS-Rasterizer::X_BITS);
+        RI_PRINTF("lines += [[%d, %d], [%d, %d]]\n",x0>>(Rasterizer::RASTERIZER_BITS-Rasterizer::X_BITS),y0,x1,y1);
+    }
+}
+#endif
+
+/*-------------------------------------------------------------------*//*!
+* \brief	Calls PixelPipe::pixelPipe for each pixel with coverage greater
+*			than zero.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+void Rasterizer::fill()
+{
+    if(m_scissor && !m_scissorEdges.size())
+        return;	//scissoring is on, but there are no scissor rectangles => nothing is visible
+
+    int firstAe = 0;
+
+    //proceed scanline by scanline
+    //keep track of edges that can intersect the pixel filters of the current scanline (Active Edge Table)
+    //until all pixels of the scanline have been processed
+    //  for all sampling points of the current pixel
+    //    determine the winding number using edge functions
+    //    add filter weight to coverage
+    //  divide coverage by the number of samples
+    //  determine a run of pixels with constant coverage
+    //  call fill callback for each pixel of the run
+
+    const int fillRuleMask = m_fillRuleMask;
+
+    int bbminx = (m_edgeMin.x >> X_BITS);
+    int bbminy = (m_edgeMin.y >> Y_BITS);
+    int bbmaxx = (m_edgeMax.x >> X_BITS)+1;
+    int bbmaxy = (m_edgeMax.y >> Y_BITS)+1;
+    int sx = RI_INT_MAX(m_vpx, bbminx);
+    int ex = RI_INT_MIN(m_vpx+m_vpwidth, bbmaxx);
+    int sy = RI_INT_MAX(m_vpy, bbminy);
+    int ey = RI_INT_MIN(m_vpy+m_vpheight, bbmaxy);
+    if(sx < m_covMinx) m_covMinx = sx;
+    if(sy < m_covMiny) m_covMiny = sy;
+    if(ex > m_covMaxx) m_covMaxx = ex;
+    if(ey > m_covMaxy) m_covMaxy = ey;
+
+#if 0
+    // Dump edges:
+    static bool dump = true;
+    if (dump)
+    {
+        RI_PRINTF("lines = []\n");
+        for (int ie = 0; dump && ie < m_edgePool.size(); ie++)
+        {
+            RI_PRINTF("lines += [[%d, %d], [%d, %d]]\n",m_edgePool[ie].v0.x, m_edgePool[ie].v0.y, m_edgePool[ie].v1.x, m_edgePool[ie].v1.y);
+        }
+        dump = false;
+    }
+
+#endif
+    int debugMagic = 0;
+
+    m_aet.clear();
+
+#if defined(RI_DEBUG)
+    maybeDumpEdges(m_edgePool);
+#endif
+
+    //fill the screen
+    for(int j = sy; j < ey; j++)
+    {
+        Windings scanlineWinding;
+        const int cminy = j << Y_BITS;
+
+        if (m_scissor)
+        {
+            // Gather scissor edges intersecting this scanline
+            // \todo Don't clear, remove unused instead!
+            m_scissorAet.clear();
+
+            for(int e = 0; e < m_scissorEdges.size(); e++)
+            {
+                const ScissorEdge& se = m_scissorEdges[e];
+
+                if(j >= se.miny && j < se.maxy)
+                    m_scissorAet.push_back(m_scissorEdges[e]);	//throws bad_alloc
+            }
+
+            //sort scissor AET by edge x
+            if (m_scissor)
+                m_scissorAet.sort();
+        }
+
+        // Drop unused edges, update remaining.
+        // \todo Combine with full sweep. Use a sort-friendly edge-discard.
+        for (int iae = firstAe; iae < m_aet.size(); iae++)
+        {
+            ActiveEdge& ae = m_aet[iae];
+
+            if (cminy >= ae.yEnd)
+            {
+                m_aet[iae] = m_aet[firstAe];
+                firstAe++;
+                continue;
+            }
+
+            /* Update existing coordinates */
+            // \todo AND instead of shift. See other places also.
+            const int y0 = (ae.yStart & ~Y_MASK);
+            const int x = ae.xRef + ((j << Y_BITS) - y0) * ae.slope;
+            ae.minx = x >> RASTERIZER_BITS;
+            ae.maxx = (x + ae.slope * (1<<Y_BITS)) >> RASTERIZER_BITS;
+
+            if (ae.minx > ae.maxx)
+                RI_ANY_SWAP(ActiveEdge::XCoord, ae.minx, ae.maxx);
+
+            // If the edge is not visible, "mark" it as immediately applicable
+            // \todo Verify that this is the correct procedure.
+
+           if (ae.maxx < 0)
+               ae.minx = ae.maxx = LEFT_DISCARD_SHORT;
+       }
+
+        /* Add new edges */
+
+        RIuint32 aeIndex = m_edges[j];
+        while (aeIndex != EDGE_TERMINATOR)
+        {
+            const ActiveEdge& ae = m_edgePool[aeIndex];
+            m_aet.push_back(ae); // \todo Just copy pointers?
+            aeIndex = ae.next;
+        }
+
+        if (firstAe >= m_aet.size())
+        {
+            RI_ASSERT(firstAe == m_aet.size());
+            continue;	//no edges on the whole scanline, skip it
+        }
+
+        //sort AET by edge minx
+        m_aet.sort(firstAe, m_aet.size() - 1);
+
+        // \todo Optimize adding and updating the edges?
+        if (m_scissor && !m_scissorAet.size())
+            continue;	// Scissoring is on, but there are no scissor rectangles on this scanline.
+
+        //fill the scanline
+        int scissorWinding = m_scissor ? 0 : 1;	//if scissoring is off, winding is always 1
+        int scissorIndex = 0;
+        int aes = firstAe;
+        int aen = firstAe;
+
+        RI_ASSERT(sx >= 0);
+
+#if 1
+        if (m_aa)
+        {
+            while ((aen < m_aet.size()) && (m_aet[aen].maxx < 0))
+            {
+                applyLeftEdge(m_aet[aen], scanlineWinding, j);
+                aen++;
+            }
+        }
+        else
+        {
+            while ((aen < m_aet.size()) && (m_aet[aen].maxx < 0))
+            {
+                applyLeftEdgeNoAA(m_aet[aen], scanlineWinding, j);
+                aen++;
+            }
+        }
+
+#if defined(RI_DEBUG)
+        for (int a = aen; a < m_aet.size(); a++)
+        {
+            RI_ASSERT(m_aet[a].maxx >= 0);
+        }
+#endif
+#endif
+
+        // \todo Combine this with the first check or reorganize the "clipping".
+        if (aen >= m_aet.size())
+            continue; // No edges within viewport. Can happen atm. when all edges are "left".
+
+        for(int i = sx; i < ex;)
+        {
+            //find edges that intersect or are to the left of the pixel antialiasing filter
+            while(aes < m_aet.size() && (i + 1) >= m_aet[aes].minx)
+                aes++;
+            //edges [0,aes[ may have an effect on winding, and need to be evaluated while sampling
+
+            // RIint8 winding[SF_SAMPLES];
+            Windings pixelWinding;
+
+            pixelWinding = scanlineWinding;
+
+            if (m_aa)
+            {
+                for(int e = aen; e < aes; e++)
+                {
+                    const ActiveEdge& currAe = m_aet[e];
+                    calculateAEWinding(currAe, pixelWinding, scanlineWinding, j, i << RASTERIZER_BITS);
+                }
+            }
+            else
+            {
+                for(int e = aen; e < aes; e++)
+                {
+                    const ActiveEdge& currAe = m_aet[e];
+                    calculateAEWindingNoAA(currAe, pixelWinding, scanlineWinding, j, i << RASTERIZER_BITS);
+                }
+            }
+
+            //compute coverage
+            int coverageSamples = 0;
+#if !defined(USE_SSE2)
+
+            for (int s = 0; s < SF_SAMPLES; s++)
+            {
+                if(pixelWinding.winding[s])
+                {
+                    coverageSamples++;
+                }
+            }
+#else
+           coverageSamples = mm_winding_to_coverage(pixelWinding, fillRuleMask);
+            _mm_empty();
+#endif
+
+            //constant coverage optimization:
+            //scan AET from left to right and skip all the edges that are completely to the left of the pixel filter.
+            //since AET is sorted by minx, the edge we stop at is the leftmost of the edges we haven't passed yet.
+            //if that edge is to the right of this pixel, coverage is constant between this pixel and the start of the edge.
+            while(aen < m_aet.size() && m_aet[aen].maxx < i)
+                aen++;
+
+            int endSpan = m_vpx + m_vpwidth;	// endSpan is the first pixel NOT part of the span
+
+            if(aen < m_aet.size())
+            {
+                endSpan = RI_INT_MAX(i+1, RI_INT_MIN(endSpan, m_aet[aen].minx));
+            }
+
+            //fill a run of pixels with constant coverage
+            if(coverageSamples)
+            {
+
+                if (!m_scissor)
+                {
+                    int fillStartX = i;	/* Inclusive */
+                    pushSpan(fillStartX, j, (endSpan - fillStartX), coverageSamples);
+                }
+                else // (scissor)
+                {
+                    int fillStartX = i;
+                    //update scissor winding number
+
+                    /* \todo Sort the scissor edges and skip unnecessary checks when scissors are used */
+                    while (scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x <= fillStartX)
+                    {
+                        scissorWinding += m_scissorAet[scissorIndex++].direction;
+                    }
+
+                    while (!scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x < endSpan)
+                    {
+                        fillStartX = m_scissorAet[scissorIndex].x;
+                        scissorWinding += m_scissorAet[scissorIndex++].direction;
+                        RI_ASSERT(fillStartX >= i);
+                    }
+
+                    RI_ASSERT(scissorWinding >= 0);
+
+                    int endScissorSpan = endSpan;
+
+                    while (scissorWinding && fillStartX < endSpan && (scissorIndex < m_scissorAet.size()))
+                    {
+
+                        // Determine the end of renderable area:
+                        while (scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x <= endSpan)
+                        {
+                            endScissorSpan = m_scissorAet[scissorIndex].x;
+                            scissorWinding += m_scissorAet[scissorIndex++].direction;
+                        }
+
+                        RI_ASSERT(fillStartX >= i);
+                        RI_ASSERT(endScissorSpan <= endSpan);
+
+                        pushSpan(fillStartX, j, (endScissorSpan - fillStartX), coverageSamples);
+                        fillStartX = endScissorSpan;
+                        endScissorSpan = endSpan;
+
+                        // Skip until within drawable area
+                        while (!scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x < endSpan)
+                        {
+                            fillStartX = m_scissorAet[scissorIndex].x;
+                            scissorWinding += m_scissorAet[scissorIndex++].direction;
+                        }
+
+                    }
+                }
+            }
+            i = endSpan;
+        }
+    }
+    commitSpans();
+#if defined(USE_SSE2)
+    _mm_empty();
+#endif
+    clear();
+}
+
+RI_INLINE void Rasterizer::commitSpans()
+{
+    if (!m_nSpans)
+        return;
+
+    m_pixelPipe->fillSpans(m_ppVariants, m_spanCache, m_nSpans);
+    m_nSpans = 0;
+
+}
+
+RI_INLINE void Rasterizer::pushSpan(int x, int y, int len, int coverage)
+{
+    //printf("x: %d, y: %d, len: %d, coverage: %d\n", x, y, len, coverage);
+    // \todo Check what causes this with scissors
+    if (len <= 0) return;
+    //RI_ASSERT(len > 0);
+
+    Span& span = m_spanCache[m_nSpans];
+
+    span.x0 = x;
+    span.y = y;
+    span.len = (RIuint16)len;
+    span.coverage = coverage;
+
+    m_nSpans++;
+
+    if (m_nSpans == N_CACHED_SPANS)
+    {
+        commitSpans();
+    }
+}
+
+//=======================================================================
+
+}	//namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riRasterizer.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,279 @@
+#ifndef __RIRASTERIZER_H
+#define __RIRASTERIZER_H
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -----------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief   Rasterizer class.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#ifndef __RIMATH_H
+#include "riMath.h"
+#endif
+
+#ifndef __RIARRAY_H
+#include "riArray.h"
+#endif
+
+#ifndef __RIPIXELPIPE_H
+#include "riPixelPipe.h"
+#endif
+
+// TESTING ONLY!!
+#include "sfDynamicPixelPipe.h"
+
+#if defined(RI_DEBUG)
+#    include <stdio.h>
+#endif
+// \todo SSE2 probably has everything necessary and matches the minimum platform requirements.
+// SSE4 is probably too new. SSE3?
+// \note This will cause the code to not compile on MSVC...
+#define USE_SSE2
+
+#if defined(USE_SSE2)
+// \todo only the last include is needed: QT creator does not find types if others not included.
+#   include <mmintrin.h>
+#   include <xmmintrin.h>
+#   include <emmintrin.h>
+#endif
+
+//=======================================================================
+
+namespace OpenVGRI
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Scalar and vector data types used by the rasterizer.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+typedef RIfloat RScalar;    //change this if you want to have different precision for rasterizer scalars and RIfloat
+
+struct RVector2
+{
+    RI_INLINE RVector2()                            { }
+    RI_INLINE RVector2(const Vector2& v)            { x = v.x; y = v.y; }
+    RI_INLINE RVector2(RIfloat vx, RIfloat vy)      { x = vx; y = vy; }
+    RI_INLINE void set(RIfloat vx, RIfloat vy)      { x = vx; y = vy; }
+    RScalar     x;
+    RScalar     y;
+};
+
+struct IVector2
+{
+    RI_INLINE IVector2() {}
+    RI_INLINE IVector2(const IVector2& v) { x = v.x; y = v.y; }
+    RI_INLINE IVector2(const Vector2& v) { x = (int)v.x; y = (int) v.y; }
+    RI_INLINE IVector2(int vx, int vy) { x = vx; y = vy; }
+    RI_INLINE void set(int vx, int vy) { x = vx; y = vy; }
+    int x;
+    int y;
+};
+
+struct Span
+{
+    RIuint16 x0;
+    RIuint16 y;
+    RIuint16 len;
+    RIuint8  coverage;
+    RIuint8  pad; // align to 8 bytes. \temp Use qualifiers instead?
+};
+
+/*-------------------------------------------------------------------*//*!
+* \brief    Converts a set of edges to coverage values for each pixel and
+*           calls PixelPipe::pixelPipe for painting a pixel.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+class Rasterizer
+{
+public:
+    Rasterizer();   //throws bad_alloc
+    ~Rasterizer();
+
+    void        setup(int vpx, int vpy, int vpwidth, int vpheight, VGFillRule fillRule, const PixelPipe* pixelPipe);
+    void        setScissor(const Array<Rectangle>& scissors);   //throws bad_alloc
+    void        setScissoring(bool enabled);
+
+    void        clear();
+    void        addEdge(const Vector2& v0, const Vector2& v1);  //throws bad_alloc
+
+    RI_INLINE void setAntiAliasing(bool enable) { m_aa = enable; }
+    void        fill(); //throws bad_alloc
+
+    void        getBBox(int& sx, int& sy, int& ex, int& ey) const       { sx = m_covMinx; sy = m_covMiny; ex = m_covMaxx; ey = m_covMaxy; }
+
+public:
+    enum { SAMPLE_BITS = 3 };
+    enum { Y_BITS = SAMPLE_BITS };
+    enum { MAX_COVERAGE = 1<<SAMPLE_BITS };
+
+    // temp!:
+    RIuint32    *m_covBuffer;
+    size_t      m_covBufferSz;
+
+private:
+    Rasterizer(const Rasterizer&);                      //!< Not allowed.
+    const Rasterizer& operator=(const Rasterizer&);     //!< Not allowed.
+
+public:
+    struct ScissorEdge
+    {
+        ScissorEdge() {}
+        bool operator<(const ScissorEdge& e) const  { return x < e.x; }
+        int         x;
+        int         miny;
+        int         maxy;
+        int         direction;      //1 start, -1 end
+    };
+
+    struct Edge
+    {
+        Edge() {}
+        bool operator<(const Edge& e) const { return v0.y < e.v0.y; }
+#if defined(RI_DEBUG)
+        bool operator<=(const Edge& e) const {return v0.y <= e.v0.y; }
+#endif
+        IVector2    v0;
+        IVector2    v1;
+        int         direction;
+    };
+
+    struct ActiveEdge
+    {
+        typedef RIint16 XCoord;
+        typedef RIint16 YCoord;
+
+        ActiveEdge() {}
+        //bool operator<(const ActiveEdge& e) const   { return minx < e.minx; }
+        bool operator<(const ActiveEdge& e) const
+        {
+            if (minx < e.minx)
+                return true;
+            if (minx == e.minx)
+                return maxx < e.maxx;
+            return false;
+        }
+#if defined(RI_DEBUG)
+        bool operator<=(const ActiveEdge& e) const { return minx <= e.minx; }
+#endif
+        // Fixed-point edge coordinates.
+        RIuint32 next; // \todo Pointer?
+        int     direction;      //-1 down, 1 up
+        int     xRef;
+        int     slope;
+        XCoord  minx;           // for the current scanline
+        XCoord  maxx;           // for the current scanline
+        YCoord  yStart;         // for the edge
+        YCoord  yEnd;           // for the edge
+    };
+
+    enum { SF_SAMPLES = 8 };
+    enum { RASTERIZER_BITS = 14 };
+    enum { RASTERIZER_MASK = ((1<<RASTERIZER_BITS)-1) };
+    enum { Y_MASK = ((1<<Y_BITS)-1) };
+    enum { X_BITS = 7 };
+    enum { XMASK  = ((1<<X_BITS)-1) };
+    enum { LEFT_DISCARD = -0x100000 };
+    enum { LEFT_DISCARD_SHORT = -32768 };
+
+    struct Windings
+    {
+#if !defined(USE_SSE2)
+        Windings() {wq = 0;}
+        // \todo Use SSE counters or packed counters!
+        // \todo 8 samples -> 64 bits == 2 32-bit uints
+        union
+        {
+            RIint8              winding[SF_SAMPLES];
+            RIuint32            wd[SF_SAMPLES/4];
+            unsigned long long  wq;
+        };
+#else
+        Windings() { sseWinding = _mm_setzero_si128(); }
+        __m128i sseWinding;
+#endif
+     };
+
+private:
+    void                pushEdge(const Edge& edge);
+    void                clipAndAddEdge(Edge& edge);
+    void                addBBox(const IVector2& v);
+    RI_INLINE void      pushSpan(int x, int y, int len, int coverage);
+    RI_INLINE void      commitSpans();
+
+    //RI_INLINE void      calculateAEWinding(const ActiveEdge& currAe, Windings& pixel, Windings& scanline, int intY, int pixelX);
+
+    Array<ActiveEdge>   m_edgePool;
+    Array<RIuint32>     m_edges;
+    Array<ScissorEdge>  m_scissorEdges;
+    Array<ActiveEdge>   m_aet;
+    Array<ScissorEdge>  m_scissorAet;
+    bool                m_scissor;
+
+    bool                    m_aa;
+
+    IVector2            m_edgeMin;
+    IVector2            m_edgeMax;
+    int                 m_covMinx;
+    int                 m_covMiny;
+    int                 m_covMaxx;
+    int                 m_covMaxy;
+    int                 m_vpx;
+    int                 m_vpy;
+    int                 m_vpwidth;
+    int                 m_vpheight;
+    int                 m_vpMinx;
+    int                 m_vpMiny;
+    int                 m_vpMaxx;
+    int                 m_vpMaxy;
+    VGFillRule          m_fillRule;
+    RIuint32            m_fillRuleMask;
+
+    const PixelPipe*        m_pixelPipe;
+    PixelPipe::PPVariants   m_ppVariants;
+
+    enum { N_CACHED_SPANS = 64 };
+    Span                m_spanCache[N_CACHED_SPANS];
+    int                 m_nSpans;
+
+};
+
+//=======================================================================
+
+}   //namespace OpenVGRI
+
+//=======================================================================
+
+#endif /* __RIRASTERIZER_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riUtils.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,240 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __RIUTILS_H_
+#   include "riUtils.h"
+#endif
+
+#include <string.h>
+
+namespace OpenVGRI
+{
+
+/**
+ * \brief   Sets mem areas to byte(s) in c.
+ * \param   dst     Destination pointer.
+ * \param   c       Data to set into dst.
+ * \param   nElements   Amount of elements to set.
+ * \param   nBytesPerElement    Amount of bytes for each element.
+ * \note    This is moslty an image-settings support function. It is assumed that several
+ *          bytes / elements can be set at once, especially in 3-byte case.
+ */
+void riMemSet32(void* dst, RIuint32 c, size_t nElements, size_t nBytesPerElement)
+{
+    // \todo This function should be called from a function that handles npot element sizes.
+    // \todo Investigate the status of (open) std::fill implementations. Some of that code 
+    // did not _seem_ to bundle sets or use SSE, etc.
+    // \todo Use SSE instructions on Intel? 
+    
+    RI_ASSERT(dst);
+    RI_ASSERT(nElements);
+
+    switch(nBytesPerElement)
+    {
+    case 4:
+    {
+        RIuint32* ptr = (RIuint32*)dst;
+        do {
+            *ptr++ = c;
+        } while(--nElements);
+        break;
+    }
+    case 3:
+    {
+        // \todo Endianness.
+        RIuint8* ptr = (RIuint8*)dst;
+        RIuint8 b[3];
+        b[0] = c & 0xff;
+        b[1] = (c >> 8)&0xff;
+        b[2] = (c >> 16)&0xff;
+        do {
+            *ptr++ = b[0];
+            *ptr++ = b[1];
+            *ptr++ = b[2];
+        } while(--nElements);
+        break;
+    }
+    case 2:
+    {
+        size_t dws = nElements / 2; 
+        if (dws)
+        {
+            RIuint32* ptr32 = (RIuint32*)dst;
+            dst = (void*)(((RIuint8*)dst + dws * 4));
+            RIuint32 dw = c | (c<<16);
+            do {
+                *ptr32++ = dw;
+            } while(--dws);
+            nElements &= 0x01;
+        }
+        if (nElements)
+        {
+            RIuint16 *ptr16 = (RIuint16*)dst;
+            const RIuint16 w = (RIuint16)c;
+            do {
+                *ptr16++ = w;
+            } while(--nElements);
+        }
+        break;
+    }
+    default:
+    {
+        RI_ASSERT(nBytesPerElement == 1);
+        memset(dst, c, nElements);
+        break;
+    }
+    }
+
+}
+
+/**
+ * \brief   Insert bits into an array of 32-bit integers.
+ * \param   hashSize    Size of array in bytes.
+ * \param   bits        Actual bits to insert.
+ * \param   bitSize     Amount of bits to insert (max 32).
+ * \param   bitPtr      Pointer to first bit to insert [0 .. (hashSize*8)-1]
+ */
+int riInsertBits32(RIuint32* hash, size_t hashSize, RIuint32 bits, RIuint32 bitSize, int bitPtr)
+{
+    RI_ASSERT(bitSize > 0 && bitSize <= 32);
+    RI_ASSERT(bits < (1u<<bitSize));
+    RI_ASSERT((bitPtr + bitSize) < (hashSize * 32));
+
+    int idw = bitPtr >> 5;
+    int ib = bitPtr - (idw << 5);
+
+    if ((ib + bitSize) > 32)
+    {
+        int rb = ((ib + bitSize) - 32) + 1;
+        RI_ASSERT(rb > 0);
+        hash[idw] |= (bits << ib);
+        hash[idw] |= (bits >> rb);
+    } 
+    else
+    {
+        int new_ib = (ib + bitSize) & 0x1f;
+        RI_ASSERT((ib + bitSize == 32) ? new_ib == 0 : true);
+        hash[idw] |= (bits << ib);
+    }
+    return bitPtr + bitSize;
+}
+
+/**
+ * \brief   Convert an image format to (internal) index.
+ */
+int riVGImageFormatToIndex(VGImageFormat format)
+{
+    switch(format)
+    {
+    /* RGB{A,X} channel ordering */
+    case VG_sRGBX_8888:
+        return 0;
+    case VG_sRGBA_8888:
+        return 1;
+    case VG_sRGBA_8888_PRE:
+        return 2;
+    case VG_sRGB_565:
+        return 3;
+    case VG_sRGBA_5551:
+        return 4;
+    case VG_sRGBA_4444:
+        return 5;
+    case VG_sL_8:
+        return 6;
+    case VG_lRGBX_8888:
+        return 7;
+    case VG_lRGBA_8888:
+        return 8;
+    case VG_lRGBA_8888_PRE:
+        return 9;
+    case VG_lL_8:
+        return 10;
+    case VG_A_8:
+        return 11;
+    case VG_BW_1:
+        return 12;
+    case VG_A_1:
+        return 13;
+    case VG_A_4:
+        return 14;
+
+    /* {A,X}RGB channel ordering */
+    case VG_sXRGB_8888:
+        return 15;
+    case VG_sARGB_8888:
+        return 16;
+    case VG_sARGB_8888_PRE:
+        return 17;
+    case VG_sARGB_1555:
+        return 18;
+    case VG_sARGB_4444:
+        return 19;
+    case VG_lXRGB_8888:
+        return 20;
+    case VG_lARGB_8888:
+        return 21;
+    case VG_lARGB_8888_PRE:
+        return 22;
+
+    /* BGR{A,X} channel ordering */
+    case VG_sBGRX_8888:
+        return 23;
+    case VG_sBGRA_8888:
+        return 24;
+    case VG_sBGRA_8888_PRE:
+        return 25;
+    case VG_sBGR_565:
+        return 26;
+    case VG_sBGRA_5551:
+        return 27;
+    case VG_sBGRA_4444:
+        return 28;
+    case VG_lBGRX_8888:
+        return 29;
+    case VG_lBGRA_8888:
+        return 30;
+    case VG_lBGRA_8888_PRE:
+        return 31;
+
+    /* {A,X}BGR channel ordering */
+    case VG_sXBGR_8888:
+        return 32;
+    case VG_sABGR_8888:
+        return 33;
+    case VG_sABGR_8888_PRE:
+        return 34;
+    case VG_sABGR_1555:
+        return 35;
+    case VG_sABGR_4444:
+        return 36;
+    case VG_lXBGR_8888:
+        return 37;
+    case VG_lABGR_8888:
+        return 38;
+    default:
+        RI_ASSERT(format == VG_lABGR_8888_PRE);
+        return 39;
+    }
+}
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riUtils.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,63 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __RIUTILS_H_
+#define __RIUTILS_H_
+
+#ifndef __RIDEFS_H
+#   include "riDefs.h"
+#endif
+
+#include "VG/openvg.h"
+#include <string.h>
+
+// This file contains "utility" functions that did not "fit" into existing RI files.
+// Once more functionality is accumulated, the corresponding functions/classes should be
+// moved to proper files asap. For example, the memcopy functions could go into file
+// "riMemory.xxx".
+
+namespace OpenVGRI
+{
+
+            void    riMemSet32(void* dst, RIuint32 c, size_t nElements, size_t nBytesPerElement);
+RI_INLINE   void    ri_memcpy(void* dst, const void* src, size_t n);
+            int     riInsertBits32(RIuint32* hash, size_t hashSize, RIuint32 bits, RIuint32 bitSize, int bitPtr);
+            int     riVGImageFormatToIndex(VGImageFormat format);
+
+RI_INLINE void ri_memcpy(void* dst, const void* src, size_t n)
+{
+#if !defined(RI_DEBUG)
+    memcpy(dst, src, n);
+#else
+    RIuint8 *p = (RIuint8*)dst;
+    RIuint8 *q = (RIuint8*)src;
+    for (size_t i = 0; i < n; i++, p++, q++)
+    {
+        *p = *q;
+    }
+#endif
+}
+
+} // namespace OpenVG
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/riVGU.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,476 @@
+/*------------------------------------------------------------------------
+ *
+ * VGU library for OpenVG 1.1 Reference Implementation
+ * ---------------------------------------------------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Implementation of the VGU utility library for OpenVG
+ *//*-------------------------------------------------------------------*/
+
+#include "vgu.h"
+#include "openvg.h"
+#include "riMath.h"
+
+using namespace OpenVGRI;
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+static void append(VGPath path, int numSegments, const VGubyte* segments, int numCoordinates, const VGfloat* coordinates)
+{
+	RI_ASSERT(numCoordinates <= 26);
+
+	VGPathDatatype datatype = (VGPathDatatype)vgGetParameteri(path, VG_PATH_DATATYPE);
+	VGfloat scale = vgGetParameterf(path, VG_PATH_SCALE);
+	VGfloat bias = vgGetParameterf(path, VG_PATH_BIAS);
+
+	switch(datatype)
+	{
+	case VG_PATH_DATATYPE_S_8:
+	{
+		RIint8 data[26];
+		for(int i=0;i<numCoordinates;i++)
+			data[i] = (RIint8)floor((coordinates[i] - bias) / scale + 0.5f);	//add 0.5 for correct rounding
+		vgAppendPathData(path, numSegments, segments, data);
+		break;
+	}
+
+	case VG_PATH_DATATYPE_S_16:
+	{
+		RIint16 data[26];
+		for(int i=0;i<numCoordinates;i++)
+			data[i] = (RIint16)floor((coordinates[i] - bias) / scale + 0.5f);	//add 0.5 for correct rounding
+		vgAppendPathData(path, numSegments, segments, data);
+		break;
+	}
+
+	case VG_PATH_DATATYPE_S_32:
+	{
+		RIint32 data[26];
+		for(int i=0;i<numCoordinates;i++)
+			data[i] = (RIint32)floor((coordinates[i] - bias) / scale + 0.5f);	//add 0.5 for correct rounding
+		vgAppendPathData(path, numSegments, segments, data);
+		break;
+	}
+
+	default:
+	{
+		RI_ASSERT(datatype == VG_PATH_DATATYPE_F);
+		RIfloat32 data[26];
+		for(int i=0;i<numCoordinates;i++)
+			data[i] = (RIfloat32)((coordinates[i] - bias) / scale);
+		vgAppendPathData(path, numSegments, segments, data);
+		break;
+	}
+	}
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguLine(VGPath path, VGfloat x0, VGfloat y0, VGfloat x1, VGfloat y1)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	static const VGubyte segments[2] = {VG_MOVE_TO | VG_ABSOLUTE, VG_LINE_TO | VG_ABSOLUTE};
+	const VGfloat data[4] = {x0, y0, x1, y1};
+	append(path, 2, segments, 4, data);
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguPolygon(VGPath path, const VGfloat * points, VGint count, VGboolean closed)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if(!points || (((RIuintptr)points) & 3) || count <= 0)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	VGubyte segments[1] = {VG_MOVE_TO | VG_ABSOLUTE};
+	VGfloat data[2];
+	for(int i=0;i<count;i++)
+	{
+		data[0] = points[i*2+0];
+		data[1] = points[i*2+1];
+		append(path, 1, segments, 2, data);
+		segments[0] = VG_LINE_TO | VG_ABSOLUTE;
+	}
+	if(closed)
+	{
+		segments[0] = VG_CLOSE_PATH;
+		append(path, 1, segments, 0, data);
+	}
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguRect(VGPath path, VGfloat x, VGfloat y, VGfloat width, VGfloat height)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if(width <= 0 || height <= 0)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	static const VGubyte segments[5] = {VG_MOVE_TO | VG_ABSOLUTE,
+										VG_HLINE_TO | VG_ABSOLUTE,
+										VG_VLINE_TO | VG_ABSOLUTE,
+										VG_HLINE_TO | VG_ABSOLUTE,
+										VG_CLOSE_PATH};
+	const VGfloat data[5] = {x, y, x + width, y + height, x};
+	append(path, 5, segments, 5, data);
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguRoundRect(VGPath path, VGfloat x, VGfloat y, VGfloat width, VGfloat height, VGfloat arcWidth, VGfloat arcHeight)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if(width <= 0 || height <= 0)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	arcWidth = RI_CLAMP(arcWidth, 0.0f, width);
+	arcHeight = RI_CLAMP(arcHeight, 0.0f, height);
+
+	static const VGubyte segments[10] = {VG_MOVE_TO | VG_ABSOLUTE,
+										 VG_HLINE_TO | VG_ABSOLUTE,
+										 VG_SCCWARC_TO | VG_ABSOLUTE,
+										 VG_VLINE_TO | VG_ABSOLUTE,
+										 VG_SCCWARC_TO | VG_ABSOLUTE,
+										 VG_HLINE_TO | VG_ABSOLUTE,
+										 VG_SCCWARC_TO | VG_ABSOLUTE,
+										 VG_VLINE_TO | VG_ABSOLUTE,
+										 VG_SCCWARC_TO | VG_ABSOLUTE,
+										 VG_CLOSE_PATH};
+	const VGfloat data[26] = {x + arcWidth/2, y,
+							  x + width - arcWidth/2,
+							  arcWidth/2, arcHeight/2, 0, x + width, y + arcHeight/2,
+							  y + height - arcHeight/2,
+							  arcWidth/2, arcHeight/2, 0, x + width - arcWidth/2, y + height,
+							  x + arcWidth/2,
+							  arcWidth/2, arcHeight/2, 0, x, y + height - arcHeight/2,
+							  y + arcHeight/2,
+							  arcWidth/2, arcHeight/2, 0, x + arcWidth/2, y};
+	append(path, 10, segments, 26, data);
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguEllipse(VGPath path, VGfloat cx, VGfloat cy, VGfloat width, VGfloat height)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if(width <= 0 || height <= 0)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	static const VGubyte segments[4] = {VG_MOVE_TO | VG_ABSOLUTE,
+										VG_SCCWARC_TO | VG_ABSOLUTE,
+										VG_SCCWARC_TO | VG_ABSOLUTE,
+										VG_CLOSE_PATH};
+	const VGfloat data[12] = {cx + width/2, cy,
+							  width/2, height/2, 0, cx - width/2, cy,
+							  width/2, height/2, 0, cx + width/2, cy};
+	append(path, 4, segments, 12, data);
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguArc(VGPath path, VGfloat x, VGfloat y, VGfloat width, VGfloat height, VGfloat startAngle, VGfloat angleExtent, VGUArcType arcType)
+{
+	VGErrorCode error = vgGetError();	//clear the error state
+	if((arcType != VGU_ARC_OPEN && arcType != VGU_ARC_CHORD && arcType != VGU_ARC_PIE) || width <= 0.0f || height <= 0.0f)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	startAngle = RI_DEG_TO_RAD(startAngle);
+	angleExtent = RI_DEG_TO_RAD(angleExtent);
+
+	VGfloat w = width/2.0f;
+	VGfloat h = height/2.0f;
+
+	VGubyte segments[1];
+	VGfloat data[5];
+
+	segments[0] = VG_MOVE_TO | VG_ABSOLUTE;
+	data[0] = x + w * (VGfloat)cos(startAngle);
+	data[1] = y + h * (VGfloat)sin(startAngle);
+	append(path, 1, segments, 2, data);
+
+	data[0] = w;
+	data[1] = h;
+	data[2] = 0.0f;
+	VGfloat endAngle = startAngle + angleExtent;
+	if(angleExtent >= 0.0f)
+	{
+		segments[0] = VG_SCCWARC_TO | VG_ABSOLUTE;
+		for(VGfloat a = startAngle + RI_PI;a < endAngle; a += RI_PI)
+		{
+            if ((a + RI_PI) == a)
+                return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+			data[3] = x + w * (VGfloat)cos(a);
+			data[4] = y + h * (VGfloat)sin(a);
+			append(path, 1, segments, 5, data);
+		}
+	}
+	else
+	{
+		segments[0] = VG_SCWARC_TO | VG_ABSOLUTE;
+		for(VGfloat a = startAngle - RI_PI;a > endAngle; a -= RI_PI)
+		{
+            if ((a - RI_PI) == a)
+                return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+			data[3] = x + w * (VGfloat)cos(a);
+			data[4] = y + h * (VGfloat)sin(a);
+			append(path, 1, segments, 5, data);
+		}
+	}
+	data[3] = x + w * (VGfloat)cos(endAngle);
+	data[4] = y + h * (VGfloat)sin(endAngle);
+	append(path, 1, segments, 5, data);
+
+	if(arcType == VGU_ARC_CHORD)
+	{
+		segments[0] = VG_CLOSE_PATH;
+		append(path, 1, segments, 0, data);
+	}
+	else if(arcType == VGU_ARC_PIE)
+	{
+		segments[0] = VG_LINE_TO | VG_ABSOLUTE;
+		data[0] = x;
+		data[1] = y;
+		append(path, 1, segments, 2, data);
+		segments[0] = VG_CLOSE_PATH;
+		append(path, 1, segments, 0, data);
+	}
+
+	error = vgGetError();
+	if(error == VG_BAD_HANDLE_ERROR)
+		return VGU_BAD_HANDLE_ERROR;
+	else if(error == VG_PATH_CAPABILITY_ERROR)
+		return VGU_PATH_CAPABILITY_ERROR;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguComputeWarpQuadToSquare(VGfloat sx0, VGfloat sy0, VGfloat sx1, VGfloat sy1, VGfloat sx2, VGfloat sy2, VGfloat sx3, VGfloat sy3, VGfloat * matrix)
+{
+	if(!matrix || ((RIuintptr)matrix) & 3)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	VGfloat mat[9];
+	VGUErrorCode ret = vguComputeWarpSquareToQuad(sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3, mat);
+	if(ret == VGU_BAD_WARP_ERROR)
+		return VGU_BAD_WARP_ERROR;
+	Matrix3x3 m(mat[0], mat[3], mat[6],
+				mat[1], mat[4], mat[7],
+				mat[2], mat[5], mat[8]);
+	bool nonsingular = m.invert();
+	if(!nonsingular)
+		return VGU_BAD_WARP_ERROR;
+	matrix[0] = m[0][0];
+	matrix[1] = m[1][0];
+	matrix[2] = m[2][0];
+	matrix[3] = m[0][1];
+	matrix[4] = m[1][1];
+	matrix[5] = m[2][1];
+	matrix[6] = m[0][2];
+	matrix[7] = m[1][2];
+	matrix[8] = m[2][2];
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguComputeWarpSquareToQuad(VGfloat dx0, VGfloat dy0, VGfloat dx1, VGfloat dy1, VGfloat dx2, VGfloat dy2, VGfloat dx3, VGfloat dy3, VGfloat * matrix)
+{
+	if(!matrix || ((RIuintptr)matrix) & 3)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	//from Heckbert:Fundamentals of Texture Mapping and Image Warping
+	//Note that his mapping of vertices is different from OpenVG's
+	//(0,0) => (dx0,dy0)
+	//(1,0) => (dx1,dy1)
+	//(0,1) => (dx2,dy2)
+	//(1,1) => (dx3,dy3)
+
+	VGfloat diffx1 = dx1 - dx3;
+	VGfloat diffy1 = dy1 - dy3;
+	VGfloat diffx2 = dx2 - dx3;
+	VGfloat diffy2 = dy2 - dy3;
+
+	VGfloat det = diffx1*diffy2 - diffx2*diffy1;
+	if(det == 0.0f)
+		return VGU_BAD_WARP_ERROR;
+
+	VGfloat sumx = dx0 - dx1 + dx3 - dx2;
+	VGfloat sumy = dy0 - dy1 + dy3 - dy2;
+
+	if(sumx == 0.0f && sumy == 0.0f)
+	{	//affine mapping
+		matrix[0] = dx1 - dx0;
+		matrix[1] = dy1 - dy0;
+		matrix[2] = 0.0f;
+		matrix[3] = dx3 - dx1;
+		matrix[4] = dy3 - dy1;
+		matrix[5] = 0.0f;
+		matrix[6] = dx0;
+		matrix[7] = dy0;
+		matrix[8] = 1.0f;
+		return VGU_NO_ERROR;
+	}
+
+	VGfloat oodet = 1.0f / det;
+	VGfloat g = (sumx*diffy2 - diffx2*sumy) * oodet;
+	VGfloat h = (diffx1*sumy - sumx*diffy1) * oodet;
+
+	matrix[0] = dx1-dx0+g*dx1;
+	matrix[1] = dy1-dy0+g*dy1;
+	matrix[2] = g;
+	matrix[3] = dx2-dx0+h*dx2;
+	matrix[4] = dy2-dy0+h*dy2;
+	matrix[5] = h;
+	matrix[6] = dx0;
+	matrix[7] = dy0;
+	matrix[8] = 1.0f;
+	return VGU_NO_ERROR;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief	
+* \param	
+* \return	
+* \note		
+*//*-------------------------------------------------------------------*/
+
+VGUErrorCode RI_APIENTRY vguComputeWarpQuadToQuad(VGfloat dx0, VGfloat dy0, VGfloat dx1, VGfloat dy1, VGfloat dx2, VGfloat dy2, VGfloat dx3, VGfloat dy3, VGfloat sx0, VGfloat sy0, VGfloat sx1, VGfloat sy1, VGfloat sx2, VGfloat sy2, VGfloat sx3, VGfloat sy3, VGfloat * matrix)
+{
+	if(!matrix || ((RIuintptr)matrix) & 3)
+		return VGU_ILLEGAL_ARGUMENT_ERROR;
+
+	VGfloat qtos[9];
+	VGUErrorCode ret1 = vguComputeWarpQuadToSquare(sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3, qtos);
+	if(ret1 == VGU_BAD_WARP_ERROR)
+		return VGU_BAD_WARP_ERROR;
+
+	VGfloat stoq[9];
+	VGUErrorCode ret2 = vguComputeWarpSquareToQuad(dx0, dy0, dx1, dy1, dx2, dy2, dx3, dy3, stoq);
+	if(ret2 == VGU_BAD_WARP_ERROR)
+		return VGU_BAD_WARP_ERROR;
+
+	Matrix3x3 m1(qtos[0], qtos[3], qtos[6],
+				 qtos[1], qtos[4], qtos[7],
+				 qtos[2], qtos[5], qtos[8]);
+	Matrix3x3 m2(stoq[0], stoq[3], stoq[6],
+				 stoq[1], stoq[4], stoq[7],
+				 stoq[2], stoq[5], stoq[8]);
+	Matrix3x3 r = m2 * m1;
+
+	matrix[0] = r[0][0];
+	matrix[1] = r[1][0];
+	matrix[2] = r[2][0];
+	matrix[3] = r[0][1];
+	matrix[4] = r[1][1];
+	matrix[5] = r[2][1];
+	matrix[6] = r[0][2];
+	matrix[7] = r[1][2];
+	matrix[8] = r[2][2];
+	return VGU_NO_ERROR;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfAlphaRcp.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,66 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef _SFALPHARCP_H_
+#define _SFALPHARCP_H_
+
+#include "riDefs.h"
+
+namespace OpenVGRI {
+enum { ALPHA_RCP_BITS = 8};
+static const RIuint16 sc_alphaRcp[256] = {
+    0xff00,  0xff00,  0x7f80,  0x5500,  0x3fc0,  0x3300,  0x2a80,  0x246e,  
+    0x1fe0,  0x1c55,  0x1980,  0x172f,  0x1540,  0x139e,  0x1237,  0x1100,  
+    0xff0,  0xf00,  0xe2b,  0xd6c,  0xcc0,  0xc25,  0xb97,  0xb16,  
+    0xaa0,  0xa33,  0x9cf,  0x972,  0x91b,  0x8cb,  0x880,  0x83a,  
+    0x7f8,  0x7ba,  0x780,  0x749,  0x715,  0x6e4,  0x6b6,  0x68a,  
+    0x660,  0x638,  0x612,  0x5ee,  0x5cc,  0x5ab,  0x58b,  0x56d,  
+    0x550,  0x534,  0x51a,  0x500,  0x4e7,  0x4d0,  0x4b9,  0x4a3,  
+    0x48e,  0x479,  0x466,  0x452,  0x440,  0x42e,  0x41d,  0x40c,  
+    0x3fc,  0x3ec,  0x3dd,  0x3ce,  0x3c0,  0x3b2,  0x3a5,  0x397,  
+    0x38b,  0x37e,  0x372,  0x366,  0x35b,  0x350,  0x345,  0x33a,  
+    0x330,  0x326,  0x31c,  0x313,  0x309,  0x300,  0x2f7,  0x2ee,  
+    0x2e6,  0x2dd,  0x2d5,  0x2cd,  0x2c6,  0x2be,  0x2b6,  0x2af,  
+    0x2a8,  0x2a1,  0x29a,  0x293,  0x28d,  0x286,  0x280,  0x27a,  
+    0x274,  0x26e,  0x268,  0x262,  0x25c,  0x257,  0x251,  0x24c,  
+    0x247,  0x242,  0x23d,  0x238,  0x233,  0x22e,  0x229,  0x225,  
+    0x220,  0x21c,  0x217,  0x213,  0x20e,  0x20a,  0x206,  0x202,  
+    0x1fe,  0x1fa,  0x1f6,  0x1f2,  0x1ef,  0x1eb,  0x1e7,  0x1e4,  
+    0x1e0,  0x1dc,  0x1d9,  0x1d6,  0x1d2,  0x1cf,  0x1cc,  0x1c9,  
+    0x1c5,  0x1c2,  0x1bf,  0x1bc,  0x1b9,  0x1b6,  0x1b3,  0x1b0,  
+    0x1ad,  0x1ab,  0x1a8,  0x1a5,  0x1a2,  0x1a0,  0x19d,  0x19b,  
+    0x198,  0x195,  0x193,  0x190,  0x18e,  0x18c,  0x189,  0x187,  
+    0x185,  0x182,  0x180,  0x17e,  0x17c,  0x179,  0x177,  0x175,  
+    0x173,  0x171,  0x16f,  0x16d,  0x16b,  0x169,  0x167,  0x165,  
+    0x163,  0x161,  0x15f,  0x15d,  0x15b,  0x159,  0x158,  0x156,  
+    0x154,  0x152,  0x150,  0x14f,  0x14d,  0x14b,  0x14a,  0x148,  
+    0x146,  0x145,  0x143,  0x142,  0x140,  0x13e,  0x13d,  0x13b,  
+    0x13a,  0x138,  0x137,  0x135,  0x134,  0x132,  0x131,  0x130,  
+    0x12e,  0x12d,  0x12b,  0x12a,  0x129,  0x127,  0x126,  0x125,  
+    0x123,  0x122,  0x121,  0x120,  0x11e,  0x11d,  0x11c,  0x11b,  
+    0x119,  0x118,  0x117,  0x116,  0x115,  0x113,  0x112,  0x111,  
+    0x110,  0x10f,  0x10e,  0x10d,  0x10c,  0x10a,  0x109,  0x108,  
+    0x107,  0x106,  0x105,  0x104,  0x103,  0x102,  0x101,  0x100,  
+};
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfBlitter.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,132 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#include "sfBlitter.h"
+
+#include "sfCompiler.h"
+
+namespace OpenVGRI {
+
+DynamicBlitter::DynamicBlitter() :
+    m_maskOperation(VG_SET_MASK),
+    m_isMaskOperation(false),
+    m_fillColor(),
+    m_isFill(false),
+
+    m_signatureState(),
+    m_uniforms()
+{
+}
+
+DynamicBlitter::~DynamicBlitter()
+{
+}
+
+/*static*/ void DynamicBlitter::calculateHash(BlitterHash& hash, const BlitSignatureState& state)
+{
+    const RIuint32 descBits = 10;
+    const RIuint32 maskOperationBits = 3;
+    const RIuint32 boolBits = 1;
+
+    RIuint32 srcFormat = (RIuint32)(state.srcDesc.toIndex());
+    RIuint32 dstFormat = (RIuint32)(state.dstDesc.toIndex());
+    RIuint32 maskOperation = ((RIuint32)(state.maskOperation - VG_CLEAR_MASK));
+    RIuint32 incompatibleStride = ((RIuint32)state.incompatibleStrides);
+    RIuint32 isMaskOperation = ((RIuint32)state.isMaskOperation);
+    RIuint32 unsafeInput = (RIuint32)state.unsafeInput;
+    
+    int b = 0;
+
+    b = riInsertBits32(hash.value, sizeof(hash.value), srcFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), dstFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), maskOperation, maskOperationBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), incompatibleStride, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), isMaskOperation, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), unsafeInput, boolBits, b);
+}
+
+/**
+ * \brief   Blit a region. The input coordinates and dimensions must be validated outside
+ *          the blitter currently.
+ * \note    The user must also apply the storage offset to the image(s).
+ */
+void DynamicBlitter::prepareBlit(Image* dst, const Image* src, int sx, int sy, int dx, int dy, int w, int h)
+{
+    //const Image *srcImage = src->getImage();
+    //Image* dstImage = dst->m_image;
+    
+    // \todo Move these to derivation of the state?
+    m_signatureState.srcDesc = src->getDescriptor();
+    m_signatureState.dstDesc = dst->getDescriptor();
+    m_signatureState.isMaskOperation = m_isMaskOperation;
+    m_signatureState.maskOperation = m_isMaskOperation ? m_maskOperation : VG_CLEAR_MASK;
+    m_signatureState.incompatibleStrides = false;
+    m_signatureState.unsafeInput = false;
+
+    m_uniforms.src = src->getData();
+    m_uniforms.dst = dst->getData();
+    m_uniforms.srcX = sx;
+    m_uniforms.srcY = sy;
+    m_uniforms.dstX = dx;
+    m_uniforms.dstY = dy;
+    m_uniforms.width = w;
+    m_uniforms.height = h;
+    m_uniforms.srcStride = src->getStride();
+    m_uniforms.dstStride = dst->getStride();
+
+    if (m_signatureState.srcDesc.isZeroConversion(m_signatureState.dstDesc))
+    {
+        const int fullCopyStride = Image::descriptorToStride(m_signatureState.srcDesc, m_uniforms.width);
+
+        if ((m_uniforms.dstStride != m_uniforms.srcStride) || (fullCopyStride != m_uniforms.srcStride)) 
+            m_signatureState.incompatibleStrides = true;
+    }
+
+    if (src->isUnsafe())
+        m_signatureState.unsafeInput = true;
+
+}
+
+void DynamicBlitter::blit()
+{
+#if 1
+    bool compiledBlitter = false;
+    {
+        PPCompiler& compiler = PPCompiler::getCompiler();
+        PPCompiler::BlitterHandle blitterHandle = compiler.compileBlitter(getSignatureState());
+        if (blitterHandle)
+        {
+            compiledBlitter = true;
+            BlitterFunction func = compiler.getBlitterPtr(blitterHandle);
+            func(getUniforms());
+            compiler.releaseBlitter(blitterHandle);
+        }
+    }
+
+    if (!compiledBlitter)
+#endif
+    {
+        executeBlitter(getSignatureState(), getUniforms());
+    }
+}
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfBlitter.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,104 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFBLITTER_H
+#define __SFBLITTER_H
+
+#ifndef __RIDEFS_H
+#   include "riDefs.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#   include "riImage.h"
+#endif
+
+#include "VG/openvg.h"
+
+namespace OpenVGRI {
+
+class PPCompiler;
+
+struct BlitterHash {
+    BlitterHash() {value[0] = 0; }
+    bool operator==(const BlitterHash& rhs) const { return value[0] == rhs.value[0]; }
+    RIuint32 value[1];
+}; 
+
+// \todo Rename to just "Blitter" and move out of the same compilation unit.
+class DynamicBlitter {
+public:
+    struct BlitSignatureState {
+        VGMaskOperation maskOperation;
+
+        bool incompatibleStrides;
+        bool isMaskOperation;
+        bool unsafeInput;
+        
+        // Derived:
+        Color::Descriptor srcDesc;
+        Color::Descriptor dstDesc;
+    };
+
+    struct BlitUniforms {
+        void*       dst;
+        const void* src;
+        RIuint32    srcX;
+        RIuint32    srcY;
+        RIuint32    dstX;
+        RIuint32    dstY;
+        RIuint32    width;
+        RIuint32    height;
+        RIint32     srcStride;
+        RIint32     dstStride;
+    };
+
+public:
+    DynamicBlitter();
+    ~DynamicBlitter();
+
+    static void calculateHash(BlitterHash& hash, const BlitSignatureState& state);
+
+    void setMaskOperation(VGMaskOperation maskOperation)    { m_maskOperation = maskOperation; }
+    void enableMaskOperation(bool isMaskOperation)          { m_isMaskOperation = isMaskOperation; }
+    void setFillColor(const Color& fillColor)               { m_fillColor = fillColor; }
+    void enableFill(bool isFill)                            { m_isFill = isFill; }
+
+    void prepareBlit(Image* dst, const Image* src, int sx, int sy, int dx, int dy, int w, int h);
+    void blit();
+
+    const BlitSignatureState&   getSignatureState() { return m_signatureState; }
+    const BlitUniforms&         getUniforms() { return m_uniforms; }
+
+private:
+
+    VGMaskOperation     m_maskOperation;
+    bool                m_isMaskOperation;
+    Color               m_fillColor;
+    bool                m_isFill;
+    
+    BlitSignatureState  m_signatureState;
+    BlitUniforms        m_uniforms;
+};
+}
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfCompiler.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,512 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFCOMPILER_H
+#   include "sfCompiler.h"
+#endif
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+
+#include <iostream>
+#include <sstream>
+#include <stdio.h>
+
+#include "llvm/LLVMContext.h"
+#include "llvm/Module.h"
+#include "llvm/Bitcode/ReaderWriter.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Type.h"
+#include "llvm/Value.h"
+#include "llvm/Constant.h"
+#include "llvm/Constants.h"
+#include "llvm/Argument.h"
+#include "llvm/Transforms/Utils/Cloning.h"
+
+#include "llvm/Pass.h"
+#include "llvm/PassManager.h"
+#include "llvm/Support/StandardPasses.h"
+#include "llvm/Transforms/Utils/BasicInliner.h"
+
+#include "llvm/ExecutionEngine/JIT.h"
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/Target/TargetSelect.h"
+#include "llvm/Support/ManagedStatic.h"
+
+// This file is found as an output of compilation (in the binary directory).
+// Rationale for this is that the output is somewhat platform dependent.
+#include "binaryPixelPipe.h"
+#include "binaryBlitter.h"
+
+namespace OpenVGRI {
+
+static bool single_compiler = true;
+
+PPCompiler* PPCompiler::s_compiler = NULL;
+
+PPCompiler::PPCompiler() :
+    m_executionEngine(NULL),
+    m_ppCache(NUM_CACHED_PIXELPIPES),
+    m_blitterCache(NUM_CACHED_BLITTERS),
+    m_llvmContext()
+{
+    // \todo Make this class into a singleton?
+    RI_ASSERT(single_compiler);
+
+    if (single_compiler)
+        single_compiler = false;
+
+    ::llvm::InitializeNativeTarget();
+    init();
+}
+
+PPCompiler::~PPCompiler()
+{
+    if (m_executionEngine)
+        delete m_executionEngine;
+}
+
+PPCompiler::PPCompilerContext::PPCompilerContext() :
+    module(NULL),
+    llvmFunction(NULL)
+{
+}
+
+PPCompiler::PPCompilerContext::~PPCompilerContext()
+{
+    // All the other objects should be owned by the executionengine, and
+    // that is owned by the PPCompiler, so do nothing here.
+
+}
+
+bool PPCompiler::initPPContext(
+    PPCompilerContext&      context, 
+    const unsigned char*    data,
+    size_t                  dataSize,
+    const char*             functionName)
+{
+    try {
+        std::string err;
+
+        const char *byteCodeStart = (const char*)data;
+        const char *byteCodeEnd = (const char*)(data + dataSize);
+
+        ::llvm::MemoryBuffer* memBuffer = ::llvm::MemoryBuffer::getMemBufferCopy(byteCodeStart, byteCodeEnd);
+        
+        llvmCheckPtrError((void*)memBuffer, err);
+
+        // Make sure the module is fully read:
+        //::llvm::Module* ppModule = moduleProvider->materializeModule(&err);
+        ::llvm::Module* ppModule = ::llvm::getLazyBitcodeModule(memBuffer, getLLVMContext(), &err);
+        ppModule->MaterializeAll();
+        
+        llvmCheckPtrError(ppModule, err);
+        context.module = ppModule;
+        //ppModule->dump();
+
+        if (!m_executionEngine)
+        {
+            m_executionEngine = ::llvm::ExecutionEngine::createJIT(ppModule, &err, NULL, ::llvm::CodeGenOpt::Aggressive);
+            llvmCheckPtrError(m_executionEngine, err);
+        }
+        else
+            m_executionEngine->addModule(ppModule);
+
+        //m_executionEngine->runStaticConstructorsDestructors(false);
+
+        ::llvm::Function* originalFunc = findFunctionWithString(ppModule, functionName);
+       
+        llvmCheckPtrError((const void*)originalFunc, err);
+        context.llvmFunction = originalFunc;
+        //originalFunc->dump();
+    } catch (int err)
+    {
+        (void)err;
+        std::cerr << "*** Failed to initialize a pixelpipeline module." << std::endl;
+        return false;
+    }
+
+    return true;
+}
+
+
+/**
+ * \brief   Loads the modules this compiler supports.
+ */
+bool PPCompiler::init()
+{
+    if (!initPPContext(m_ppContext, integerPixelPipe_binary, sizeof(integerPixelPipe_binary), "executePixelPipeline"))
+        return false;
+    
+    if (!initPPContext(m_blitterContext, integerBlitter_binary, sizeof(integerBlitter_binary), "executeBlitter"))
+        return false;
+
+    m_ppCache.setLLVMInterface(m_executionEngine, m_ppContext.module);
+    m_blitterCache.setLLVMInterface(m_executionEngine, m_blitterContext.module);
+
+    return true;
+}
+
+// Helps cast void* to function pointers (may be platform dependent, usually works):
+union FuncCaster {
+    void*               ptr;
+    PixelPipeFunction   pipeFunc;
+    BlitterFunction     blitFunc; 
+};
+
+PPCompiler::PartialEvalFunc PPCompiler::compilePixelPipeline(::llvm::LLVMContext& llvmContext, PPCompilerContext& compilerContext, ConstantGenFunc constGenFunc, const void* state, const std::string& newFunctionName)
+{
+    // Get the constant state argument (must be the first in the list):
+    ::llvm::Function::arg_iterator argit = compilerContext.llvmFunction->arg_begin();
+    ::llvm::Argument& arg = *argit;
+    //arg.getType()->dump();
+
+    ::llvm::Constant* constantState = constGenFunc(state, llvmContext, arg.getType()->getContainedType(0));
+
+    RI_ASSERT(constantState);
+
+    //constantState->dump();
+
+    // \todo Even though this variable could be automatically cleaned up by the optimizations,
+    // it should be stored in the cache and destroyed along with the function when
+    // the cache-entry is dropped out.
+    ::llvm::GlobalVariable* constantStateVariable = new ::llvm::GlobalVariable(
+        *compilerContext.module, constantState->getType(), true, ::llvm::GlobalValue::PrivateLinkage, constantState, newFunctionName + "_constState");
+
+    // When to delete the global variable?
+    // -> When the pixel-pipe is removed from the cache. Also, when the compiler is deleted.
+
+    ::llvm::DenseMap<const ::llvm::Value*, ::llvm::Value*> valueMap;
+    std::pair<const ::llvm::Value*, ::llvm::Value*> valueReplacement((::llvm::Value*)&arg, constantStateVariable);
+    valueMap.insert(valueReplacement);
+
+    ::llvm::Function* specializedFunc = ::llvm::CloneFunction(compilerContext.llvmFunction, valueMap, NULL);
+    specializedFunc->setName(newFunctionName);
+    //specializedFunc->dump();
+
+    compilerContext.module->getFunctionList().push_back(specializedFunc);
+
+    // \note Currently this creates the pass manager every time a pipeline is compiled...
+    ::llvm::PassManager pm;
+    // \todo Seems like the greater the threshold, the more the pass will inline:
+    // In practice, everything should be inlineed into the resulting pipe.
+    ::llvm::Pass* inliningPass = ::llvm::createFunctionInliningPass(100000);
+    ::llvm::createStandardModulePasses(&pm, 3, false, true, true, true, false, inliningPass);
+    pm.run(*compilerContext.module);
+
+    //ppModule->dump();
+
+    //compilerContext.llvmFunction->dump();
+    PartialEvalFunc ret = {specializedFunc, constantStateVariable};
+    return ret;
+}
+
+/**
+ * \brief   Compile a pipeline if necessary. If the pipeline is cached, return a
+ *          handle to it. 
+ * \return  NULL handle if operation was not successful, otherwise a handle to the pipeline.
+ * \todo    For deferred JITting, it might make sense to return a special value
+ *          to indicate that the pipeline is under compilation.
+ * \note    LLVM compilation should be thread-safe internally.
+ */
+PPCompiler::PixelPipeHandle PPCompiler::compilePixelPipeline(const PixelPipe::SignatureState& state)
+{
+    PixelPipeHash hash;
+    calculatePPHash(hash, state);
+
+    PixelPipeEntryHandle entry = m_ppCache.findCachedItemByHash(hash);
+
+    if (!entry)
+    {
+        PartialEvalFunc pf;
+        std::string funcName = "compiledPPFunc_" + PPCompiler::stringOfArray(hash.value, sizeof(hash.value)/sizeof(hash.value[0]));
+        pf = compilePixelPipeline(getLLVMContext(), m_ppContext, createPPConstant, (const void*)&state, funcName.c_str());
+        entry = m_ppCache.cacheFunction(hash, pf.llvmFunc, pf.llvmConst);
+#if defined(RI_DEBUG) && 0
+        pf.llvmFunc->dump();
+#endif
+    }
+
+    if (!entry)
+    {
+        RI_ASSERT(false);
+        // Release the function!
+    }
+
+    return (PixelPipeHandle)entry;
+}
+
+PPCompiler::BlitterHandle PPCompiler::compileBlitter(const DynamicBlitter::BlitSignatureState& state)
+{
+    // \todo This function is almost the same as compilePixelPipeline.
+    BlitterHash hash;
+    DynamicBlitter::calculateHash(hash, state);
+
+    BlitterEntryHandle entry = m_blitterCache.findCachedItemByHash(hash);
+
+    if (!entry)
+    {
+        PartialEvalFunc pf;
+        std::string funcName = "compiledBlitterFunc_" + PPCompiler::stringOfArray(hash.value, sizeof(hash.value)/sizeof(hash.value[0]));
+        pf = compilePixelPipeline(getLLVMContext(), m_blitterContext, createBlitterConstant, (const void*)&state, funcName.c_str());
+        entry = m_blitterCache.cacheFunction(hash, pf.llvmFunc, pf.llvmConst);
+    }
+
+    if (!entry)
+    {
+        RI_ASSERT(false);
+        // Release the function!
+    }
+
+    RI_ASSERT(entry);
+
+    return (BlitterHandle)entry;
+}
+
+PixelPipeFunction PPCompiler::getPixelPipePtr(PixelPipeHandle handle)
+{
+    PixelPipeEntryHandle entryHandle = (PixelPipeEntryHandle)handle;
+    ::llvm::Function* function = m_ppCache.getFunction(entryHandle); 
+
+    FuncCaster c;
+    c.ptr = m_executionEngine->getPointerToFunction(function);
+    return c.pipeFunc;
+}
+
+BlitterFunction PPCompiler::getBlitterPtr(BlitterHandle handle)
+{
+    BlitterEntryHandle entryHandle = (BlitterEntryHandle)handle;
+    ::llvm::Function* function = m_blitterCache.getFunction(entryHandle);
+
+    FuncCaster c;
+    c.ptr = m_executionEngine->getPointerToFunction(function);
+    return c.blitFunc;
+}
+
+// Release a reference to a pixel-pipeline handle.
+void PPCompiler::releasePixelPipeline(PixelPipeHandle handle)
+{
+    PixelPipeEntryHandle entryHandle = (PixelPipeEntryHandle)handle;
+    m_ppCache.releaseEntry(entryHandle);
+}
+
+// Release a reference to a blitter handle.
+void PPCompiler::releaseBlitter(BlitterHandle handle)
+{
+    BlitterEntryHandle entryHandle = (BlitterEntryHandle)handle;
+    m_blitterCache.releaseEntry(entryHandle);
+}
+
+#if 0
+// \todo Complete this and make it fully recursive: this way all the C-structs
+// can be converted to corresponding LLVM classes at runtime.
+::llvm::Constant* PPCompiler::createConstantStruct(const void* structure, size_t structSize, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType) const
+{
+    // Only copies integer-values (int, bools)
+    RIuint8* bytePtr = (RIuint8*)structure; 
+    ::llvm::Type::subtype_iterator subtypeBegin, subtypeEnd;
+
+    subtypeBegin = structType->subtype_begin();
+    subtypeEnd = structType->subtype_end();
+
+    for(::llvm::Type::subtype_iterator it = subtypeBegin; it != subtypeEnd; ++it)
+    {
+        ::llvm::Type* elementType = *it;
+        RI_ASSERT(elementType->isSized());
+        unsigned int elementBitSize = elementType->getPrimitiveSizeInBits();
+        RI_ASSERT((elementBitSize % 8) == 0);
+        unsigned int elementSize = elementBitSize / 8;
+        RI_ASSERT(elementSize > 0 && elementSize <= 4); 
+       
+        bytePtr += elementSize;
+    }
+}
+#endif
+/**
+ * \brief   Creates a LLVM constant from a color descriptor.
+ * \todo    Create global constants from these for every possible color format!
+ */
+RI_INLINE static ::llvm::Constant* createDescConstant(const Color::Descriptor& desc, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType)
+{
+    ::llvm::Constant* constants[] = {
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.redBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.redShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.greenBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.greenShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.blueBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.blueShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.alphaBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.alphaShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.luminanceBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.luminanceShift, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.shape, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.vgFormat, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.internalFormat, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.bitsPerPixel, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.bytesPerPixel, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.maskBits, true),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.maskShift, true),
+    };
+
+    std::vector< ::llvm::Constant*> structConsts;
+
+    for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++)
+    {
+        structConsts.push_back(constants[i]);
+    }
+
+    ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts);
+
+    return constStruct;
+}
+
+::llvm::Constant* PPCompiler::createPPConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType)
+{
+    // Get the actual object. This is a messy way to abstract setting the structure, but
+    // there is little sense in making more classes/adapters/whatever at this point.
+    const PixelPipe::SignatureState& state = *(const PixelPipe::SignatureState*)signatureState;
+    // \todo There seems to be no way to track the structure member names once
+    // LLVM has generated the bitcode (only offsets and references to those
+    // offsets remain). Means to track proper setting of struct members in
+    // DEBUG build must be implemented in some other way.
+    // 
+    // For now, the state and this function must be kept carefully in sync!
+    
+    const int cDescriptorElementIndex = 8;
+    const ::llvm::Type* descType = structType->getContainedType(cDescriptorElementIndex);
+
+    ::llvm::Constant* constants[] = {
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.blendMode, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageMode, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintType, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.maskOperation, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintTilingMode, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintSampler, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageSampler, false),
+
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageGradientType, false),
+
+        createDescConstant(state.dstDesc, llvmContext, descType),
+        createDescConstant(state.maskDesc, llvmContext, descType),
+        createDescConstant(state.imageDesc, llvmContext, descType),
+        createDescConstant(state.patternDesc, llvmContext, descType),
+
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasMasking, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasImage, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasColorTransform, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.isRenderToMask, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.fillColorTransparent, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.unsafeImageInput, false),
+    };
+
+    std::vector< ::llvm::Constant*> structConsts;
+
+    for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++)
+    {
+        structConsts.push_back(constants[i]);
+    }
+
+    ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts);
+
+    return constStruct;
+}
+
+::llvm::Constant* PPCompiler::createBlitterConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType)
+{
+    const DynamicBlitter::BlitSignatureState& state = *(const DynamicBlitter::BlitSignatureState*)signatureState;
+    
+    const int cDescriptorElementIndex = 4;
+    const ::llvm::Type* descType = structType->getContainedType(cDescriptorElementIndex);
+
+    ::llvm::Constant* constants[] = {
+        ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.maskOperation, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.incompatibleStrides, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.isMaskOperation, false),
+        ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.unsafeInput, false),
+
+        createDescConstant(state.srcDesc, llvmContext, descType),
+        createDescConstant(state.dstDesc, llvmContext, descType),
+    };
+
+    std::vector< ::llvm::Constant*> structConsts;
+
+    for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++)
+    {
+        structConsts.push_back(constants[i]);
+    }
+
+    ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts);
+
+    return constStruct;
+}
+
+/**
+ * \brief   Find a function whose name containst ``namepart''. Useful for finding c++
+ *          decorated names from modules (if they are unique).
+ * \note    Maybe should use C-functions only in the final product.
+ */
+::llvm::Function* PPCompiler::findFunctionWithString(::llvm::Module* module, const char* namepart)
+{
+    // Find a function whose name contains 'namepart'
+    llvm::Module::iterator it, end;
+    it = module->begin();
+    end = module->end();
+    for (; it != end; ++it)
+    {
+        if (!it->isDeclaration())
+            if (it->getNameStr().find(namepart) != std::string::npos)
+                return it;
+    }
+    return NULL;
+}
+
+void PPCompiler::llvmCheckPtrError(const void* ptr, std::string& err)
+{
+#if defined(RI_DEBUG)
+    (void)err;
+    //std::cout << "LLVM returned: " << ptr << ". Error string: \"" << err << "\"" << std::endl;
+#else
+    (void)err;
+#endif
+    if (!ptr)
+        throw(-1);
+}
+
+/*static*/ std::string PPCompiler::stringOfArray(const RIuint32* arr, int nElems)
+{
+    char tempBuffer[9];
+    std::stringstream out;
+    // Ambiquities resolved by using a constant width:
+    RI_ASSERT(nElems > 0);
+    int i = nElems-1;
+    do {
+        snprintf(tempBuffer, sizeof(tempBuffer), "%08x", arr[i]);
+        out << tempBuffer;
+        i--;
+    } while(i >= 0);
+
+    return out.str();
+}
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfCompiler.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,156 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFCOMPILER_H
+#define __SFCOMPILER_H
+
+#include <string>
+
+#ifndef __SFDYNAMICPIXELPIPE_H
+#   include "sfDynamicPixelPipe.h"
+#endif
+
+#ifndef __SFDYNAMICBLITTER_H
+#   include "sfDynamicBlitter.h"
+#endif
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+
+#ifndef __SFFUNCTIONCACHE_H
+#   include "sfFunctionCache.h"
+#endif
+
+#include "llvm/LLVMContext.h"
+
+// \note PPCompiler class also caches a certain amount of compiled functions.
+// It may make sense to move the cache into a separate container.
+
+// LLVM forward declarations
+namespace llvm { 
+    class Type;
+    class Constant;
+    class Function;
+    class Module;
+    class ExecutionEngine;
+}
+
+namespace OpenVGRI {
+
+// Pixel-pipeline function with constant state removed:
+typedef void (*PixelPipeFunction)(const PixelPipe::PPUniforms&, PixelPipe::PPVariants&, const Span*, int);
+// Image-blitting function with constant state removed:
+typedef void (*BlitterFunction)(const DynamicBlitter::BlitUniforms&);
+
+class PPCompiler
+{
+public:
+    typedef int PixelPipeHandle;
+    typedef int BlitterHandle;
+private:
+    // Function that generates LLVM-constant from a pixel-pipeline:
+    typedef ::llvm::Constant* (*ConstantGenFunc)(const void* structure, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType);
+
+    struct PPCompilerContext {
+        PPCompilerContext();
+        ~PPCompilerContext();
+        // Stores persistent objects related to each component (pixelpipe or blitter).
+        // Note that the execution engine must be a per-process singleton for LLVM before
+        // version 2.7!
+        ::llvm::Module* module;
+        ::llvm::Function* llvmFunction; 
+    };
+
+    struct PartialEvalFunc
+    {
+        ::llvm::Function*   llvmFunc;
+        ::llvm::GlobalVariable*   llvmConst;
+    };
+
+public:
+    PPCompiler();
+    ~PPCompiler();
+
+    static PartialEvalFunc compilePixelPipeline(::llvm::LLVMContext& llvmContext, PPCompilerContext& compilerContext, ConstantGenFunc constGenFunc, const void* state, const std::string& newFuntionName);
+
+    // These functions get an reserve a handle to a pixelpipe/blitter. MUST use release
+    // after done with the function.
+    PixelPipeHandle     compilePixelPipeline(const PixelPipe::SignatureState& state);
+    BlitterHandle       compileBlitter(const DynamicBlitter::BlitSignatureState& state);
+
+    PixelPipeFunction   getPixelPipePtr(PixelPipeHandle handle);
+    BlitterFunction     getBlitterPtr(BlitterHandle handle);
+
+    void releasePixelPipeline(PixelPipeHandle handle);
+    void releaseBlitter(BlitterHandle handle);
+
+    bool init();
+
+    // It seems that under VS, the static init order is not correct so the compiler has to be created
+    // during run-time.
+    static PPCompiler&  getCompiler() { if(!s_compiler) { s_compiler = new PPCompiler(); } return *s_compiler; }
+
+private:
+    bool initPPContext(PPCompilerContext& context, const unsigned char* data, size_t dataSize, const char* functionName);
+    //void* compileRenderingFunction(const void* signatureState, RenderingFunctionType type);
+
+    static ::llvm::Constant* createConstantStruct(const void* structure, size_t structureSize, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType);
+    static ::llvm::Constant* createPPConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType);
+    static ::llvm::Constant* createBlitterConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType);
+    static ::llvm::Function* findFunctionWithString(::llvm::Module* module, const char* namepart);
+    static void llvmCheckPtrError(const void* ptr, std::string& err);
+
+    static std::string stringOfArray(const RIuint32* arr, int nElems);
+
+private:
+    //::llvm::LLVMContext& getLLVMContext() { return ::llvm::getGlobalContext(); }
+    ::llvm::LLVMContext& getLLVMContext() { return m_llvmContext; }
+
+    // The order is important atm. because llvm context must be destroyed last:
+    //::llvm::LLVMContext& m_llvmContext;
+    PPCompilerContext m_blitterContext;
+    PPCompilerContext m_ppContext;
+    ::llvm::ExecutionEngine* m_executionEngine;
+
+    // \note Loading a system with LLVM already consumes a lot of memory, so
+    // the amount of cached functions can be grown substantially depending on
+    // requirements.
+    enum { NUM_CACHED_PIXELPIPES = 64 };
+    enum { NUM_CACHED_BLITTERS = NUM_CACHED_PIXELPIPES };
+    
+    FunctionCache<PixelPipeHash> m_ppCache;
+    FunctionCache<BlitterHash> m_blitterCache;
+    typedef FunctionCache<PixelPipeHash>::EntryHandle PixelPipeEntryHandle;
+    typedef FunctionCache<BlitterHash>::EntryHandle BlitterEntryHandle;
+    //std::vector<CacheEntry<BlitterHash> > blitterCache;
+    
+    ::llvm::LLVMContext m_llvmContext;
+
+    static PPCompiler* s_compiler;
+};
+
+}
+
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfDynamicBlitter.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,217 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#include "sfDynamicBlitter.h"
+
+#ifndef __SFBLITTER_H
+#   include "sfBlitter.h"
+#endif
+
+#ifndef __SFMASK_H
+#   include "sfMask.h"
+#endif
+
+namespace OpenVGRI {
+
+RI_INLINE static bool maskOperationRequiresLoad(VGMaskOperation op)
+{
+    switch(op)
+    {
+    case VG_CLEAR_MASK:
+    case VG_FILL_MASK:
+    case VG_SET_MASK:
+        return false;
+    default:
+        RI_ASSERT(op == VG_UNION_MASK || op == VG_INTERSECT_MASK || op == VG_SUBTRACT_MASK);
+        return true;
+    }
+}
+
+/**
+ * \brief   Blit rectangular areas between similar or different color format buffers.
+ * \note    Implementation is structured so that the per-pixel branches are minimized
+ *          even if dynamic compilation is not in use.
+ * \todo    For some reason the completely generic integer conversion does not optimize
+ *          fully run-time. Check what causes this!
+ */
+void executeBlitter(const DynamicBlitter::BlitSignatureState& state, const DynamicBlitter::BlitUniforms& uniforms)
+{
+    const void* srcPtr = Image::calculateAddress(
+        uniforms.src, state.srcDesc.bitsPerPixel, uniforms.srcX, uniforms.srcY, uniforms.srcStride); 
+    void* dstPtr = Image::calculateAddress(
+        uniforms.dst, state.dstDesc.bitsPerPixel, uniforms.dstX, uniforms.dstY, uniforms.dstStride);
+
+    // The following flag is useful for debugging. Enabling it will hurt performance.
+//#define ALWAYS_FORCE_FULL_CONVERSION
+
+    // Currently the data must be byte-aligned for memcpy optimizations:
+    const int minBpp = RI_INT_MIN(state.srcDesc.bitsPerPixel, state.dstDesc.bitsPerPixel);
+    const bool byteCopy = minBpp >= 8 ? true : false;
+    const bool forceFullConversion = state.isMaskOperation || state.unsafeInput || !byteCopy;
+    
+#if !defined(ALWAYS_FORCE_FULL_CONVERSION)
+    if (state.srcDesc.isZeroConversion(state.dstDesc) && !forceFullConversion)
+    {
+        const int fullCopyStride = Image::descriptorToStride(state.srcDesc, uniforms.width);
+
+        if ((uniforms.dstStride != uniforms.srcStride) || (fullCopyStride != uniforms.srcStride)) 
+        {
+            // memcpy individual scanlines.
+            const size_t scanLength = (size_t)RI_INT_ABS(Image::descriptorToStride(state.srcDesc, uniforms.width));
+            for (RIuint32 i = 0; i < uniforms.height; i++)
+            {
+                memcpy(dstPtr, srcPtr, scanLength);
+                dstPtr = (void*)((RIuint8*)dstPtr + uniforms.dstStride);
+                srcPtr = (void*)((RIuint8*)srcPtr + uniforms.srcStride);
+            }
+        } else
+        {
+            // memcpy the whole area
+            memcpy(dstPtr, srcPtr, uniforms.srcStride * uniforms.height);
+        }
+    } else if (state.srcDesc.isShiftConversion(state.dstDesc) && !forceFullConversion)
+    {
+        // \todo Separate to function? Replace with pointer read/write & advance.
+        if (state.srcDesc.isShiftConversionToLower(state.dstDesc))
+        {
+            // Components can be immediately shifted down to lower bit-depth.
+            for (RIuint32 j = 0; j < uniforms.height; j++)
+            {
+                RIuint8* srcStart = (RIuint8*)srcPtr;
+                RIuint8* dstStart = (RIuint8*)dstPtr;
+                RIuint32 srcX = uniforms.srcX;
+                RIuint32 dstX = uniforms.dstX;
+                for (RIuint32 i = 0; i < uniforms.width; i++)
+                {
+                    RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX); // \todo srcX!
+                    RIuint32 dc = Color::Descriptor::crossConvertToLower(c, state.srcDesc, state.dstDesc);
+                    Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc);
+
+                    srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                    dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); 
+
+                    srcX++;
+                    dstX++;
+                }
+                srcPtr = (void*)(srcStart + uniforms.srcStride);
+                dstPtr = (void*)(dstStart + uniforms.dstStride);
+            }
+        }
+        else
+        {
+            // Color components require expansion before shifting to destination color-format */
+            for (RIuint32 j = 0; j < uniforms.height; j++)
+            {
+                RIuint8* srcStart = (RIuint8*)srcPtr;
+                RIuint8* dstStart = (RIuint8*)dstPtr;
+                RIuint32 srcX = uniforms.srcX;
+                RIuint32 dstX = uniforms.dstX;
+                for (RIuint32 i = 0; i < uniforms.width; i++)
+                {
+                    RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                    IntegerColor ic = IntegerColor(c, state.srcDesc);
+                    ic.expandColor(state.srcDesc);
+                    ic.truncateColor(state.dstDesc);
+                    RIuint32 dc = ic.getPackedColor(state.dstDesc);
+                    Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc);
+
+                    srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                    dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); 
+
+                    srcX++;
+                    dstX++;
+                }
+                srcPtr = (void*)(srcStart + uniforms.srcStride);
+                dstPtr = (void*)(dstStart + uniforms.dstStride);
+            }
+        }
+    } else
+#endif
+    {
+        /* This block should handle the rest (and all) of the color-conversion cases. */
+        for (RIuint32 j = 0; j < uniforms.height; j++)
+        {
+            RIuint8* srcStart = (RIuint8*)srcPtr;
+            RIuint8* dstStart = (RIuint8*)dstPtr;
+            RIuint32 srcX = uniforms.srcX;
+            RIuint32 dstX = uniforms.dstX;
+            for (RIuint32 i = 0; i < uniforms.width; i++)
+            {
+                RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                IntegerColor ic;
+                RIuint32 dc;
+                
+                if (!state.isMaskOperation)
+                {
+                    ic = IntegerColor(c, state.srcDesc);
+                    if (state.unsafeInput)
+                        ic.clampToAlpha();
+
+                    ic.convertToFrom(state.dstDesc, state.srcDesc, false);
+                    dc = ic.getPackedColor(state.dstDesc);
+                }
+                else
+                {
+                    // Apply the given mask operation between two surfaces.
+                    IntegerColor id;
+
+                    if (maskOperationRequiresLoad(state.maskOperation))
+                    {
+                        ic.fromPackedMask(c, state.srcDesc);
+                        ic.expandMask(state.srcDesc);
+
+                        IntegerColor id;
+
+                        RIuint32 d = Image::readPackedPixelFromAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX);
+                        id.fromPackedMask(d, state.dstDesc);
+                        id.expandColor(state.dstDesc);
+
+                        RIuint32 coverage = ic.a + (ic.a >> 7);
+                        ic = intMaskOperation(coverage, id, state.maskOperation);
+                    }
+                    else
+                    {
+                        // Other ops handled with memset, not blitter
+                        RI_ASSERT(state.maskOperation == VG_SET_MASK); 
+                        ic.fromPackedMask(c, state.srcDesc);
+                        //ic.expandMask(state.srcDesc);
+                        ic.convertToFrom(state.dstDesc, state.srcDesc, true);
+                    }
+                    dc = ic.getPackedMaskColor(state.dstDesc);
+                }
+
+                Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc);
+
+                srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX);
+                dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); 
+
+                srcX++;
+                dstX++;
+            }
+            srcPtr = (void*)(srcStart + uniforms.srcStride);
+            dstPtr = (void*)(dstStart + uniforms.dstStride);
+        }
+    }
+}
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfDynamicBlitter.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,38 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFDYNAMICBLITTER_H
+#define __SFDYNAMICBLITTER_H
+
+#ifndef __SFBLITTER_H
+#   include "sfBlitter.h"
+#endif
+
+namespace OpenVGRI {
+
+// Blitter function (may be statically compiled also)
+void executeBlitter(const DynamicBlitter::BlitSignatureState& state, const DynamicBlitter::BlitUniforms& uniforms);
+
+}
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfDynamicPixelPipe.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1533 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+// This file contains the generated pixel-pipeline code and provides
+// interface to compile and run them.
+
+#ifndef __RIRASTERIZER_H
+#   include "riRasterizer.h"
+#endif
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+
+#ifndef __SFDYNAMICPIXELPIPE_H
+#   include "sfDynamicPixelPipe.h"
+#endif
+
+#ifndef __RIUTILS_H
+#   include "riUtils.h"
+#endif
+
+#ifndef __SFMASK_H
+#   include "sfMask.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#   include "riImage.h"
+#endif
+
+#if defined(RI_DEBUG)
+#   include <stdio.h>
+#endif
+
+namespace OpenVGRI {
+
+RI_INLINE static bool alwaysLoadDst(const PixelPipe::SignatureState& state)
+{
+    if (!state.isRenderToMask)
+    {
+        if (state.hasImage)
+            return true;
+
+        VGBlendMode bm = state.blendMode;
+
+        if (bm == VG_BLEND_SRC_IN ||
+                bm == VG_BLEND_DST_OVER ||
+                bm == VG_BLEND_DST_IN ||
+                bm == VG_BLEND_ADDITIVE ||
+                bm == VG_BLEND_MULTIPLY ||
+                bm == VG_BLEND_SCREEN ||
+                bm == VG_BLEND_DARKEN ||
+                bm == VG_BLEND_LIGHTEN)
+        {
+            return true;
+        } else
+        {
+            return false;
+        }
+    }
+    else
+    {
+        switch (state.maskOperation)
+        {
+        case VG_SET_MASK:
+            return false;
+        default:
+            return true;
+        }
+    }
+}
+
+RI_INLINE static bool canSolidFill(const PixelPipe::SignatureState& state)
+{
+    if (state.isRenderToMask)
+    {
+        if (state.maskOperation == VG_SET_MASK ||
+            state.maskOperation == VG_UNION_MASK)
+            return true;
+        // \note SUBTRACT is also possible.
+        return false;
+    }
+
+    if (state.paintType != VG_PAINT_TYPE_COLOR)
+        return false;
+
+    if (state.hasImage)
+        return false;
+
+    // Some blendmodes can use dst color even if coverage == 1.0
+    if (state.blendMode != VG_BLEND_SRC && state.blendMode != VG_BLEND_SRC_OVER)
+        return false;
+
+    if (state.hasMasking)
+        return false;
+
+    if (state.fillColorTransparent)
+        return false;
+
+    if (state.hasColorTransform)
+        return false; // \todo Trace solid color alpha -> 1.0
+
+    return true;
+}
+
+RI_INLINE static int intReflectRepeat(int n, int bits)
+{
+    const int mask = (1<<bits)-1;
+    return (n ^ (n << (31 - bits) >> 31)) & mask;
+}
+
+RI_INLINE static void applyGradientRepeat(int& sx0, int& sx1, PixelPipe::TilingMode sm)
+{
+    switch (sm)
+    {
+    case PixelPipe::TILING_MODE_PAD:
+        sx0 = RI_INT_CLAMP(sx0, 0, PixelPipe::SAMPLE_MASK);
+        sx1 = RI_INT_CLAMP(sx1, 0, PixelPipe::SAMPLE_MASK);
+        break;
+    case PixelPipe::TILING_MODE_REFLECT:
+        sx0 = intReflectRepeat(sx0, PixelPipe::SAMPLE_BITS);
+        sx1 = intReflectRepeat(sx1, PixelPipe::SAMPLE_BITS);
+        break;
+    default:
+        RI_ASSERT(sm == PixelPipe::TILING_MODE_REPEAT);
+
+        sx0 = sx0 & PixelPipe::SAMPLE_MASK;
+        sx1 = sx1 & PixelPipe::SAMPLE_MASK;
+        break;
+    }
+
+    RI_ASSERT(sx0 >= 0 && sx0 < (1<<Paint::GRADIENT_LUT_BITS));
+    RI_ASSERT(sx1 >= 0 && sx1 < (1<<Paint::GRADIENT_LUT_BITS));
+
+}
+
+RI_INLINE static IntegerColor readLUTColor(const PixelPipe::PPUniforms& uniforms, int i)
+{
+    RI_ASSERT(i >= 0 && i <= Paint::GRADIENT_LUT_MASK);
+    return uniforms.gradientLookup[i];
+}
+
+
+/**
+ * \brief   Sample linear gradient using integer-arithmetic.
+ * \note    The actual gradient computation is done piecewise within the
+ *          pixel-pipeline.
+ */
+RI_INLINE static IntegerColor intLinearGradient(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v)
+{
+    RIint32 sx0 = v.sx >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS);
+    RIint32 sx1 = sx0 + 1;
+
+    applyGradientRepeat(sx0, sx1, state.paintTilingMode);
+
+    IntegerColor ic0 = readLUTColor(u, sx0 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS));
+
+    if (true)
+    {
+        return ic0;
+    } else
+    {
+        // bilinear interpolation
+        //RIint32 f1 = sx0; 
+        readLUTColor(u, sx1 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS));
+        RI_ASSERT(false);
+        return IntegerColor(0,0,0,0);
+    }
+} 
+
+/**
+ * \brief   Radial gradient implementation for the integer-pipeline. Will use float at least
+ *          for the square-root. Will return integer-color always.
+ */
+RI_INLINE static IntegerColor intRadialGradient(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v)
+{
+    RGScalar a = (v.rx * u.rfxp) + (v.ry * u.rfyp);
+    RGScalar b = u.rsqrp * (RI_SQR(v.rx) + RI_SQR(v.ry));
+    RGScalar c = RI_SQR((v.rx * u.rfyp) - (v.ry * u.rfxp));
+    RGScalar d = b - c;
+    RI_ASSERT(!RI_ISNAN(d) ? d >= 0.0f : true);
+    RGScalar g = (a + sqrtf(d));
+
+    int sx0 = RI_FLOAT_TO_FX(g, PixelPipe::SAMPLE_BITS);
+    int sx1 = sx0 + 1;
+
+    applyGradientRepeat(sx0, sx1, state.paintTilingMode);
+
+    IntegerColor ic0 = readLUTColor(u, sx0 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS));
+    RI_ASSERT(ic0.r <= 255);
+    RI_ASSERT(ic0.g <= 255);
+    RI_ASSERT(ic0.b <= 255);
+    RI_ASSERT(ic0.a <= 255);
+
+    if (false)
+    {
+        // Linear interpolation of 2 gradient samples.
+        IntegerColor ic1 = readLUTColor(u, sx1 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS));
+        //int fx0 = sx0 & PixelPipe::SAMPLE_MASK;
+        //int fx1 = PixelPipe::SAMPLE_MASK - fx0;
+        
+    }
+
+    return ic0;
+}
+
+RI_INLINE static bool applyPatternRepeat(int &x, int &y, PixelPipe::TilingMode tilingMode)
+{
+    switch (tilingMode)
+    {
+    case PixelPipe::TILING_MODE_PAD:
+        x = RI_INT_CLAMP(x, 0, PixelPipe::GRADIENT_MASK);
+        y = RI_INT_CLAMP(y, 0, PixelPipe::GRADIENT_MASK);
+        break; 
+    case PixelPipe::TILING_MODE_REPEAT:
+        x = x & PixelPipe::GRADIENT_MASK;
+        y = y & PixelPipe::GRADIENT_MASK;
+        break;
+    case PixelPipe::TILING_MODE_REFLECT:
+        x = intReflectRepeat(x, PixelPipe::GRADIENT_BITS);
+        y = intReflectRepeat(y, PixelPipe::GRADIENT_BITS);
+        break;
+    default:
+        RI_ASSERT(tilingMode == PixelPipe::TILING_MODE_FILL);
+        // Do nothing -> Fill is checked on integer coordinates.
+        break;
+    }
+    return false;
+}
+
+/**
+ * \brief   Same as applyPatternRepeat, but with pattern-space integer coordinates without
+ *          fractional part.
+ * \note    Assumes that the coordinate is in range [0,width or height].
+ */
+RI_INLINE static bool applyPatternSampleRepeat(int &x, int &y, int w, int h, PixelPipe::TilingMode tilingMode)
+{
+
+    switch (tilingMode)
+    {
+    case PixelPipe::TILING_MODE_PAD:
+        RI_ASSERT(x >= 0 && x <= w);
+        RI_ASSERT(y >= 0 && y <= h);
+        if (x >= w) x = w-1;
+        if (y >= h) y = h-1;
+        break;
+    case PixelPipe::TILING_MODE_REPEAT:
+        RI_ASSERT(x >= 0 && x <= w);
+        RI_ASSERT(y >= 0 && y <= h);
+        if (x >= w) x = 0;
+        if (y >= h) y = 0;
+        break;
+    case PixelPipe::TILING_MODE_REFLECT:
+        RI_ASSERT(x >= 0 && x <= w);
+        RI_ASSERT(y >= 0 && y <= h);
+        if (x >= w) x = w-1; // w-2?
+        if (y >= h) y = h-1; // h-2?
+        break;
+    default:
+        RI_ASSERT(tilingMode == PixelPipe::TILING_MODE_FILL);
+        if (x < 0 || x >= w) return true;
+        if (y < 0 || y >= h) return true;
+        break;
+    }
+
+    return false;
+}
+
+RI_INLINE IntegerColor readPattern(const void* basePtr, int stride, const Color::Descriptor& desc, int ix, int iy, const IntegerColor* fillColor, bool fill)
+{
+    const void* ptr = Image::calculateAddress(basePtr, desc.bitsPerPixel, ix, iy, stride);
+
+    if (!fill)
+        return IntegerColor(Image::readPackedPixelFromAddress(ptr, desc.bitsPerPixel, ix), desc);
+    else
+    {
+        RI_ASSERT(fillColor);
+        return *fillColor; 
+    }
+
+}
+
+/**
+ * \brief   Rescale the result of bilinear interpolation.
+ * \todo    See if this or individual shifts and rounds are faster on x86
+ */
+RI_INLINE static RIuint32 bilinearDiv(unsigned int c)
+{
+    RIuint32 rcp = 33026;
+
+    RIuint64 m = (RIuint64)c * rcp;
+    RIuint32 d = (RIuint32)(m >> 30);
+    return (d >> 1) + (d & 1);
+}
+
+/**
+ * \brief   Read an optionally filtered sample from an image. For multiple samples, apply repeat
+ *          for all the generated sampling points. This only implements a simple sampling: nearest
+ *          or Linear filtering and is much simpler than the original RI.
+ * \param   image       Image to sample from
+ * \param   sx0         Sample x in .8 fixed point. MUST be within the image except for FILL.
+ * \param   sy0         Sample y in .8 fixed point. MUST be within the image except for FILL.
+ * \param   samplerType Type of the sampler used.
+ * \param   tilingMode  Tiling mode for generated sample points, if required.
+ * \param   fillColor   Color to use for TILING_MODE_FILL
+ * \todo Where should we determine if a NN-sample needs to be unpacked?
+ *       -> It is also easy to just read that sample separately.
+ */
+RI_INLINE static IntegerColor intSampleImage(
+    const void* ptr,
+    int stride,
+    int w,
+    int h,
+    const Color::Descriptor& desc,
+    RIint32 sx0, 
+    RIint32 sy0, 
+    PixelPipe::SamplerType samplerType, 
+    PixelPipe::TilingMode tilingMode, 
+    const IntegerColor* fillColor)
+{
+    RI_ASSERT(fillColor || (tilingMode != PixelPipe::TILING_MODE_FILL));
+     
+    // \todo The following code is between low- and high-level representation of sampling.
+    // It should probably be modified to appear fully as low-level, since we want as many
+    // optimizations as possible.
+
+    const bool bilinear = samplerType == PixelPipe::SAMPLER_TYPE_LINEAR;
+
+    IntegerColor retColor;
+    bool maybeFill = tilingMode == PixelPipe::TILING_MODE_FILL;
+    bool fillSample = false;
+
+    RIint32 ix, iy;
+
+    IntegerColor ic00;
+
+    RIint32 fx = sx0 & 0xff;
+    RIint32 fy = sy0 & 0xff;
+
+    ix = sx0 >> PixelPipe::SAMPLE_BITS;
+    iy = sy0 >> PixelPipe::SAMPLE_BITS;
+
+    if (maybeFill)
+    {
+        if (ix < 0 || ix >= w)
+            fillSample = true;
+        if (iy < 0 || iy >= h)
+            fillSample = true;
+    }
+
+    ic00 = readPattern(ptr, stride, desc, ix, iy, fillColor, fillSample);
+
+    if (!bilinear)
+    {
+        retColor = ic00;
+        retColor.expandColor(desc); // \todo Handling of bilinear?
+    }
+    else
+    {
+        // Bilinear filtering.
+
+        IntegerColor ic01, ic10, ic11;
+        IntegerColor t0, t1;
+
+        int xs = ix + 1;
+        int ys = iy;
+
+        fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode);
+        ic01 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample);
+
+        t0 = IntegerColor::linearBlendNS(ic00, ic01, fx);
+
+        xs = ix;
+        ys = iy+1;
+        fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode);
+        ic10 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample);
+
+        xs = ix+1;
+        ys = iy+1;
+        fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode);
+        ic11 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample);
+    
+        t1 = IntegerColor::linearBlendNS(ic10, ic11, fx);
+    
+        retColor = IntegerColor::linearBlendNS(t0, t1, fy);
+
+        retColor.r = bilinearDiv(retColor.r);
+        retColor.g = bilinearDiv(retColor.g);
+        retColor.b = bilinearDiv(retColor.b);
+        retColor.a = bilinearDiv(retColor.a);
+
+        return retColor;
+    }
+
+    return retColor;
+}
+
+RI_INLINE static RIint32 gradientToFixedCoords(RIint32 gradCoord, RIint32 dim)
+{
+    return (RIint32)(((RIint64)dim * gradCoord) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS));
+}
+
+
+RI_INLINE static IntegerColor intPattern(const PixelPipe::SignatureState &state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v)
+{
+    // \todo The following code is between low- and high-level representation of sampling.
+    // It should probably be modified to appear fully as low-level, since we want as many
+    // optimizations as possible.
+
+    // "External" variables
+    const PixelPipe::TilingMode tilingMode = state.paintTilingMode;
+    const IntegerColor fillColor = u.tileFillColor;
+    const int w = u.paint_width;
+    const int h = u.paint_height;
+
+    IntegerColor retColor;
+
+    RIint32 sx0 = v.sx;
+    RIint32 sy0 = v.sy;
+
+    IntegerColor ic00;
+
+    applyPatternRepeat(sx0, sy0, tilingMode);
+    sx0 = gradientToFixedCoords(sx0, w);
+    sy0 = gradientToFixedCoords(sy0, h);
+    //sx0 = (RIint32)(((RIint64)w * sx0) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS));
+    //sy0 = (RIint32)(((RIint64)h * sy0) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS));
+
+    const void* ptr = u.patternPtr;
+    const int stride = u.patternStride;
+    const Color::Descriptor& desc = state.patternDesc;
+
+    return intSampleImage(ptr, stride, w, h, desc, sx0, sy0, state.paintSampler, tilingMode, &fillColor);
+}
+
+RI_INLINE static bool formatPremultipliedAfterSampling(const Color::Descriptor& desc, PixelPipe::SamplerType samplerType, PixelPipe::ImageGradientType gradientType)
+{
+    // Sampled at pixel centers -> no processing of colors -> does not get premultiplied
+    if (gradientType == PixelPipe::GRADIENT_TYPE_INTEGER)
+        return desc.isPremultiplied();
+
+    if (samplerType != PixelPipe::SAMPLER_TYPE_NEAREST)
+        return true;
+
+    return desc.isPremultiplied();
+}
+
+RI_INLINE static bool imagePremultipliedAfterSampling(const PixelPipe::SignatureState& state)
+{
+    RI_ASSERT(state.hasImage);
+
+    return formatPremultipliedAfterSampling(state.imageDesc, state.imageSampler, state.imageGradientType);
+}
+
+RI_INLINE static bool gradientPremultipliedAfterSampling(const PixelPipe::SignatureState& state)
+{
+    if (state.paintSampler != PixelPipe::SAMPLER_TYPE_NEAREST)
+        return true;
+
+    return true;
+
+    // Otherwise, the gradient value is a single sample, and should be in the destination
+    // color-space:
+    //return state.dstDesc.isPremultiplied();
+}
+
+RI_INLINE static bool patternPremultipliedAfterSampling(const PixelPipe::SignatureState& state)
+{
+    RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN);
+
+    return formatPremultipliedAfterSampling(state.patternDesc, state.paintSampler, PixelPipe::GRADIENT_TYPE_FIXED);
+}
+
+/**
+ * \brief   Returns true if generated paint will be in RGB, false if luminance.
+ */
+RI_INLINE static bool paintInRGB(const PixelPipe::SignatureState& state)
+{
+    if (state.paintType != VG_PAINT_TYPE_PATTERN)
+        return true;
+
+    return !state.patternDesc.isLuminance();
+}
+
+
+/**
+ * \brief   Applies color transform to input color
+ * \param   isNonlinear "true" if input is nonlinear. This only affects luminance -> RGB conversion,
+ *          other conversions happen in the input color-space.
+ * \note    Leaves the color unpremultiplied, in source color-space and converts luminance to RGB
+ * \todo    isNonlinear is not needed. It can be deduced from the state information!
+ */
+RI_INLINE static IntegerColor maybeColorTransform(const PixelPipe::SignatureState& state, const IntegerColor& c, const RIint32* colorTransformValues, bool isNonlinear)
+{
+    if (!state.hasColorTransform)
+        return c;
+
+    RI_ASSERT(state.hasImage || state.paintType == VG_PAINT_TYPE_PATTERN);
+    
+    IntegerColor r = c;
+
+    if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY)
+    {
+        r.unpremultiply();
+    }
+    else if (state.imageMode == VG_DRAW_IMAGE_STENCIL || state.paintType == VG_PAINT_TYPE_PATTERN)
+    {
+        // -> Check pattern
+        if (patternPremultipliedAfterSampling(state))
+            r.unpremultiply(); 
+    }
+    else
+    {
+        // -> Check image
+        if (imagePremultipliedAfterSampling(state))
+            r.unpremultiply();
+    }
+
+    // Check if it is necessary to convert to RGB:
+    if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY)
+    {
+        if (state.imageDesc.isLuminance() && !paintInRGB(state))
+        {
+            r.fullLuminanceToRGB(false, isNonlinear, false, isNonlinear);
+        }
+    }
+    else if (state.imageMode == VG_DRAW_IMAGE_STENCIL)
+    {
+        if (state.patternDesc.isLuminance())
+            r.fullLuminanceToRGB(false, isNonlinear, false, isNonlinear);
+    }
+    
+    // \todo Use lookup-tables in some cases?
+    r.r = (((RIint32)r.r * colorTransformValues[0]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[4];
+    r.g = (((RIint32)r.g * colorTransformValues[1]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[5];
+    r.b = (((RIint32)r.b * colorTransformValues[2]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[6];
+    r.a = (((RIint32)r.a * colorTransformValues[3]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[7];
+
+    // Clamp (integerColor?)
+    r.r = (RIuint32)RI_INT_CLAMP((int)r.r, 0, 255);
+    r.g = (RIuint32)RI_INT_CLAMP((int)r.g, 0, 255);
+    r.b = (RIuint32)RI_INT_CLAMP((int)r.b, 0, 255);
+    r.a = (RIuint32)RI_INT_CLAMP((int)r.a, 0, 255);
+
+
+    return r;
+}
+
+/// Some rounding multiplications for blends:
+
+/**
+ * \brief   Multiply with rounding.
+ */
+RI_INLINE static RIuint32 rMul2(RIuint32 c0, RIuint32 c1, RIuint32 k0, RIuint32 k1)
+{
+    RIuint32 t = c0 * k0 + c1 * k1; 
+    //RIuint32 r = (t + (t>>9)) >> 8;
+    RIuint32 r = (t + (1>>7))>>8;
+    RI_ASSERT(r <= 255);
+    return r;
+}
+
+/**
+ * \brief   Returns rounding color-multiplication: c0 + c1 * k
+ */
+RI_INLINE static RIuint32 rMul1(RIuint32 c0, RIuint32 c1, RIuint32 k)
+{
+    RIuint32 t = c1 * k;
+    RIuint32 r = c0 + ((t + (t >> 7)) >> 8);
+    RI_ASSERT(r <= 255);
+    return r;
+}
+
+/**
+ * \brief   Fixed-point multiplication
+ */
+RI_INLINE static RIuint32 rMul(RIuint32 c0, RIuint32 f)
+{
+    RIuint32 t = c0 * f;
+    return (t + (1<<7))>>8;
+}
+
+/**
+ * \brief   Multiply two colors [0, 255]
+ */
+RI_INLINE static RIuint32 cMul(RIuint32 c0, RIuint32 c1)
+{
+    RIuint32 t = c0 * c1;
+    RIuint32 r = (t + (t >> 9)) >> 8;
+    //RIuint32 t = c0 * c1;
+    //RIuint32 r = (t + (t >> 7))>>8;
+    RI_ASSERT(r <= 255);
+    return r;
+}
+
+// \todo Are signed versions required?
+RI_INLINE static RIuint32 cMin(RIuint32 c0, RIuint32 c1)
+{
+    return c0 <= c1 ? c0 : c1;
+}
+
+RI_INLINE static RIuint32 cMax(RIuint32 c0, RIuint32 c1)
+{
+    return c0 >= c1 ? c0 : c1;
+}
+
+/**
+ * \brief   Blends two integer colors. Only considers the alpha-channels within
+ *          the colors themselves. There should be a separate function to do
+ *          blending with individual channel-alphas.
+ * \note    It is also possible that LLVM is able to detect, whether individual alpha-
+ *          channels contain a single/multi alpha
+ * \todo    Overall, check how much and how fast LLVM is able to optimize out unused
+ *          expressions.
+ */
+RI_INLINE static IntegerColor blendIntegerColors(const IntegerColor& s, const IntegerColor& d, VGBlendMode blendMode)
+{
+    IntegerColor r;
+
+    switch(blendMode)
+    {
+    case VG_BLEND_SRC:
+        r = s;
+        break;
+
+    case VG_BLEND_SRC_OVER:
+    {
+        RIuint32 ia = 255 - s.a;
+        r.r = rMul1(s.r, d.r, ia);
+        r.g = rMul1(s.g, d.g, ia);
+        r.b = rMul1(s.b, d.b, ia);
+        r.a = rMul1(s.a, d.a, ia);
+        break;
+    }
+    case VG_BLEND_DST_OVER:
+    {
+        RIuint32 ia = 255 - d.a;
+        r.r = rMul1(d.r, s.r, ia);
+        r.g = rMul1(d.g, s.g, ia);
+        r.b = rMul1(d.b, s.b, ia);
+        r.a = rMul1(d.a, s.a, ia);
+        break;
+    }
+    case VG_BLEND_SRC_IN:
+    {
+        r.r = cMul(s.r, d.a);
+        r.g = cMul(s.g, d.a);
+        r.b = cMul(s.b, d.a);
+        r.a = cMul(s.a, d.a);
+        break;
+    }
+    case VG_BLEND_DST_IN:
+    {
+        r.r = cMul(d.r, s.a);
+        r.g = cMul(d.g, s.a);
+        r.b = cMul(d.b, s.a);
+        r.a = cMul(d.a, s.a);
+        break;
+    }
+    case VG_BLEND_MULTIPLY:
+    {
+        RIuint32 iasrc, iadst;
+        iasrc = 255 - s.a;
+        iadst = 255 - d.a;
+        r.r = rMul2(s.r, d.r, iadst + d.r, iasrc);
+        r.g = rMul2(s.g, d.g, iadst + d.g, iasrc);
+        r.b = rMul2(s.b, d.b, iadst + d.b, iasrc);
+        r.a = rMul1(s.a, d.a, iasrc);
+        break;
+    }
+    case VG_BLEND_SCREEN:
+    {
+        r.r = rMul1(s.r, d.r, 255 - s.r);
+        r.g = rMul1(s.g, d.g, 255 - s.g);
+        r.b = rMul1(s.b, d.b, 255 - s.b);
+        r.a = rMul1(s.a, d.a, 255 - s.a);
+        break;
+    }
+    case VG_BLEND_DARKEN:
+    {
+        RIuint32 iasrc = 255 - s.a;
+        RIuint32 iadst = 255 - d.a;
+        r.r = cMin(rMul1(s.r, d.r, iasrc), rMul1(d.r, s.r, iadst));
+        r.g = cMin(rMul1(s.g, d.g, iasrc), rMul1(d.g, s.g, iadst));
+        r.b = cMin(rMul1(s.b, d.b, iasrc), rMul1(d.b, s.b, iadst));
+        r.a = rMul1(s.a, d.a, iasrc);
+        break;
+    }
+    case VG_BLEND_LIGHTEN:
+    {
+        // \todo Compact darken w/r lighten?
+        RIuint32 iasrc = 255 - s.a;
+        RIuint32 iadst = 255 - d.a;
+        r.r = cMax(rMul1(s.r, d.r, iasrc), rMul1(d.r, s.r, iadst));
+        r.g = cMax(rMul1(s.g, d.g, iasrc), rMul1(d.g, s.g, iadst));
+        r.b = cMax(rMul1(s.b, d.b, iasrc), rMul1(d.b, s.b, iadst));
+        //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a)
+        //in practice there can be a very slight difference because
+        //of the max operation in the blending formula that may cause color to exceed alpha.
+        //Because of this, we compute the result both ways and return the maximum.
+        r.a = cMax(rMul1(s.a, d.a, iasrc), rMul1(d.a, s.a, iadst));
+        break;
+    }
+    default:
+    {
+        RI_ASSERT(blendMode == VG_BLEND_ADDITIVE);
+        r.r = cMin(s.r + d.r, 255);
+        r.g = cMin(s.g + d.g, 255);
+        r.b = cMin(s.b + d.b, 255);
+        r.a = cMin(s.a + d.a, 255);
+        break;
+    }
+    }
+    return r;
+
+}
+
+RI_INLINE static IntegerColor blendIntegerStencil(const IntegerColor& s, const IntegerColor& im, const IntegerColor& d, VGBlendMode blendMode)
+{
+    IntegerColor r;
+
+    switch(blendMode)
+    {
+    case VG_BLEND_SRC:
+        r = s;
+        break;
+
+    case VG_BLEND_SRC_OVER:
+    {
+        r.r = rMul1(s.r, d.r, 255 - im.r);
+        r.g = rMul1(s.g, d.g, 255 - im.g);
+        r.b = rMul1(s.b, d.b, 255 - im.b);
+        r.a = rMul1(s.a, d.a, 255 - s.a);
+        break;
+    }
+    case VG_BLEND_DST_OVER:
+    {
+        r = blendIntegerColors(s, d, blendMode);
+        break;
+    }
+    case VG_BLEND_SRC_IN:
+    {
+        r = blendIntegerColors(s, d, blendMode);
+        break;
+    }
+    case VG_BLEND_DST_IN:
+    {
+        r.r = cMul(d.r, im.r);
+        r.g = cMul(d.g, im.g);
+        r.b = cMul(d.b, im.b);
+        r.a = cMul(d.a, s.a);
+        break;
+    }
+    case VG_BLEND_MULTIPLY:
+    {
+        RIuint32 iadst;
+        iadst = 255 - d.a;
+        r.r = rMul2(s.r, d.r, iadst + d.r, 255 - im.r);
+        r.g = rMul2(s.g, d.g, iadst + d.g, 255 - im.g);
+        r.b = rMul2(s.b, d.b, iadst + d.b, 255 - im.b);
+        r.a = rMul1(s.a, d.a, 255 - s.a);
+        break;
+    }
+    case VG_BLEND_SCREEN:
+    {
+        r = blendIntegerColors(s, d, blendMode);
+        break;
+    }
+    case VG_BLEND_DARKEN:
+    {
+        RIuint32 iadst = 255 - d.a;
+        r.r = cMin(rMul1(s.r, d.r, 255 - im.r), rMul1(d.r, s.r, iadst));
+        r.g = cMin(rMul1(s.g, d.g, 255 - im.g), rMul1(d.g, s.g, iadst));
+        r.b = cMin(rMul1(s.b, d.b, 255 - im.b), rMul1(d.b, s.b, iadst));
+        r.a = rMul1(s.a, d.a, 255 - s.a);
+        break;
+    }
+    case VG_BLEND_LIGHTEN:
+    {
+        // \todo Compact darken w/r lighten?
+        RIuint32 iadst = 255 - d.a;
+        r.r = cMax(rMul1(s.r, d.r, 255 - im.r), rMul1(d.r, s.r, iadst));
+        r.g = cMax(rMul1(s.g, d.g, 255 - im.g), rMul1(d.g, s.g, iadst));
+        r.b = cMax(rMul1(s.b, d.b, 255 - im.b), rMul1(d.b, s.b, iadst));
+        //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a)
+        //in practice there can be a very slight difference because
+        //of the max operation in the blending formula that may cause color to exceed alpha.
+        //Because of this, we compute the result both ways and return the maximum.
+        r.a = cMax(rMul1(s.a, d.a, 255 - s.a), rMul1(d.a, s.a, iadst));
+        break;
+    }
+    default:
+    {
+        RI_ASSERT(blendMode == VG_BLEND_ADDITIVE);
+        return blendIntegerColors(s, d, blendMode);
+        break;
+    }
+    }
+    return r;
+
+}
+
+/**
+ * \brief   Perform SRC_OVER and apply coverage in a single operation.
+ * \note    It is possible to do optimizations like this for other blending operations,
+ *          but they are not as widely used -> optimize if there is a requirement.
+ * \note    Prints are included because GDB is confused about the value of r.
+ */
+static RI_INLINE IntegerColor srcOverCoverage(const IntegerColor& s, const IntegerColor& d, RIuint32 cov)
+{
+    IntegerColor r;
+    RIuint32 ac = ((s.a + (s.a>>7)) * cov);
+    ac = (ac + (1<<7))>>8;
+    RIuint32 ia = 256 - ac;
+
+    r.r = rMul2(s.r, d.r, cov, ia);
+    r.g = rMul2(s.g, d.g, cov, ia);
+    r.b = rMul2(s.b, d.b, cov, ia);
+    r.a = rMul2(s.a, d.a, cov, ia);
+    //r.r = (s.r * cov + d.r * ia) >> 8;
+    //r.g = (s.g * cov + d.g * ia) >> 8;
+    //r.b = (s.b * cov + d.b * ia) >> 8;
+    //r.a = (s.a * cov + d.a * ia) >> 8;
+
+#if defined(RI_DEBUG)
+    if (!(r.r <= r.a && r.g <= r.a && r.b <= r.a && r.a <= 255))
+    {
+        printf("r: %d, g: %d, b: %d, a: %d\n",r.r,r.g,r.b,r.a);
+        RI_ASSERT(false);
+    }
+    //RI_ASSERT(r.r <= 255 && r.g <= 255 && r.b <= 255 && r.a <= 255);
+#endif
+
+    return r;
+}
+
+/**
+ * \brief   Check if converting between two color formats requires a gamma-conversion.
+ * \todo    Move this to descriptor class.
+ */
+static RI_INLINE bool needGammaConvert(const Color::Descriptor& srcDesc, const Color::Descriptor& dstDesc)
+{
+    //if ((!srcDesc.isAlphaOnly()) && (srcDesc.isNonlinear() != dstDesc.isNonlinear()))
+        //return true;
+    if ((srcDesc.isNonlinear() != dstDesc.isNonlinear()))
+        return true;
+
+    return false;
+}
+
+
+RI_INLINE static bool preBlendPremultiplication(const PixelPipe::SignatureState& state)
+{
+    // \todo Simplify the rules (see the corresponding places in the pixelpipe
+    const bool colorTransform = state.hasColorTransform;
+
+    if (PixelPipe::isImageOnly(state))
+    {
+        if (colorTransform)
+            return true;
+
+        // Gamma conversion will leave the result premultiplied
+        if (needGammaConvert(state.imageDesc, state.dstDesc))
+            return true;
+        //if (state.imageDesc.isAlphaOnly())
+            //return false;
+
+        return !imagePremultipliedAfterSampling(state);
+    }
+
+    if (state.hasImage)
+    {
+        if (state.imageMode == VG_DRAW_IMAGE_NORMAL)
+            return !imagePremultipliedAfterSampling(state);
+        // Image color has been combined with the paint color and that requires premultiplication
+        if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY)
+            return false; // Always results in a premultiplied output color
+
+        return false; // ?
+    }
+
+    if (state.paintType == VG_PAINT_TYPE_COLOR)
+        return false;
+
+    if (state.paintType != VG_PAINT_TYPE_PATTERN)
+        return !gradientPremultipliedAfterSampling(state);
+
+    // Must be pattern
+    RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN);
+
+    if (state.hasColorTransform)
+        return true;
+
+    if (needGammaConvert(state.patternDesc, state.dstDesc))
+        return true;
+    
+    return !patternPremultipliedAfterSampling(state);
+}
+
+/**
+ * \brief   Apply coverage [0 .. 256] on color
+ * \note    This is actually "just coverage".
+ */
+RI_INLINE static IntegerColor srcCoverage(const IntegerColor& s, const IntegerColor& d, RIuint32 cov)
+{
+    IntegerColor r;
+    RIuint32 icov = 256-cov;
+    // Make function for multiplication between fixed point values (coverage is
+    // a proper [0 .. 1] value.
+    r.r = (s.r * cov + d.r * icov) >> 8;
+    r.g = (s.g * cov + d.g * icov) >> 8;
+    r.b = (s.b * cov + d.b * icov) >> 8;
+    r.a = (s.a * cov + d.a * icov) >> 8;
+
+    RI_ASSERT(r.r <= 255 && r.g <= 255 && r.b <= 255 && r.a <= 255);
+
+    return r;
+}
+
+/**
+ * \brief   Converts color gamma only. Care must be taken concerning luminance color formats.
+ * \return  Converted color in "color". This will always be unpremultiplied if gamma conversion
+ *          takes place, i.e, tries to minimize the amount of further conversions.
+ */
+RI_INLINE static void maybeGammaConvert(const Color::Descriptor& srcDesc, const Color::Descriptor& dstDesc, IntegerColor& color, bool inputPremultiplied)
+{
+    if (needGammaConvert(srcDesc, dstDesc))
+    {
+        if (inputPremultiplied)
+            color.unpremultiply();
+            //color.unpremultiply(srcDesc.isLuminance());
+
+        if (dstDesc.isNonlinear())
+            color.linearToGamma();
+        else
+            color.gammaToLinear();
+    }
+    // Output always unpremultiplied if gamma conversion takes place
+}
+
+/**
+ * \brief   Integer pixel-pipeline.
+ * \note    See internal_formats.txt for info on how the data is passed within the pipeline
+ */
+RI_INLINE static void intPixelPipe(const PixelPipe::SignatureState& signatureState, const PixelPipe::PPUniforms &uniforms, PixelPipe::PPVariants& variants)
+{
+    const RIuint32 ppMaxCoverage = Rasterizer::MAX_COVERAGE << (8 - Rasterizer::SAMPLE_BITS);
+    RIuint32 coverage = variants.coverage << (8 - Rasterizer::SAMPLE_BITS);
+    IntegerColor out;
+    IntegerColor imageColor; // imagemode != normal
+    const Color::Descriptor& dstDesc = signatureState.dstDesc;
+    const Color::Descriptor& patternDesc = signatureState.patternDesc;
+    const Color::Descriptor& imageDesc = signatureState.imageDesc;
+
+    if (!PixelPipe::isImageOnly(signatureState))
+    {
+        switch(signatureState.paintType)
+        {
+        case VG_PAINT_TYPE_COLOR:
+            out = uniforms.solidColor;
+            break;
+        case VG_PAINT_TYPE_LINEAR_GRADIENT:
+            out = intLinearGradient(signatureState, uniforms, variants);
+            variants.sx += uniforms.dgdx;
+            // \todo Optimize this so that the lookup is in premultiplied dst format!
+            // How about image-operations?
+            if ((signatureState.imageMode != VG_DRAW_IMAGE_MULTIPLY) && dstDesc.isLuminance())
+            {
+                out.fullRGBToLuminance(true, dstDesc.isNonlinear(), true, dstDesc.isNonlinear());
+            }
+            break;
+        case VG_PAINT_TYPE_RADIAL_GRADIENT:
+            out = intRadialGradient(signatureState, uniforms, variants);
+            variants.rx += uniforms.rdxdx;
+            variants.ry += uniforms.rdydx;
+
+            // \todo Optimize this so that the lookup is in premultiplied dst format!
+            if ((signatureState.imageMode != VG_DRAW_IMAGE_MULTIPLY) && dstDesc.isLuminance())
+            {
+                out.fullRGBToLuminance(true, dstDesc.isNonlinear(), true, dstDesc.isNonlinear());
+            }
+            break;
+        default:
+            RI_ASSERT(signatureState.paintType == VG_PAINT_TYPE_PATTERN);
+            out = intPattern(signatureState, uniforms, variants);
+            // color-space == pattern color-space, not always premultiplied, expanded
+            //
+            // \todo Only increment the proper pixel-counters. This requires detecting the
+            // transform type before generating the pixel-pipeline.
+            // \note Implement fastpaths for at least identity transform with image edges coinciding
+            // with the pixel edges. <- This has been done for images.
+            variants.sx += uniforms.paint_dxdx;
+            variants.sy += uniforms.paint_dydx;
+
+            if (!patternDesc.hasAlpha())
+                out.a = 255;
+
+            if (!signatureState.hasImage)
+            {
+                out = maybeColorTransform(signatureState, out, uniforms.colorTransformValues, patternDesc.isNonlinear());
+                const bool tmpPre = patternPremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform;
+                const bool outLuminance = !signatureState.hasColorTransform && imageDesc.isLuminance();
+
+                if (outLuminance != dstDesc.isLuminance())
+                {
+                    if (outLuminance)
+                        out.fullLuminanceToRGB(tmpPre, patternDesc.isNonlinear(), tmpPre, patternDesc.isNonlinear());
+                    else
+                        out.fullRGBToLuminance(tmpPre, patternDesc.isNonlinear(), tmpPre, patternDesc.isNonlinear());
+                }
+                maybeGammaConvert(patternDesc, dstDesc, out, tmpPre);
+            }
+
+            break;
+        }
+    }
+    
+    if (signatureState.hasImage)
+    {
+        switch (signatureState.imageGradientType)
+        {
+        case PixelPipe::GRADIENT_TYPE_INTEGER:
+        {
+            void* addr = Image::calculateAddress(uniforms.imagePtr, imageDesc.bitsPerPixel, variants.iImageX, variants.iImageY, uniforms.imageStride);
+            RIuint32 packedImageColor = Image::readPackedPixelFromAddress(addr, imageDesc.bitsPerPixel, variants.iImageX);
+            imageColor.fromPackedColor(packedImageColor, imageDesc);
+            imageColor.expandColor(imageDesc);
+            // color-space == image color-space, not always premultiplied, expanded
+
+            // Only integer image-gradient can have unsafe image data as an input at the moment.
+            if (signatureState.unsafeImageInput)
+            {
+                if (imageDesc.hasAlpha() && imageDesc.isPremultiplied())
+                    imageColor.clampToAlpha();
+            }
+
+            variants.iImageX += uniforms.image_idxdx;
+            variants.iImageY += uniforms.image_idydx;
+            break;
+        }
+        case PixelPipe::GRADIENT_TYPE_FIXED:
+        {
+            RI_ASSERT(!signatureState.unsafeImageInput);
+
+            RIint32 sx, sy;
+            sx = variants.iImageX;
+            sy = variants.iImageY;
+            applyPatternRepeat(sx, sy, PixelPipe::TILING_MODE_PAD);
+            sx = gradientToFixedCoords(sx, uniforms.image_iWidth);
+            sy = gradientToFixedCoords(sy, uniforms.image_iHeight);
+            imageColor = intSampleImage(
+                uniforms.imagePtr,
+                uniforms.imageStride,
+                uniforms.image_iWidth,
+                uniforms.image_iHeight,
+                imageDesc,
+                sx, sy, signatureState.imageSampler, PixelPipe::TILING_MODE_PAD, NULL);
+
+            variants.iImageX += uniforms.image_idxdx;
+            variants.iImageY += uniforms.image_idydx;
+            break;
+        }
+        default:
+        {
+            RI_ASSERT(signatureState.imageGradientType == PixelPipe::GRADIENT_TYPE_FLOAT);
+            RI_ASSERT(!signatureState.unsafeImageInput);
+
+            RIfloat fx, fy, fw, rw;
+            fx = variants.fImageX;
+            fy = variants.fImageY;
+            fw = variants.fImageW;
+            rw = 1.0f / fw;
+            RIint32 sx0, sy0;
+            fx = RI_CLAMP(fx * rw, 0.0f, uniforms.image_fWidth - 1.0f); // \todo fImageMaxX
+            fy = RI_CLAMP(fy * rw, 0.0f, uniforms.image_fHeight - 1.0f);
+            sx0 = RI_ROUND_TO_INT(fx * (1<<PixelPipe::SAMPLE_BITS));
+            sy0 = RI_ROUND_TO_INT(fy * (1<<PixelPipe::SAMPLE_BITS)); 
+
+            imageColor = intSampleImage(
+                uniforms.imagePtr,
+                uniforms.imageStride,
+                uniforms.image_iWidth,
+                uniforms.image_iHeight,
+                imageDesc,
+                sx0, sy0, signatureState.imageSampler, PixelPipe::TILING_MODE_PAD, NULL);
+
+            variants.fImageX += uniforms.image_fdxdx;
+            variants.fImageY += uniforms.image_fdydx;
+            variants.fImageW += uniforms.image_fdwdx;
+            break;
+        }
+        }
+
+        if (!imageDesc.hasAlpha())
+            imageColor.a = 255;
+        
+        if (PixelPipe::isImageOnly(signatureState))
+        {
+            RI_ASSERT(signatureState.imageMode == VG_DRAW_IMAGE_NORMAL);
+            out = maybeColorTransform(signatureState, imageColor, uniforms.colorTransformValues, imageDesc.isNonlinear());
+
+            const bool tmpPre = imagePremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform;
+            const bool outLuminance = !signatureState.hasColorTransform && imageDesc.isLuminance();
+
+            // Color-format conversion to dst before blending.
+            if (outLuminance != dstDesc.isLuminance())
+            {
+                if (outLuminance)
+                    out.fullLuminanceToRGB(tmpPre, imageDesc.isNonlinear(), tmpPre, imageDesc.isNonlinear());
+                else
+                    out.fullRGBToLuminance(tmpPre, imageDesc.isNonlinear(), tmpPre, imageDesc.isNonlinear());
+            }
+            maybeGammaConvert(imageDesc, dstDesc, out, tmpPre);
+
+            //if (!signatureState.hasColorTransform)
+                //out.premultiply();
+        }
+        else
+        {
+            RI_ASSERT(signatureState.imageMode != VG_DRAW_IMAGE_NORMAL);
+
+            if (!imagePremultipliedAfterSampling(signatureState))
+                imageColor.premultiply();
+
+            if (signatureState.imageMode == VG_DRAW_IMAGE_MULTIPLY)
+            {
+                if (signatureState.paintType == VG_PAINT_TYPE_PATTERN && 
+                    !patternPremultipliedAfterSampling(signatureState))
+                {
+                    out.premultiply();
+                }
+
+                out.r = cMul(out.r, imageColor.r);
+                out.g = cMul(out.g, imageColor.g);
+                out.b = cMul(out.b, imageColor.b);
+                out.a = cMul(out.a, imageColor.a);
+
+                out = maybeColorTransform(signatureState, out, uniforms.colorTransformValues, imageDesc.isNonlinear());
+                //const bool outLuminance = !signatureState.hasColorTransform && imageDesc.isLuminance();
+                // Color transform will always result in RGB, regardless of input.
+                const bool outLuminance = (imageDesc.isLuminance() && !paintInRGB(signatureState)) && !signatureState.hasColorTransform;
+                if (!outLuminance && dstDesc.isLuminance())
+                {
+                    // Convert to destination (luminance)
+                    out.fullRGBToLuminance(!signatureState.hasColorTransform, imageDesc.isNonlinear(), true, dstDesc.isNonlinear());
+                }
+                else if (imageDesc.isNonlinear() != dstDesc.isNonlinear())
+                {
+                    // Non-luminance gamma
+                    if (!signatureState.hasColorTransform)
+                        out.unpremultiply();
+
+                    if (dstDesc.isNonlinear())
+                        out.linearToGamma();
+                    else
+                        out.gammaToLinear();
+
+                    out.premultiply();
+                }
+                else if (signatureState.hasColorTransform)
+                    out.premultiply();
+
+                // Output dst and premultiplied.
+            } 
+            else
+            {
+                RI_ASSERT(signatureState.imageMode == VG_DRAW_IMAGE_STENCIL);
+                IntegerColor alphas, pr;
+                
+                if (signatureState.paintType == VG_PAINT_TYPE_PATTERN)
+                {
+                    out = maybeColorTransform(signatureState, out, uniforms.colorTransformValues, patternDesc.isNonlinear());
+                    const bool isLuminance = patternDesc.isLuminance() && !signatureState.hasColorTransform;
+                    // If using pattern, convert to destination color-space
+                    // \todo If not, handle this when the lookups are generated.
+                    if (isLuminance != dstDesc.isLuminance())
+                    {
+                        out.fullRGBToLuminance(patternPremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform, patternDesc.isNonlinear(), true, dstDesc.isNonlinear());
+                    }
+                    else if (patternDesc.isNonlinear() != dstDesc.isNonlinear())
+                    {
+                        if (patternPremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform)
+                            out.unpremultiply();
+
+                        if (dstDesc.isNonlinear())
+                            out.linearToGamma();
+                        else
+                            out.gammaToLinear();
+
+                        out.premultiply();
+                    } else if (signatureState.hasColorTransform || !patternPremultipliedAfterSampling(signatureState))
+                        out.premultiply();
+                }
+
+                if (dstDesc.isLuminance() && !imageDesc.isLuminance())
+                {
+                    // Convert image to luminance
+                    imageColor.rgbToLuminance();
+                    imageColor.r = imageColor.b = imageColor.b = RI_INT_MIN(imageColor.r, imageColor.a);
+                }
+
+#if defined(RI_DEBUG) && 0
+                printf("stencil r: %d, g: %d, b: %d, a: %d\n",imageColor.r,imageColor.g,imageColor.b,imageColor.a);
+                printf("input r: %d, g: %d, b: %d, a: %d\n",out.r,out.g,out.b,out.a);
+#endif
+                if (signatureState.paintType == VG_PAINT_TYPE_COLOR)
+                {
+                    // Better precision for solid color input.
+                    // Compute alpha channels
+                    alphas.r = rMul(out.a, imageColor.r);
+                    alphas.g = rMul(out.a, imageColor.g);
+                    alphas.b = rMul(out.a, imageColor.b);
+                    // Premultiply
+                    pr.r = rMul(out.r, imageColor.r);
+                    pr.g = rMul(out.g, imageColor.g);
+                    pr.b = rMul(out.b, imageColor.b);
+                    pr.a = rMul(out.a, imageColor.a);
+                }
+                else
+                {
+                    // Compute alpha channels
+                    alphas.r = cMul(out.a, imageColor.r);
+                    alphas.g = cMul(out.a, imageColor.g);
+                    alphas.b = cMul(out.a, imageColor.b);
+                    // Premultiply
+                    pr.r = cMul(out.r, imageColor.r);
+                    pr.g = cMul(out.g, imageColor.g);
+                    pr.b = cMul(out.b, imageColor.b);
+                    pr.a = cMul(out.a, imageColor.a);
+                }
+#if defined(RI_DEBUG) && 0
+                printf("alphas r: %d, g: %d, b: %d, a: %d\n",alphas.r,alphas.g,alphas.b,alphas.a);
+                printf("pr r: %d, g: %d, b: %d, a: %d\n",pr.r,pr.g,pr.b,pr.a);
+#endif
+                out = pr;
+                imageColor = alphas;
+            }
+        }
+    }
+
+    if (signatureState.hasMasking)
+    {
+        // \todo Read and process only the proper component of the mask pixel.
+        const int maskBpp = signatureState.maskDesc.bitsPerPixel;
+
+        RIuint32 packedMaskColor = Image::readPackedPixelFromAddress(variants.maskPtr, maskBpp, variants.dstX);
+        IntegerColor maskColor;
+        maskColor.fromPackedMask(packedMaskColor, signatureState.maskDesc);
+        maskColor.expandMask(signatureState.maskDesc);
+
+        RIuint32 maskCoverage = maskColor.a + (maskColor.a >> 7);
+        coverage = (coverage * maskCoverage) >> 8;
+
+        variants.maskPtr = (void*)Image::incrementPointer(variants.maskPtr, maskBpp, variants.dstX);  
+    }
+    
+#if defined(RI_DEBUG)
+    IntegerColor preblend = out;
+#endif
+    // \todo Coverage check for pixelpipes != solid color with solid output colors?
+
+    IntegerColor d(0,0,0,0);
+
+    // All operations that depend on DST are done next. Keep it organized like that.
+    if ((coverage < ppMaxCoverage) || (out.a < 255) || alwaysLoadDst(signatureState))
+    {
+        d = IntegerColor(Image::readPackedPixelFromAddress(
+            variants.dst, dstDesc.bitsPerPixel, variants.dstX), dstDesc);
+        d.expandColor(dstDesc);
+
+        if (!dstDesc.isPremultiplied())
+        {
+            d.premultiply();
+        }
+
+        // Premultiply output
+#if 0
+        if (!PixelPipe::isImageOnly(signatureState))
+        {
+            if (signatureState.paintType == VG_PAINT_TYPE_PATTERN && !patternPremultipliedAfterSampling(signatureState))
+                out.premultiply();
+            else if (signatureState.hasImage && !imagePremultipliedAfterSampling(signatureState))
+                out.premultiply();
+        }
+#endif
+
+        if (!signatureState.isRenderToMask)
+        {
+            VGBlendMode bm = signatureState.blendMode;
+
+            // Currently SRC requires premultiplication even when only applying coverage.
+            //if (bm != VG_BLEND_SRC)
+            {
+                // If the src color has not been premultiplied before, now's the time.
+                // \todo Fast path for src alpha == 255 and SRC_OVER? Others?
+                if (preBlendPremultiplication(signatureState))
+                    out.premultiply();
+            }
+
+            if (signatureState.hasImage && signatureState.imageMode == VG_DRAW_IMAGE_STENCIL)
+            {
+                out = blendIntegerStencil(out, imageColor, d, bm);
+            } 
+            else
+            {
+                switch(bm)
+                {
+                case VG_BLEND_SRC_OVER:
+                    out = srcOverCoverage(out, d, coverage);
+                    break;
+                case VG_BLEND_SRC:
+                    out = srcCoverage(out, d, coverage);
+                    break;
+                default:
+                    out = blendIntegerColors(out, d, bm);
+                    out = srcCoverage(out, d, coverage);
+                    break;
+                }
+            }
+
+#if defined(RI_DEBUG)
+            if (dstDesc.isPremultiplied())
+            {
+                RI_ASSERT(out.r <= out.a);
+                RI_ASSERT(out.g <= out.a);
+                RI_ASSERT(out.b <= out.a);
+            }
+#endif
+
+        }
+        else
+        {
+            // Mask operation
+            out = intMaskOperation(coverage, d, signatureState.maskOperation);
+        }
+
+        // out is always premultiplied at this point. Must be in destination color-space
+        if (!dstDesc.isPremultiplied())
+        { 
+            // Unpremultiply if output is not premultiplied
+            out.unpremultiply();
+        }
+    }
+    else
+    {
+        // Unpremultiply, ...
+        if (!dstDesc.isPremultiplied())
+            out.unpremultiply();
+    }
+
+    // VG_SET_MASK does not require dst load:
+    if (signatureState.isRenderToMask && signatureState.maskOperation == VG_SET_MASK)
+        out = intMaskOperation(coverage, d, VG_SET_MASK);
+
+    out.truncateColor(dstDesc);
+    Image::writePackedPixelToAddress(
+        variants.dst, dstDesc.bitsPerPixel, variants.dstX, out.getPackedColor(dstDesc));
+
+    // \todo X for bpp < 8
+    variants.dst = (void*)Image::incrementPointer(variants.dst, dstDesc.bitsPerPixel, variants.dstX);
+    //variants.dst = colorBuffer->advancePointer(variants.dst);
+    variants.dstX++;
+}
+
+RI_INLINE static void fillSolidSpan(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, int startX, int y, int nPixels, RIuint32 packedColor) 
+{
+    Image::fillPackedPixels((void*)uniforms.dstPtr, state.dstDesc.bitsPerPixel, startX, y, uniforms.dstStride, nPixels, packedColor);
+}
+
+/**
+ * \brief   This will calculate all the pixel-pipeline variants that need to be updated per-pixel.
+ * \note    There may be a need for a different, faster function for image rendering, where
+ *          there are faster methods of updating the variants.
+ */
+RI_INLINE static void prepareSpanVariants(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, const Span& span, PixelPipe::PPVariants& variants)
+{
+    //variants.dst = uniforms.dst->calculateAddress(span.x0, span.y);
+    variants.dst = Image::calculateAddress(uniforms.dstPtr, state.dstDesc.bitsPerPixel, span.x0, span.y, uniforms.dstStride);
+    variants.dstX = span.x0;
+    variants.coverage = span.coverage;
+
+    if (state.paintType != VG_PAINT_TYPE_COLOR)
+    {
+        if (state.paintType == VG_PAINT_TYPE_LINEAR_GRADIENT)
+        {
+            // \todo Adjust pixel-center.
+            int x = uniforms.dgdx * span.x0 + uniforms.dgdy * span.y + uniforms.lgc;
+            variants.sx = x;
+        } 
+        else if (state.paintType == VG_PAINT_TYPE_RADIAL_GRADIENT)
+        {
+            RGScalar x = uniforms.rdxdx * (RGScalar)span.x0 + uniforms.rdxdy * (RGScalar)span.y;
+            RGScalar y = uniforms.rdydy * (RGScalar)span.y + uniforms.rdydx * (RGScalar)span.x0;
+
+            variants.rx = x + uniforms.rx0;
+            variants.ry = y + uniforms.ry0;
+        }
+        else
+        {
+            RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN);
+            variants.sx = uniforms.paint_dxdx * span.x0 + uniforms.paint_dxdy * span.y + uniforms.paint_x0;
+            variants.sy = uniforms.paint_dydy * span.y + uniforms.paint_dydx * span.x0 + uniforms.paint_y0;
+        }
+    }
+
+    if (state.hasMasking)
+    {
+        variants.maskPtr = Image::calculateAddress(uniforms.maskPtr, state.maskDesc.bitsPerPixel, span.x0, span.y, uniforms.maskStride);
+    }
+
+    if (state.hasImage)
+    {
+        switch (state.imageGradientType)
+        {
+        case PixelPipe::GRADIENT_TYPE_INTEGER:
+        case PixelPipe::GRADIENT_TYPE_FIXED:
+            variants.iImageX = uniforms.image_ix0 + span.x0 * uniforms.image_idxdx + span.y * uniforms.image_idxdy;
+            variants.iImageY = uniforms.image_iy0 + span.y * uniforms.image_idydy + span.x0 * uniforms.image_idydx;
+            break;
+        default:
+            RI_ASSERT(state.imageGradientType == PixelPipe::GRADIENT_TYPE_FLOAT);
+            variants.fImageX = uniforms.image_fx0 + span.x0 * uniforms.image_fdxdx + span.y * uniforms.image_fdxdy;
+            variants.fImageY = uniforms.image_fy0 + span.y * uniforms.image_fdydy + span.x0 * uniforms.image_fdydx;
+            variants.fImageW = uniforms.image_fw0 + span.x0 * uniforms.image_fdwdx + span.y * uniforms.image_fdwdy;
+            break;
+        }
+    }
+}
+
+void executePixelPipeline(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans)
+{
+    RI_ASSERT(nSpans > 0);
+    for (int i = 0; i < nSpans; i++)
+    {
+        const Span& s = spans[i]; 
+
+        if (s.coverage != Rasterizer::MAX_COVERAGE || !canSolidFill(state))
+        {
+            int n = s.len;
+            RI_ASSERT(n);
+            prepareSpanVariants(state, uniforms, s, variants);
+
+            do {
+                intPixelPipe(state, uniforms, variants);
+            } while (--n);
+        } else
+        {
+            fillSolidSpan(state, uniforms, s.x0, s.y, s.len, uniforms.packedSolidColor);
+        }
+    }
+    
+}
+
+void calculatePPHash(PixelPipeHash& hash, const PixelPipe::SignatureState& derivedState)
+{
+    const RIuint32 blendModeBits = 4;
+    const RIuint32 imageModeBits = 2;
+    const RIuint32 paintTypeBits = 2;
+    const RIuint32 tilingModeBits = 2;
+    const RIuint32 samplerBits = 1;
+    const RIuint32 imageGradientTypeBits = 2;
+    const RIuint32 boolBits = 1;
+    const RIuint32 descBits = 10;
+    const RIuint32 maskOperationBits = 3;
+
+    RIuint32 blendMode = ((RIuint32)derivedState.blendMode) - ((RIuint32)VG_BLEND_SRC);
+    RIuint32 imageMode = ((RIuint32)derivedState.imageMode) - ((RIuint32)VG_DRAW_IMAGE_NORMAL);
+    RIuint32 paintType = ((RIuint32)derivedState.paintType) - ((RIuint32)VG_PAINT_TYPE_COLOR);
+    RIuint32 maskOperation = ((RIuint32)derivedState.maskOperation) - ((RIuint32)VG_CLEAR_MASK);
+    RIuint32 paintTilingMode = ((RIuint32)derivedState.paintTilingMode);
+    RIuint32 paintSampler = ((RIuint32)derivedState.paintSampler);
+    RIuint32 imageSampler = ((RIuint32)derivedState.imageSampler);
+
+    RIuint32 imageGradientType = ((RIuint32)derivedState.imageGradientType);
+
+    RIuint32 dstFormat = (RIuint32)(derivedState.dstDesc.toIndex());
+    RIuint32 maskFormat = (RIuint32)(derivedState.maskDesc.toIndex());
+    RIuint32 imageFormat = (RIuint32)(derivedState.imageDesc.toIndex());
+    RIuint32 patternFormat = (RIuint32)(derivedState.patternDesc.toIndex());
+
+    RIuint32 hasMasking = derivedState.hasMasking ? 1 : 0;
+    RIuint32 hasImage = derivedState.hasImage ? 1 : 0;
+    RIuint32 hasColorTransform = derivedState.hasColorTransform ? 1 : 0;
+    RIuint32 isMaskOperation = derivedState.isRenderToMask ? 1 : 0;
+    RIuint32 fillColorTransparent = derivedState.fillColorTransparent ? 1 : 0;
+    RIuint32 unsafeImageInput = derivedState.unsafeImageInput ? 1 : 0;
+
+    // Modify hashes according to relevant state:
+    int b = 0;
+    b = riInsertBits32(hash.value, sizeof(hash.value), blendMode, blendModeBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), imageMode, imageModeBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), paintType, paintTypeBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), maskOperation, maskOperationBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), paintTilingMode, tilingModeBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), paintSampler, samplerBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), imageSampler, samplerBits, b);
+
+    b = riInsertBits32(hash.value, sizeof(hash.value), imageGradientType, imageGradientTypeBits, b);
+
+    b = riInsertBits32(hash.value, sizeof(hash.value), dstFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), maskFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), imageFormat, descBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), patternFormat, descBits, b);
+
+    b = riInsertBits32(hash.value, sizeof(hash.value), hasMasking, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), hasImage, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), hasColorTransform, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), isMaskOperation, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), fillColorTransparent, boolBits, b);
+    b = riInsertBits32(hash.value, sizeof(hash.value), unsafeImageInput, boolBits, b);
+}
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfDynamicPixelPipe.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,50 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFDYNAMICPIXELPIPE_H
+#define __SFDYNAMICPIXELPIPE_H
+
+#ifndef __RIPIXELPIPE_H
+#   include "riPixelPipe.h"
+#endif
+
+namespace OpenVGRI {
+
+
+struct PixelPipeHash 
+{
+    PixelPipeHash() {value[0] = 0; value[1] = 0;}
+    bool operator==(const PixelPipeHash& rhs) const { return value[0] == rhs.value[0] && value[1] == rhs.value[1]; }
+
+    RIuint32 value[2];
+}; 
+// Interface to compiler?
+void pixelPipelineCall(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans);
+// Interface to rasterizer
+void executePixelPipeline(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans);
+
+void calculatePPHash(PixelPipeHash& hash, const PixelPipe::SignatureState& state);
+
+}
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfEGLInterface.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,470 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#include "SurfaceDescriptor.h"
+#include "BufferContainer.h"
+
+#include "sfEGLInterface.h"
+#include "riContext.h"
+#include "riPath.h"
+#include "vgext.h"
+#include "riImage.h"
+
+namespace 
+    {
+    EGLtoVGInterface g_EGLtoVGInterface;
+    }
+
+IEGLtoVGInterface* getVGInterface(void)
+{    
+    return &g_EGLtoVGInterface;
+}
+
+EGLtoVGInterface::EGLtoVGInterface() :
+    m_egl(NULL)
+{
+    m_contexts.reserve(4);
+}
+
+EGLtoVGInterface::~EGLtoVGInterface()
+{
+    for(int i = 0; i < m_contexts.size(); i++)
+    {
+        RI_ASSERT(m_contexts[i]);
+        RI_DELETE(m_contexts[i]);
+    }
+}
+
+void EGLtoVGInterface::SetEGLInterface( IVGtoEGLInterface* egl )
+{
+    RI_ASSERT(!m_egl);
+    m_egl = egl;
+}
+
+int EGLtoVGInterface::findContext(OpenVGRI::VGContext* contextPtr)
+{
+    return m_contexts.findIndex(contextPtr);
+}
+
+bool EGLtoVGInterface::isValidImage(void* image)
+    {
+    bool ret = false;
+    for(int i = 0; i < m_contexts.size() && !ret; i++)
+        {
+        ret = m_contexts[i]->isValidImage((VGImage)image);
+        }
+    return ret;
+    }
+
+void* EGLtoVGInterface::CreateContext( void* shareContext )
+{
+    if (shareContext)
+    {
+        if (findContext((OpenVGRI::VGContext*)shareContext) < 0)
+            return NULL;
+    }
+
+    OpenVGRI::VGContext* newContext = NULL;
+
+    try 
+    {
+        newContext = RI_NEW(OpenVGRI::VGContext, ((OpenVGRI::VGContext*)shareContext));
+        m_contexts.push_back(newContext);
+    } 
+    catch (std::bad_alloc)
+    {
+        if (newContext) 
+            delete newContext;
+
+        newContext = NULL;
+    }
+
+    return newContext;
+}
+
+bool EGLtoVGInterface::ReleaseContext( void* context )
+{
+    int contextIndex = findContext((OpenVGRI::VGContext*)context);
+
+    if (contextIndex < 0)
+        return false;
+
+    OpenVGRI::VGContext* ctx = (OpenVGRI::VGContext*)context;
+    if( !m_contexts.remove(ctx) )
+        return false;
+    
+    RI_DELETE(ctx);
+
+    return true;
+}
+
+OpenVGRI::Color::Descriptor EGLtoVGInterface::vgDescriptorFromSurfaceDescriptor(const SurfaceDescriptor* sdesc)
+{
+    const CColorDescriptor& scdesc = sdesc->m_colorDescriptor;
+    OpenVGRI::Color::Descriptor vdesc;
+    unsigned int formatBits = 0;
+
+    // VG formats are built favoring the first ones in the enum (RGBA, RGBX, etc.)
+
+    // Padded alpha (RGBX, etc.) must be handled. For example:
+    // if (vdesc.bitsPerPixel < sdesc.bitsPerPixel)
+    //      alphabits = 0, alphashift = 8
+    vdesc.bitsPerPixel = scdesc.m_bpp;
+    vdesc.bytesPerPixel = vdesc.bitsPerPixel >> 3;
+
+    vdesc.alphaBits = scdesc.m_alphaSize;
+    vdesc.alphaShift = sdesc->m_alphaShift;
+    vdesc.redBits = scdesc.m_redSize;
+    vdesc.redShift = sdesc->m_redShift;
+    vdesc.greenBits = scdesc.m_greenSize;
+    vdesc.greenShift = sdesc->m_greenShift;
+    vdesc.blueBits = scdesc.m_blueSize;
+    vdesc.blueShift = sdesc->m_blueShift;
+    vdesc.luminanceBits = scdesc.m_luminanceSize;
+    vdesc.luminanceShift = sdesc->m_luminanceShift;
+    
+    if(scdesc.isLuminance())
+        formatBits |= OpenVGRI::Color::LUMINANCE;    
+    
+    // \note Could be copied if LUMINANCE == LUMINANCE, etc.
+    if (scdesc.isPremultiplied())
+        formatBits |= OpenVGRI::Color::PREMULTIPLIED;
+
+    if (scdesc.isNonlinear())
+        formatBits |= OpenVGRI::Color::NONLINEAR;
+
+    vdesc.internalFormat = (OpenVGRI::Color::InternalFormat)formatBits;
+    // \todo format
+    vdesc.vgFormat = (VGImageFormat)-1; // Not necessarily any VG image format
+    vdesc.shape = vdesc.getShape();
+
+    return vdesc;
+}
+
+bool EGLtoVGInterface::CreateSurface(const SurfaceDescriptor* desc, BufferContainer* buffers, void* image)
+{
+    RI_ASSERT( buffers );
+    OpenVGRI::Color::Descriptor vgColorDescriptor; 
+    OpenVGRI::Image* newImage = NULL;
+    if(image)
+        {
+        if(!isValidImage(image))
+            return false;
+        newImage = (OpenVGRI::Image*)image;
+        vgColorDescriptor = newImage->getDescriptor();
+        }
+    else
+        {
+        vgColorDescriptor = vgDescriptorFromSurfaceDescriptor(desc);
+        }
+    OpenVGRI::Drawable* newDrawable = NULL;
+    
+    //VGImageQuality quality = VG_IMAGE_QUALITY_BETTER;
+
+    int w = desc->m_width;
+    int h = desc->m_height;
+    int stride = OpenVGRI::Image::descriptorToStride(vgColorDescriptor, w);
+    size_t bufSize = h * stride;
+
+    OpenVGRI::RIuint8* dataPtr = NULL;
+
+    try 
+    {
+        int maskBits = 0;
+        if( !newImage )
+            {
+            newImage = RI_NEW(OpenVGRI::Image,(vgColorDescriptor, w, h, VG_IMAGE_QUALITY_BETTER));
+            maskBits = desc->m_maskSize;
+            }
+        else
+            {
+            dataPtr = newImage->getData();
+            maskBits = newImage->getDescriptor().maskBits;
+            }
+        newDrawable = RI_NEW(OpenVGRI::Drawable, (newImage, maskBits));
+        newDrawable->addReference();
+    } 
+    catch (std::bad_alloc)
+    {
+        if (dataPtr)        RI_DELETE_ARRAY(dataPtr);
+        if (newImage)       RI_DELETE(newImage);
+        if (newDrawable)    RI_DELETE(newDrawable);
+
+        return false;
+    }
+    buffers->m_clientSurface = newDrawable;
+    buffers->m_colorBuffer = newDrawable->getColorBuffer()->getImage()->getData();
+    buffers->m_maskBuffer = newDrawable->getMaskBuffer();
+    return true;
+}
+
+bool EGLtoVGInterface::ReleaseSurface(void* surface)
+{
+    RI_ASSERT(surface);
+
+    OpenVGRI::Drawable *drawable = (OpenVGRI::Drawable*)surface;
+
+    if (!drawable->removeReference())
+        RI_DELETE(drawable);
+    
+	return true;
+}
+
+bool EGLtoVGInterface::SetCurrentSurface( void* context, void* surface )
+{
+    OpenVGRI::Drawable* drawable = (OpenVGRI::Drawable*)surface;
+    OpenVGRI::VGContext *ctx = (OpenVGRI::VGContext*)context;
+
+    int i = findContext(ctx);
+
+    if (i < 0)
+        return false;
+
+    ctx->setDefaultDrawable(drawable);
+
+    return true;
+}
+
+bool EGLtoVGInterface::ResizeSurface( void* context, void* surface, int width, int height, BufferContainer* buffers )
+    {
+    OpenVGRI::Drawable* drawable = (OpenVGRI::Drawable*)surface;
+    OpenVGRI::VGContext *ctx = (OpenVGRI::VGContext*)context;
+    int i = findContext(ctx);
+    if(i < 0)
+        return false;
+    
+    try 
+    {
+        drawable->resize( ctx, width, height );
+    } 
+    catch (std::bad_alloc) 
+    {
+        return false;
+    }
+    buffers->m_clientSurface = drawable;
+    buffers->m_colorBuffer = drawable->getColorBuffer()->getImage()->getData();
+    buffers->m_maskBuffer = drawable->getMaskBuffer();
+    return true;
+    }
+
+bool EGLtoVGInterface::IsValidImage( void* image, CColorDescriptor* colorDesc, int* width, int* height )
+{
+    bool ret = isValidImage(image);
+    if(ret)
+        {
+        *width = ((OpenVGRI::Image*)image)->getWidth();
+        *height = ((OpenVGRI::Image*)image)->getHeight();
+        const OpenVGRI::Color::Descriptor& desc = ((OpenVGRI::Image*)image)->getDescriptor();
+        colorDesc->m_bpp = desc.bitsPerPixel;
+        colorDesc->m_redSize = desc.redBits;
+        colorDesc->m_greenSize = desc.greenBits;
+        colorDesc->m_blueSize = desc.blueBits;
+        colorDesc->m_alphaSize = desc.alphaBits;
+        colorDesc->m_luminanceSize = desc.luminanceBits;
+        colorDesc->m_alphaMaskSize = desc.maskBits;
+        colorDesc->m_format = (CColorDescriptor::ColorFormat)desc.internalFormat;
+        }
+
+    return ret;
+}
+
+bool EGLtoVGInterface::IsImageInUse( void* image )
+{
+    bool ret = false;
+    if(image && isValidImage(image))
+        {
+        ret = ((OpenVGRI::Image*)image)->isInUse();
+        }
+    return ret;
+}
+
+void* EGLtoVGInterface::CreateImage()
+{
+    RI_ASSERT(false);
+	return NULL;
+}
+
+bool EGLtoVGInterface::ReleaseImage()
+{
+    RI_ASSERT(false);
+	return false;
+}
+
+void EGLtoVGInterface::Flush()
+{
+    vgFlush();
+}
+
+void EGLtoVGInterface::Finish()
+{
+    vgFinish();
+}
+
+fpVGProc EGLtoVGInterface::GetVGProcAddress( const char *procname )
+{
+    fpVGProc ret = NULL;
+    if(strcmp(procname, "vgePathCoordsSizeInBytes") == 0)
+        {
+        ret = (fpVGProc)vgePathCoordsSizeInBytes;
+        }
+    return ret;
+}
+
+void EGLtoVGInterface::CopyBuffers( void* buffer, int stride, void* surface )
+    {
+    OpenVGRI::Drawable *drawable = (OpenVGRI::Drawable*)surface;
+    int width = drawable->getColorBuffer()->getWidth();
+    int height = drawable->getColorBuffer()->getHeight();
+	// \todo Pixel format.
+    VGImageFormat format = VG_sARGB_8888_PRE;
+    vgReadPixels( buffer, stride, format, 0, 0, width, height );
+    }
+
+void EGLtoVGInterface::UpdateBuffers( void* buffer, int stride, const SurfaceDescriptor* desc )
+    {
+    // \todo format, errors
+    VGImageFormat format = VG_sARGB_8888_PRE;
+    vgWritePixels( buffer, stride, format, 0, 0, desc->m_width, desc->m_height );
+    }
+
+bool EGLtoVGInterface::IsRootImage( void* image )
+    {
+    if( !image ) return false;    
+    if ( vgGetParent( (VGImage)image ) )
+        {
+        // if vgGetParent returns not NULL image it is not parent image
+        // , only child image has parent image, and this should return false
+        return false;
+        }
+    // vgGetParent is NULL and image is parent image
+    return true;
+    }                                                    
+
+void EGLtoVGInterface::GetImageData( void* image, SurfaceDescriptor& desc, void* data )
+    {
+    OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image;
+    if( !image )
+        {
+        return;
+        }
+    desc.m_height = vgimage->getHeight();
+    desc.m_width  = vgimage->getWidth();
+    int bufSize;
+    
+    OpenVGRI::Color::Descriptor colorDesc   = vgimage->getDescriptor();
+	VGImageFormat vgFormat;
+	// Convert some formats into more GL-friendly formats.
+	if( colorDesc.vgFormat == VG_BW_1 )
+		{
+		vgFormat = VG_lL_8;
+		}
+	else if( colorDesc.vgFormat == VG_A_1 || colorDesc.vgFormat == VG_A_4 )
+		{
+		vgFormat = VG_A_8;
+		}
+	else
+		{
+		vgFormat = colorDesc.vgFormat;
+		}
+    desc.m_colorDescriptor.m_format = (CColorDescriptor::ColorFormat)colorDesc.internalFormat;
+    desc.m_alphaShift     = colorDesc.alphaShift;
+    desc.m_blueShift      = colorDesc.blueShift;
+    desc.m_greenShift     = colorDesc.greenShift;
+    desc.m_redShift       = colorDesc.redShift;
+    desc.m_luminanceShift = colorDesc.luminanceShift;
+    desc.m_stride         = vgimage->getStride();
+
+    bufSize = (desc.m_stride * desc.m_height);
+    // Allocate data from memory.
+    data = RI_NEW_ARRAY(OpenVGRI::RIuint8, bufSize);
+    // Get data from VG
+    vgGetImageSubData( (VGImage)vgimage, data, vgimage->getStride(), vgFormat, 0, 0, vgimage->getWidth(), vgimage->getWidth() );
+
+    }
+
+void EGLtoVGInterface::AddRef( void* image )
+    {
+    OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image;
+    if( !image )
+        {
+        return;
+        }
+    vgimage->addReference();
+    }
+
+void EGLtoVGInterface::RemoveRef( void* image )
+    {
+    OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image;
+    if( !image )
+        {
+        return;
+        }
+    vgimage->removeReference();
+    }
+
+/*static*/ IVGtoEGLInterface* EGLtoVGInterface::GetEGLInterface()
+{
+    return g_EGLtoVGInterface.m_egl;
+}
+
+void* OpenVGRI::eglvgGetCurrentVGContext(void)
+{
+    return EGLtoVGInterface::GetEGLInterface()->GetVGContext();
+}
+
+bool OpenVGRI::eglvgIsInUse(void* image)
+{
+    return EGLtoVGInterface::GetEGLInterface()->IsImageInUse(image);
+}
+
+bool OpenVGRI::eglvgLockSurface(bool read, bool write)
+{
+	return EGLtoVGInterface::GetEGLInterface()->LockVGSurface(read, write);
+}
+
+bool OpenVGRI::eglvgUnlockSurface()
+{
+	return EGLtoVGInterface::GetEGLInterface()->UnlockVGSurface();
+}
+
+void OpenVGRI::OSAcquireMutex(void)
+{
+}
+
+void OpenVGRI::OSReleaseMutex(void) 
+{
+}
+
+void OpenVGRI::eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride )
+    {
+    SurfaceDescriptor surfDesc;
+    EGLtoVGInterface::GetEGLInterface()->GetDescForImage( image, surfDesc );
+    desc = EGLtoVGInterface::vgDescriptorFromSurfaceDescriptor( &surfDesc );
+    width = surfDesc.m_width;
+    height = surfDesc.m_height;
+    stride = surfDesc.m_stride;
+    }
+
+void* OpenVGRI::eglvgGetImageData( void* image )
+    {
+    return EGLtoVGInterface::GetEGLInterface()->GetDataForImage( image );
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfEGLInterface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,89 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef _SFEGLINTERFACE_H_
+#define _SFEGLINTERFACE_H_
+
+#include "riImage.h"
+#include "VGInterface.h"
+
+
+// Get pointer to global interface object.
+extern "C" { RI_API_CALL IEGLtoVGInterface* getVGInterface(void); }
+extern "C" { RI_API_CALL VGErrorCode vgPlatsimGetError(void); }
+
+namespace OpenVGRI 
+{
+    void* eglvgGetCurrentVGContext(void);
+    bool  eglvgIsInUse(void* image);
+	bool  eglvgLockSurface(bool read, bool write);
+    bool  eglvgUnlockSurface();
+	void  OSAcquireMutex(void);
+	void  OSReleaseMutex(void);
+    void  eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride );
+    void* eglvgGetImageData( void* image );
+}
+
+// Services from OpenVG to EGL
+class EGLtoVGInterface : public IEGLtoVGInterface
+{
+public:
+    EGLtoVGInterface();
+    ~EGLtoVGInterface();
+
+    void    SetEGLInterface( IVGtoEGLInterface* egl );
+    void*   CreateContext( void* shareContext );
+    bool    ReleaseContext( void* context );
+    bool    CreateSurface( const SurfaceDescriptor* desc, BufferContainer* buffers, void* image );
+    bool    ReleaseSurface(void* surface);
+    bool    SetCurrentSurface( void* context, void* surface );
+    bool    ResizeSurface( void* context, void* surface, int width, int height, BufferContainer* buffers );
+    bool    IsValidImage( void* image, CColorDescriptor* colorDesc, int* width, int* height );
+    bool    IsImageInUse( void* image );
+    void*   CreateImage();
+    bool    ReleaseImage();
+    void    Flush();
+    void    Finish();
+    fpVGProc GetVGProcAddress( const char *procname );
+    void    CopyBuffers( void* buffer, int stride, void* surface );
+    void    UpdateBuffers( void* buffer, int stride, const SurfaceDescriptor* desc );
+    bool    IsRootImage( void* buffer );
+    void    GetImageData( void* image, SurfaceDescriptor& desc, void* data );
+    void    AddRef( void* image );
+    void    RemoveRef( void* image );
+
+    // Methods for local OpenVG-implementation. To be called only from OpenVG internals.
+    static IVGtoEGLInterface* GetEGLInterface();
+    static OpenVGRI::Color::Descriptor vgDescriptorFromSurfaceDescriptor(const SurfaceDescriptor* sdesc); // \todo static
+    
+private:    
+    int     findContext(OpenVGRI::VGContext* contextPtr);
+    bool    isValidImage(void* image);
+
+private:
+    OpenVGRI::Array<OpenVGRI::VGContext*>   m_contexts;
+    IVGtoEGLInterface*                      m_egl;
+
+};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfFunctionCache.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,310 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFFUNCTIONCACHE_H
+#define __SFFUNCTIONCACHE_H
+
+// (LRU) Cache for compiled pixelpipe functions. Never takes ownership of
+// any of the objects.
+// \todo LRU might not be the best strategy or the best strategy might
+// depend on the use-case -> create more of these.
+
+#include "riArray.h"
+
+#if defined(__unix__)
+#   include <pthread.h>
+#else
+#   include <windows.h>
+#endif
+
+#include "llvm/ExecutionEngine/ExecutionEngine.h"
+#include "llvm/Module.h"
+
+namespace llvm {
+    class Function;
+}
+
+namespace OpenVGRI {
+
+template<class HashClass> class FunctionCache 
+{
+private:
+    enum { IMPLEMENTATION_MAX_CACHE_ENTRIES = 1024 };
+    //enum { MAX_GLOBAL_TIME = 10000};
+    enum { MAX_GLOBAL_TIME = RI_UINT32_MAX };
+
+    struct CacheEntry 
+    {
+        CacheEntry() : refCount(1) {}
+        CacheEntry(HashClass aHash, ::llvm::Function* aFunc, ::llvm::GlobalVariable* aConst, RIuint32 theUT) : refCount(1) {hash = aHash; llvmFunction = aFunc; llvmConstant = aConst; ut = theUT;}
+        bool operator==(const CacheEntry& rhs) const { return hash == rhs.hash; }
+        bool operator<(const CacheEntry& rhs) const { return ut < rhs.ut; } // Sort by time of usage.
+
+        HashClass           hash;
+        ::llvm::Function*   llvmFunction;
+        ::llvm::GlobalVariable*   llvmConstant;
+        RIuint32            ut;
+        RIint32             refCount;
+    };
+
+public:
+    typedef CacheEntry* EntryHandle;
+
+public:
+    FunctionCache(int nMaxEntries) :
+        m_time(0)
+    {
+        // Limit so that if the cache is too large, you must optimize the implementation.
+        // Also note that the optimized pixel pipes are most likely small, so it would 
+        // be better to have a fast cache and a lot of entries!
+        // \note A simple optimization is to sort the usage time sort order and remove the last
+        // item in the array (instead of the first).
+        RI_ASSERT(nMaxEntries > 0 && nMaxEntries < IMPLEMENTATION_MAX_CACHE_ENTRIES); 
+        m_nMaxEntries = nMaxEntries;
+        m_entries.reserve(nMaxEntries);
+    }
+
+    ~FunctionCache() 
+    {
+        for (int i = 0; i < m_entries.size(); i++)
+        {
+            clearEntry(m_entries[i]);
+        }
+    }
+    
+    // This info is needed for the module to remove functions and deallocate executable
+    // functions:
+    void setLLVMInterface(::llvm::ExecutionEngine* ee, ::llvm::Module* module)
+    {
+        m_executionEngine = ee;
+        m_module = module;
+    }
+
+    // \todo If we never need the entry index, the locking can be
+    // simplified a lot.
+    // Must lock the cache during this operation!
+    EntryHandle findCachedItemByHash(const HashClass& hash)
+    {
+        acquireMutex();
+        int i = findCachedItemIndexByHash(hash, true);
+        if (i == -1)
+        {
+            releaseMutex();
+            return NULL;
+        }
+        EntryHandle handle = &m_entries[i];
+        releaseMutex();
+        
+        return handle;
+    }
+
+    /**
+     * \brief   Caches a function. Sets the reference count to 1
+     * \return  EntryHandle != NULL on success.
+     * \todo    The cache must be locked during the operation.
+     */
+    EntryHandle cacheFunction(HashClass hash, ::llvm::Function* function, ::llvm::GlobalVariable* constant)
+    {
+        acquireMutex();
+        RI_ASSERT(findCachedItemIndexByHash(hash) == -1);
+
+        if (m_entries.size() == m_nMaxEntries)
+        {
+            if (!removeLRU())
+            {
+                releaseMutex();
+                return NULL;
+            }
+        }
+
+        m_entries.push_back(CacheEntry(hash, function, constant, m_time));
+        
+        RI_ASSERT(m_entries.size() > 0);
+        EntryHandle ret = &m_entries[m_entries.size()-1];
+        incrementGlobalTime();
+
+        releaseMutex();
+        return ret;
+    }
+
+    ::llvm::Function* getFunction(EntryHandle handle)
+    {
+        return handle->llvmFunction;
+    }
+
+    // \note Does not remove the function from cache!
+    void releaseEntry(EntryHandle handle)
+    {
+        RI_ASSERT(handle->refCount > 0);
+        handle->refCount--;
+    }
+
+private:
+    void incrementGlobalTime()
+    {
+        m_time++;
+        if (m_time == MAX_GLOBAL_TIME)
+            rebaseUsageTime();
+    }
+
+    void incrementAccessTime(CacheEntry &entry)
+    {
+        entry.ut = m_time;
+        incrementGlobalTime();
+    }
+
+    int findCachedItemIndexByHash(const HashClass& hash, bool reserve = false)
+    {
+        // \note Could just overload operator== from entry and use the Array.find function.
+        for (int i = 0; i < m_entries.size(); i++)
+        {
+            if (m_entries[i].hash == hash)
+            {
+                if (reserve)
+                {
+                    incrementAccessTime(m_entries[i]);
+                    m_entries[i].refCount++;
+                }
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    void clearEntry(CacheEntry& entry)
+    {
+        m_executionEngine->freeMachineCodeForFunction(entry.llvmFunction);
+        entry.llvmFunction->eraseFromParent();
+        //entry.llvmConstant->eraseFromParent();
+    }
+
+    /**
+     * \return  true if LRU item was successfully removed, false otherwise.
+     * \note    Could try other pipes, but it is unlikely that the cache gets filled
+     *          so soon that the blit for the least recently used blit has not been
+     *          released.
+     * \todo    Implement drop of other cache-entries?
+     */
+    bool removeLRU() 
+    {
+        // \note This is pretty inefficient for many cache size:
+        // After first LRU removal, the cache is almost sorted anyway, so
+        // more efficient solution should be implemented.
+        //
+        m_entries.sort();
+
+        if (m_entries[0].refCount > 0)
+            return false;
+
+        clearEntry(m_entries[0]);
+        m_entries.remove(m_entries[0]);
+
+        return true;
+    }
+
+    void rebaseUsageTime()
+    {
+        RIuint32 i;
+        m_entries.sort();
+        RI_ASSERT(m_entries.size() > 0);
+        for(i = 0; i < (RIuint32)m_entries.size(); i++)
+        {
+            m_entries[i].ut = i;
+        };
+        m_time = i;
+    }
+
+    static void acquireMutex();
+    static void releaseMutex();
+
+private:
+    ::llvm::Module              *m_module;
+    ::llvm::ExecutionEngine     *m_executionEngine;
+
+    RIuint32            m_time;
+    Array <CacheEntry>  m_entries;
+    int                 m_nMaxEntries;
+
+    static bool             s_mutexInitialized;
+#if defined(__unix__)
+    static pthread_mutex_t  s_mutex;
+#else
+    static CRITICAL_SECTION s_mutex;
+#endif
+};
+
+template<class HashClass>
+bool FunctionCache<HashClass>::s_mutexInitialized = false;
+
+#if defined(__unix__)
+template<class HashClass>
+pthread_mutex_t FunctionCache<HashClass>::s_mutex;
+#else
+template<class HashClass>
+CRITICAL_SECTION FunctionCache<HashClass>::s_mutex;
+#endif
+
+template<class HashClass>
+void FunctionCache<HashClass>::acquireMutex()
+{
+    if (!s_mutexInitialized)
+    {
+#if defined(__unix__)
+        int ret;
+        pthread_mutexattr_t attr;
+        ret = pthread_mutexattr_init(&attr);	//initially not locked
+        RI_ASSERT(!ret);	//check that there aren't any errors
+        ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);	//count the number of recursive locks
+        RI_ASSERT(!ret);	//check that there aren't any errors
+        ret = pthread_mutex_init(&s_mutex, &attr);
+        pthread_mutexattr_destroy(&attr);
+        RI_ASSERT(!ret);	//check that there aren't more errors
+#else
+        ::InitializeCriticalSection(&s_mutex);
+#endif
+        s_mutexInitialized = true;
+    }
+#if defined(__unix__)
+    int ret = pthread_mutex_lock(&s_mutex);
+    RI_ASSERT(!ret);
+#else
+    ::EnterCriticalSection(&s_mutex);
+#endif
+}
+
+template<class HashClass>
+void FunctionCache<HashClass>::releaseMutex()
+{
+    RI_ASSERT(s_mutexInitialized);
+#if defined(__unix__)
+    int ret = pthread_mutex_unlock(&s_mutex);
+    RI_ASSERT(!ret);
+#else
+    ::LeaveCriticalSection(&s_mutex);
+#endif
+}
+
+}
+
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfGammaLUT.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,100 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef _SFGAMMARCP_H_
+#define _SFGAMMARCP_H_
+
+#include "riDefs.h"
+
+namespace OpenVGRI {
+static const RIuint8 sc_sRGB_to_lRGB[256] = {
+    0x0,  0x0,  0x0,  0x0,  0x0,  0x0,  0x0,  0x1,  
+    0x1,  0x1,  0x1,  0x1,  0x1,  0x1,  0x1,  0x1,  
+    0x1,  0x1,  0x2,  0x2,  0x2,  0x2,  0x2,  0x2,  
+    0x2,  0x2,  0x3,  0x3,  0x3,  0x3,  0x3,  0x4,  
+    0x4,  0x4,  0x4,  0x4,  0x5,  0x5,  0x5,  0x5,  
+    0x5,  0x6,  0x6,  0x6,  0x6,  0x7,  0x7,  0x7,  
+    0x8,  0x8,  0x8,  0x8,  0x9,  0x9,  0x9,  0xa,  
+    0xa,  0xa,  0xb,  0xb,  0xc,  0xc,  0xc,  0xd,  
+    0xd,  0xe,  0xe,  0xe,  0xf,  0xf,  0x10,  0x10,  
+    0x11,  0x11,  0x12,  0x12,  0x12,  0x13,  0x13,  0x14,  
+    0x15,  0x15,  0x16,  0x16,  0x17,  0x17,  0x18,  0x18,  
+    0x19,  0x1a,  0x1a,  0x1b,  0x1b,  0x1c,  0x1d,  0x1d,  
+    0x1e,  0x1f,  0x1f,  0x20,  0x21,  0x21,  0x22,  0x23,  
+    0x23,  0x24,  0x25,  0x26,  0x26,  0x27,  0x28,  0x29,  
+    0x29,  0x2a,  0x2b,  0x2c,  0x2d,  0x2d,  0x2e,  0x2f,  
+    0x30,  0x31,  0x32,  0x33,  0x33,  0x34,  0x35,  0x36,  
+    0x37,  0x38,  0x39,  0x3a,  0x3b,  0x3c,  0x3d,  0x3e,  
+    0x3f,  0x40,  0x41,  0x42,  0x43,  0x44,  0x45,  0x46,  
+    0x47,  0x48,  0x49,  0x4a,  0x4c,  0x4d,  0x4e,  0x4f,  
+    0x50,  0x51,  0x52,  0x54,  0x55,  0x56,  0x57,  0x58,  
+    0x5a,  0x5b,  0x5c,  0x5d,  0x5f,  0x60,  0x61,  0x63,  
+    0x64,  0x65,  0x67,  0x68,  0x69,  0x6b,  0x6c,  0x6d,  
+    0x6f,  0x70,  0x72,  0x73,  0x74,  0x76,  0x77,  0x79,  
+    0x7a,  0x7c,  0x7d,  0x7f,  0x80,  0x82,  0x83,  0x85,  
+    0x86,  0x88,  0x8a,  0x8b,  0x8d,  0x8e,  0x90,  0x92,  
+    0x93,  0x95,  0x97,  0x98,  0x9a,  0x9c,  0x9d,  0x9f,  
+    0xa1,  0xa3,  0xa4,  0xa6,  0xa8,  0xaa,  0xac,  0xad,  
+    0xaf,  0xb1,  0xb3,  0xb5,  0xb7,  0xb8,  0xba,  0xbc,  
+    0xbe,  0xc0,  0xc2,  0xc4,  0xc6,  0xc8,  0xca,  0xcc,  
+    0xce,  0xd0,  0xd2,  0xd4,  0xd6,  0xd8,  0xda,  0xdc,  
+    0xde,  0xe0,  0xe2,  0xe5,  0xe7,  0xe9,  0xeb,  0xed,  
+    0xef,  0xf2,  0xf4,  0xf6,  0xf8,  0xfa,  0xfd,  0xff,  
+};
+
+static const RIuint8 sc_lRGB_to_sRGB[256] = {
+    0x0,  0xd,  0x16,  0x1c,  0x21,  0x26,  0x2a,  0x2e,  
+    0x31,  0x35,  0x38,  0x3a,  0x3d,  0x40,  0x42,  0x44,  
+    0x47,  0x49,  0x4b,  0x4d,  0x4f,  0x51,  0x53,  0x55,  
+    0x56,  0x58,  0x5a,  0x5b,  0x5d,  0x5f,  0x60,  0x62,  
+    0x63,  0x65,  0x66,  0x67,  0x69,  0x6a,  0x6c,  0x6d,  
+    0x6e,  0x70,  0x71,  0x72,  0x73,  0x74,  0x76,  0x77,  
+    0x78,  0x79,  0x7a,  0x7b,  0x7d,  0x7e,  0x7f,  0x80,  
+    0x81,  0x82,  0x83,  0x84,  0x85,  0x86,  0x87,  0x88,  
+    0x89,  0x8a,  0x8b,  0x8c,  0x8d,  0x8e,  0x8f,  0x90,  
+    0x91,  0x92,  0x93,  0x93,  0x94,  0x95,  0x96,  0x97,  
+    0x98,  0x99,  0x9a,  0x9a,  0x9b,  0x9c,  0x9d,  0x9e,  
+    0x9f,  0x9f,  0xa0,  0xa1,  0xa2,  0xa3,  0xa3,  0xa4,  
+    0xa5,  0xa6,  0xa7,  0xa7,  0xa8,  0xa9,  0xaa,  0xaa,  
+    0xab,  0xac,  0xad,  0xad,  0xae,  0xaf,  0xaf,  0xb0,  
+    0xb1,  0xb2,  0xb2,  0xb3,  0xb4,  0xb4,  0xb5,  0xb6,  
+    0xb6,  0xb7,  0xb8,  0xb8,  0xb9,  0xba,  0xba,  0xbb,  
+    0xbc,  0xbc,  0xbd,  0xbe,  0xbe,  0xbf,  0xc0,  0xc0,  
+    0xc1,  0xc2,  0xc2,  0xc3,  0xc3,  0xc4,  0xc5,  0xc5,  
+    0xc6,  0xc7,  0xc7,  0xc8,  0xc8,  0xc9,  0xca,  0xca,  
+    0xcb,  0xcb,  0xcc,  0xcd,  0xcd,  0xce,  0xce,  0xcf,  
+    0xcf,  0xd0,  0xd1,  0xd1,  0xd2,  0xd2,  0xd3,  0xd3,  
+    0xd4,  0xd5,  0xd5,  0xd6,  0xd6,  0xd7,  0xd7,  0xd8,  
+    0xd8,  0xd9,  0xda,  0xda,  0xdb,  0xdb,  0xdc,  0xdc,  
+    0xdd,  0xdd,  0xde,  0xde,  0xdf,  0xdf,  0xe0,  0xe0,  
+    0xe1,  0xe2,  0xe2,  0xe3,  0xe3,  0xe4,  0xe4,  0xe5,  
+    0xe5,  0xe6,  0xe6,  0xe7,  0xe7,  0xe8,  0xe8,  0xe9,  
+    0xe9,  0xea,  0xea,  0xeb,  0xeb,  0xec,  0xec,  0xed,  
+    0xed,  0xed,  0xee,  0xee,  0xef,  0xef,  0xf0,  0xf0,  
+    0xf1,  0xf1,  0xf2,  0xf2,  0xf3,  0xf3,  0xf4,  0xf4,  
+    0xf5,  0xf5,  0xf6,  0xf6,  0xf6,  0xf7,  0xf7,  0xf8,  
+    0xf8,  0xf9,  0xf9,  0xfa,  0xfa,  0xfb,  0xfb,  0xfb,  
+    0xfc,  0xfc,  0xfd,  0xfd,  0xfe,  0xfe,  0xff,  0xff,  
+};
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/sfMask.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,85 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ */
+
+#ifndef __SFMASK_H
+#define __SFMASK_H
+
+#include "VG/openvg.h"
+
+#ifndef __RIDEFS_H
+#   include "riDefs.h"
+#endif
+
+#ifndef __RIIMAGE_H
+#   include "riImage.h"
+#endif
+
+// Contains implementations of some mask operations that are needed in both the
+// pixel-pipeline and the blitter.
+
+namespace OpenVGRI {
+
+RI_INLINE IntegerColor intMaskOperation(RIuint32 coverage, const IntegerColor& d, VGMaskOperation maskOperation);
+
+RI_INLINE IntegerColor intMaskOperation(RIuint32 coverage, const IntegerColor& d, VGMaskOperation maskOperation)
+{
+    RIuint32 newCoverage;
+    switch (maskOperation)
+    {
+        case VG_SET_MASK:
+            // \note This should work approximately if coverage < 256 always.
+            // See other cases for proper conversions.
+            return IntegerColor(0, 0, 0, coverage); // nop.
+            break;
+        case VG_UNION_MASK:
+        {
+            RIuint32 oldCoverage = d.a;
+            oldCoverage += (oldCoverage >> 7);
+            RIuint32 im = 256 - coverage;
+            RIuint32 ip = 256 - oldCoverage;
+            newCoverage = 256 - ((im * ip) >> 8);
+            break;
+        }
+        case VG_INTERSECT_MASK:
+        {
+            RIuint32 oldCoverage = d.a;
+            oldCoverage += (oldCoverage >> 7);
+            newCoverage = (coverage * oldCoverage) >> 8;
+            break;
+        }
+        default:
+        {
+            RI_ASSERT(maskOperation == VG_SUBTRACT_MASK);
+            RIuint32 im = 256 - coverage;
+            RIuint32 oldCoverage = d.a;
+            oldCoverage += (oldCoverage >> 7);
+            newCoverage = (oldCoverage * im) >> 8;
+            break;
+        }
+    }
+    return IntegerColor(0, 0, 0, newCoverage - (newCoverage >> 8));
+}
+
+}
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/hostopenvg/src/src/win32/riEGLOS.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,382 @@
+/*------------------------------------------------------------------------
+ *
+ * EGL 1.3
+ * -------
+ *
+ * Copyright (c) 2007 The Khronos Group Inc.
+ * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ *//**
+ * \file
+ * \brief	Simple implementation of EGL 1.3
+ * \note	caveats:
+			- always renders into the backbuffer and blits it to window (no single buffered rendering)
+			- no native Windows or Mac OS X pixmap support
+			- no power management events
+			- no support for swap interval
+ * \todo	what happens in egl functions when eglTerminate has been called but the context and surface are still in use?
+ * \todo	OSDeinitMutex should be called in case getEGL fails.
+ * \todo	clarify getThread and getCurrentThread distinction.
+ *//*-------------------------------------------------------------------*/
+
+#include "EGL/egl.h"
+#include "openvg.h"
+#include "riArray.h"
+#include "riMath.h"
+#include "riContext.h"
+#include "riImage.h"
+
+namespace OpenVGRI
+{
+
+#include <windows.h>
+
+void* OSGetCurrentThreadID(void)
+{
+	return (void*)GetCurrentThreadId();	//TODO this is not safe
+}
+
+static HANDLE mutex = NULL;
+static int mutexRefCount = 0;
+//acquired mutex cannot be deinited.
+void OSDeinitMutex(void)
+{
+	RI_ASSERT(mutex);
+	RI_ASSERT(mutexRefCount == 0);
+	BOOL ret = CloseHandle(mutex);
+	RI_ASSERT(ret);
+	RI_UNREF(ret);
+}
+void OSAcquireMutex(void)
+{
+	if(!mutex)
+    {
+        mutex = CreateMutex(NULL, FALSE, NULL);	//initially not locked
+        mutexRefCount = 0;
+    }
+	RI_ASSERT(mutex);
+	DWORD ret = WaitForSingleObject(mutex, INFINITE);
+	RI_ASSERT(ret != WAIT_FAILED);
+	RI_UNREF(ret);
+	mutexRefCount++;
+}
+void OSReleaseMutex(void)
+{
+	RI_ASSERT(mutex);
+	mutexRefCount--;
+	RI_ASSERT(mutexRefCount >= 0);
+	BOOL ret = ReleaseMutex(mutex);
+	RI_ASSERT(ret);
+	RI_UNREF(ret);
+}
+
+static bool isBigEndian()
+{
+	static const RIuint32 v = 0x12345678u;
+	const RIuint8* p = (const RIuint8*)&v;
+	RI_ASSERT (*p == (RIuint8)0x12u || *p == (RIuint8)0x78u);
+	return (*p == (RIuint8)(0x12)) ? true : false;
+}
+
+
+#ifdef RI_USE_GLUT
+#	include <GL/gl.h>
+#	define GLUT_DISABLE_ATEXIT_HACK
+#	include "glut.h"
+
+struct OSWindowContext
+{
+    int                 window;
+    unsigned int*       tmp;
+    int                 tmpWidth;
+    int                 tmpHeight;
+};
+
+void* OSCreateWindowContext(EGLNativeWindowType window)
+{
+    try
+    {
+        OSWindowContext* ctx = RI_NEW(OSWindowContext, ());
+        ctx->window = (int)window;
+        ctx->tmp = NULL;
+        ctx->tmpWidth = 0;
+        ctx->tmpHeight = 0;
+        return ctx;
+    }
+	catch(std::bad_alloc)
+	{
+		return NULL;
+	}
+}
+
+void OSDestroyWindowContext(void* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        RI_DELETE_ARRAY(ctx->tmp);
+        RI_DELETE(ctx);
+    }
+}
+
+bool OSIsWindow(const void* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+		//TODO implement
+        return true;
+    }
+    return false;
+}
+
+void OSGetWindowSize(const void* context, int& width, int& height)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        int currWin = glutGetWindow();
+        glutSetWindow(ctx->window);
+        width = glutGet(GLUT_WINDOW_WIDTH);
+        height = glutGet(GLUT_WINDOW_HEIGHT);
+        glutSetWindow(currWin);
+    }
+    else
+    {
+        width = 0;
+        height = 0;
+    }
+}
+
+void OSBlitToWindow(void* context, const Drawable* drawable)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        int w = drawable->getWidth();
+        int h = drawable->getHeight();
+
+        int currWin = glutGetWindow();
+        glutSetWindow(ctx->window);
+
+        if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h)
+        {
+            RI_DELETE_ARRAY(ctx->tmp);
+            ctx->tmp = NULL;
+            try
+            {
+                ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h);	//throws bad_alloc
+                ctx->tmpWidth = w;
+                ctx->tmpHeight = h;
+            }
+            catch(std::bad_alloc)
+            {
+                //do nothing
+            }
+        }
+
+        if(ctx->tmp)
+        {
+            glViewport(0, 0, w, h);
+            glDisable(GL_DEPTH_TEST);
+            glMatrixMode(GL_PROJECTION);
+            glLoadIdentity();
+            glMatrixMode(GL_MODELVIEW);
+            glLoadIdentity();
+            //NOTE: we assume here that the display is always in sRGB color space
+            VGImageFormat f = VG_sXBGR_8888;
+            if(isBigEndian())
+                f = VG_sRGBX_8888;
+            vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h);
+            glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp);
+        }
+
+        glutSwapBuffers();	//shows the OpenGL frame buffer
+        glutSetWindow(currWin);		//restore the current window
+    }
+}
+
+EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id)
+{
+    return (EGLDisplay)display_id;  //just casting to (EGLDisplay) should be enough to make a unique identifier out of this
+}
+
+#else
+//Windows native
+#ifndef _WINDOWS_
+#	define _WIN32_WINNT 0x0400
+#	define WIN32_LEAN_AND_MEAN
+#	include <windows.h>
+#endif
+
+struct OSWindowContext
+{
+    HWND                window;
+	HDC					bufDC;
+	HBITMAP				bufDIB;
+    unsigned int*       tmp;
+    int                 tmpWidth;
+    int                 tmpHeight;
+};
+
+OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window)
+{
+    OSWindowContext* ctx = NULL;
+    try
+    {
+        ctx = RI_NEW(OSWindowContext, ());
+    }
+	catch(std::bad_alloc)
+	{
+		return NULL;
+	}
+
+    ctx->window = (HWND)window;
+    HDC winDC = GetDC(ctx->window);
+    ctx->bufDC = CreateCompatibleDC(winDC);
+    ReleaseDC(ctx->window, winDC);
+    if(!ctx->bufDC)
+    {
+        RI_DELETE(ctx);
+        return NULL;
+    }
+
+    ctx->bufDIB = NULL;
+    ctx->tmp = NULL;
+    ctx->tmpWidth = 0;
+    ctx->tmpHeight = 0;
+    return ctx;
+}
+
+void OSDestroyWindowContext(OSWindowContext* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        if(ctx->bufDC)
+        {
+            SelectObject(ctx->bufDC, NULL);
+            DeleteDC(ctx->bufDC);
+        }
+        if(ctx->bufDIB)
+            DeleteObject(ctx->bufDIB);
+        RI_DELETE(ctx);
+    }
+}
+
+bool OSIsWindow(const OSWindowContext* context)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+		if(IsWindow(ctx->window))
+			return true;
+    }
+    return false;
+}
+
+void OSGetWindowSize(const OSWindowContext* context, int& width, int& height)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+		RECT rect;
+		GetClientRect(ctx->window, &rect);
+		width = rect.right - rect.left;
+		height = rect.bottom - rect.top;
+    }
+    else
+    {
+        width = 0;
+        height = 0;
+    }
+}
+
+void OSBlitToWindow(OSWindowContext* context, const Drawable* drawable)
+{
+    OSWindowContext* ctx = (OSWindowContext*)context;
+    if(ctx)
+    {
+        int w = drawable->getWidth();
+        int h = drawable->getHeight();
+
+        if(!ctx->tmp || !ctx->bufDIB || ctx->tmpWidth != w || ctx->tmpHeight != h)
+        {
+            if(ctx->bufDIB)
+                DeleteObject(ctx->bufDIB);
+            ctx->tmp = NULL;
+            ctx->bufDIB = NULL;
+
+            ctx->tmpWidth = w;
+            ctx->tmpHeight = h;
+
+            struct
+            {
+                BITMAPINFOHEADER	header;
+                DWORD				rMask;
+                DWORD				gMask;
+                DWORD				bMask;
+            } bmi;
+            bmi.header.biSize			= sizeof(BITMAPINFOHEADER);
+            bmi.header.biWidth			= w;
+            bmi.header.biHeight			= h;
+            bmi.header.biPlanes			= 1;
+            bmi.header.biBitCount		= (WORD)32;
+            bmi.header.biCompression	= BI_BITFIELDS;
+            bmi.rMask = 0x000000ff;
+            bmi.gMask = 0x0000ff00;
+            bmi.bMask = 0x00ff0000;
+            ctx->bufDIB = CreateDIBSection(ctx->bufDC, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&ctx->tmp, NULL, 0);
+            if(!ctx->bufDIB)
+            {
+                ctx->tmp = NULL;
+                return;
+            }
+        }
+
+        if(ctx->tmp)
+        {
+            //NOTE: we assume here that the display is always in sRGB color space
+			GdiFlush();
+            VGImageFormat f = VG_sABGR_8888_PRE;
+            if(isBigEndian())
+                f = VG_sRGBA_8888_PRE;
+            vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h);
+
+            SelectObject(ctx->bufDC, ctx->bufDIB);
+            HDC winDC = GetDC(ctx->window);
+            BitBlt(winDC, 0, 0, w, h, ctx->bufDC, 0, 0, SRCCOPY);
+            ReleaseDC(ctx->window, winDC);
+            SelectObject(ctx->bufDC, NULL);
+        }
+    }
+}
+
+EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id)
+{
+    RI_UNREF(display_id);
+    return (EGLDisplay)1;    //support only a single display
+}
+
+#endif
+
+}   //namespace OpenVGRI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/BufferContainer.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,44 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _BUFFERCONTAINER_H_
+#define _BUFFERCONTAINER_H_
+
+struct BufferContainer
+{
+    void*   m_clientSurface;
+    void*   m_colorBuffer;
+    void*   m_stencilBuffer;
+    void*   m_depthBuffer;
+    void*   m_sampleBuffer;
+    void*   m_maskBuffer;
+};
+
+#endif //_BUFFERCONTAINER_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/ColorDescriptor.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,109 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _COLORDESCRIPTOR_H_
+#define _COLORDESCRIPTOR_H_
+
+class CColorDescriptor
+{
+public:
+
+    enum ColorFormat {
+        lRGBA			= 0,
+        sRGBA			= 1,
+        lRGBA_PRE		= 2,
+        sRGBA_PRE		= 3,
+        lLA				= 4,
+        sLA				= 5,
+        lLA_PRE			= 6,
+        sLA_PRE			= 7
+    };
+
+    enum ColorFormatBits
+    {
+        NONLINEAR		= (1<<0),
+        PREMULTIPLIED	= (1<<1),
+        LUMINANCE		= (1<<2)
+    };
+
+    CColorDescriptor(void) {
+        m_bpp           = 0;
+        m_redSize       = 0;
+        m_greenSize     = 0;
+        m_blueSize      = 0;
+        m_luminanceSize = 0;
+        m_alphaSize     = 0;
+        m_alphaMaskSize = 0;
+        m_format        = lRGBA_PRE;
+        }
+
+	CColorDescriptor(int red, int green, int blue, 
+                     int luminance, bool nonlinear, int alpha, bool premultiplied,
+                     int alphaMask, int bpp);
+    ~CColorDescriptor(void) {};
+
+    void Set( int red, int green, int blue, int luminance, bool nonlinear, int alpha,
+        bool premultiplied, int alphaMask, int bpp);
+
+    void SetAttribute( int attribute, int value );
+    int GetAttribute( int attribute ) const;
+    inline int Bpp() const { return m_bpp; }
+    inline int RedSize() const { return m_redSize; }
+    inline int GreenSize() const { return m_greenSize; }
+    inline int BlueSize() const { return m_blueSize; }
+    inline int LuminanceSize() const { return m_luminanceSize; }
+    inline int AlphaSize() const { return m_alphaSize; }
+    inline int AlphaMaskSize() const { return m_alphaMaskSize; }
+    inline bool isLuminance() const { return (m_format & LUMINANCE) != 0; }
+    inline bool isNonlinear() const { return (m_format & NONLINEAR) != 0; }
+    inline bool isPremultiplied() const { return (m_format & PREMULTIPLIED) != 0; }
+    ColorFormat Format() const { return m_format; }
+
+    int GetSurfaceType() const;
+    void SetSurfaceType(int surfaceType);
+    void SetSurfaceType(int colorSpace, int alphaFormat);
+    void SetColorBufferType( int colorBufferType );
+
+    CColorDescriptor& operator=( const CColorDescriptor& rhs );
+    bool operator==( const CColorDescriptor& rhs ) const;
+    bool operator!=( const CColorDescriptor& rhs ) const;
+    bool MatchBitDepth( const CColorDescriptor& desc ) const;
+
+public:
+    int  m_bpp;            /* Bits per pixel */
+	int  m_redSize;        /* EGL_RED_SIZE */
+    int  m_greenSize;      /* EGL_GREEN_SIZE */
+    int  m_blueSize;       /* EGL_BLUE_SIZE */
+    int  m_luminanceSize;  /* EGL_LUMINANCE_SIZE */
+    int  m_alphaSize;      /* EGL_ALPHA_SIZE */
+    int  m_alphaMaskSize;  /* EGL_ALPHA_MASK_SIZE */
+    ColorFormat  m_format; /* Color format */
+};
+#endif //_COLORDESCRIPTOR_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/EGL/egl.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,329 @@
+/* -*- mode: c; tab-width: 8; -*- */
+/* vi: set sw=4 ts=8: */
+/* Reference version of egl.h for EGL 1.4.
+ * $Revision: 9356 $ on $Date: 2009-10-21 02:52:25 -0700 (Wed, 21 Oct 2009) $
+ */
+
+/*
+** Copyright (c) 2007-2009 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.
+*/
+
+#ifndef __egl_h_
+#define __egl_h_
+
+/* All platform-dependent types and macro boilerplate (such as EGLAPI
+ * and EGLAPIENTRY) should go in eglplatform.h.
+ */
+#include <EGL/eglplatform.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* EGL Types */
+/* EGLint is defined in eglplatform.h */
+typedef unsigned int EGLBoolean;
+typedef unsigned int EGLenum;
+typedef void *EGLConfig;
+typedef void *EGLContext;
+typedef void *EGLDisplay;
+typedef void *EGLSurface;
+typedef void *EGLClientBuffer;
+
+/* EGL Versioning */
+#define EGL_VERSION_1_0			1
+#define EGL_VERSION_1_1			1
+#define EGL_VERSION_1_2			1
+#define EGL_VERSION_1_3			1
+#define EGL_VERSION_1_4			1
+
+/* EGL Enumerants. Bitmasks and other exceptional cases aside, most
+ * enums are assigned unique values starting at 0x3000.
+ */
+
+/* EGL aliases */
+#define EGL_FALSE			0
+#define EGL_TRUE			1
+
+/* Out-of-band handle values */
+#define EGL_DEFAULT_DISPLAY		((EGLNativeDisplayType)0)
+#define EGL_NO_CONTEXT			((EGLContext)0)
+#define EGL_NO_DISPLAY			((EGLDisplay)0)
+#define EGL_NO_SURFACE			((EGLSurface)0)
+
+/* Out-of-band attribute value */
+#define EGL_DONT_CARE			((EGLint)-1)
+
+/* Errors / GetError return values */
+#define EGL_SUCCESS			0x3000
+#define EGL_NOT_INITIALIZED		0x3001
+#define EGL_BAD_ACCESS			0x3002
+#define EGL_BAD_ALLOC			0x3003
+#define EGL_BAD_ATTRIBUTE		0x3004
+#define EGL_BAD_CONFIG			0x3005
+#define EGL_BAD_CONTEXT			0x3006
+#define EGL_BAD_CURRENT_SURFACE		0x3007
+#define EGL_BAD_DISPLAY			0x3008
+#define EGL_BAD_MATCH			0x3009
+#define EGL_BAD_NATIVE_PIXMAP		0x300A
+#define EGL_BAD_NATIVE_WINDOW		0x300B
+#define EGL_BAD_PARAMETER		0x300C
+#define EGL_BAD_SURFACE			0x300D
+#define EGL_CONTEXT_LOST		0x300E	/* EGL 1.1 - IMG_power_management */
+
+/* Reserved 0x300F-0x301F for additional errors */
+
+/* Config attributes */
+#define EGL_BUFFER_SIZE			0x3020
+#define EGL_ALPHA_SIZE			0x3021
+#define EGL_BLUE_SIZE			0x3022
+#define EGL_GREEN_SIZE			0x3023
+#define EGL_RED_SIZE			0x3024
+#define EGL_DEPTH_SIZE			0x3025
+#define EGL_STENCIL_SIZE		0x3026
+#define EGL_CONFIG_CAVEAT		0x3027
+#define EGL_CONFIG_ID			0x3028
+#define EGL_LEVEL			0x3029
+#define EGL_MAX_PBUFFER_HEIGHT		0x302A
+#define EGL_MAX_PBUFFER_PIXELS		0x302B
+#define EGL_MAX_PBUFFER_WIDTH		0x302C
+#define EGL_NATIVE_RENDERABLE		0x302D
+#define EGL_NATIVE_VISUAL_ID		0x302E
+#define EGL_NATIVE_VISUAL_TYPE		0x302F
+#define EGL_SAMPLES			0x3031
+#define EGL_SAMPLE_BUFFERS		0x3032
+#define EGL_SURFACE_TYPE		0x3033
+#define EGL_TRANSPARENT_TYPE		0x3034
+#define EGL_TRANSPARENT_BLUE_VALUE	0x3035
+#define EGL_TRANSPARENT_GREEN_VALUE	0x3036
+#define EGL_TRANSPARENT_RED_VALUE	0x3037
+#define EGL_NONE			0x3038	/* Attrib list terminator */
+#define EGL_BIND_TO_TEXTURE_RGB		0x3039
+#define EGL_BIND_TO_TEXTURE_RGBA	0x303A
+#define EGL_MIN_SWAP_INTERVAL		0x303B
+#define EGL_MAX_SWAP_INTERVAL		0x303C
+#define EGL_LUMINANCE_SIZE		0x303D
+#define EGL_ALPHA_MASK_SIZE		0x303E
+#define EGL_COLOR_BUFFER_TYPE		0x303F
+#define EGL_RENDERABLE_TYPE		0x3040
+#define EGL_MATCH_NATIVE_PIXMAP		0x3041	/* Pseudo-attribute (not queryable) */
+#define EGL_CONFORMANT			0x3042
+
+/* Reserved 0x3041-0x304F for additional config attributes */
+
+/* Config attribute values */
+#define EGL_SLOW_CONFIG			0x3050	/* EGL_CONFIG_CAVEAT value */
+#define EGL_NON_CONFORMANT_CONFIG	0x3051	/* EGL_CONFIG_CAVEAT value */
+#define EGL_TRANSPARENT_RGB		0x3052	/* EGL_TRANSPARENT_TYPE value */
+#define EGL_RGB_BUFFER			0x308E	/* EGL_COLOR_BUFFER_TYPE value */
+#define EGL_LUMINANCE_BUFFER		0x308F	/* EGL_COLOR_BUFFER_TYPE value */
+
+/* More config attribute values, for EGL_TEXTURE_FORMAT */
+#define EGL_NO_TEXTURE			0x305C
+#define EGL_TEXTURE_RGB			0x305D
+#define EGL_TEXTURE_RGBA		0x305E
+#define EGL_TEXTURE_2D			0x305F
+
+/* Config attribute mask bits */
+#define EGL_PBUFFER_BIT			0x0001	/* EGL_SURFACE_TYPE mask bits */
+#define EGL_PIXMAP_BIT			0x0002	/* EGL_SURFACE_TYPE mask bits */
+#define EGL_WINDOW_BIT			0x0004	/* EGL_SURFACE_TYPE mask bits */
+#define EGL_VG_COLORSPACE_LINEAR_BIT	0x0020	/* EGL_SURFACE_TYPE mask bits */
+#define EGL_VG_ALPHA_FORMAT_PRE_BIT	0x0040	/* EGL_SURFACE_TYPE mask bits */
+#define EGL_MULTISAMPLE_RESOLVE_BOX_BIT 0x0200	/* EGL_SURFACE_TYPE mask bits */
+#define EGL_SWAP_BEHAVIOR_PRESERVED_BIT 0x0400	/* EGL_SURFACE_TYPE mask bits */
+
+#define EGL_OPENGL_ES_BIT		0x0001	/* EGL_RENDERABLE_TYPE mask bits */
+#define EGL_OPENVG_BIT			0x0002	/* EGL_RENDERABLE_TYPE mask bits */
+#define EGL_OPENGL_ES2_BIT		0x0004	/* EGL_RENDERABLE_TYPE mask bits */
+#define EGL_OPENGL_BIT			0x0008	/* EGL_RENDERABLE_TYPE mask bits */
+
+/* QueryString targets */
+#define EGL_VENDOR			0x3053
+#define EGL_VERSION			0x3054
+#define EGL_EXTENSIONS			0x3055
+#define EGL_CLIENT_APIS			0x308D
+
+/* QuerySurface / SurfaceAttrib / CreatePbufferSurface targets */
+#define EGL_HEIGHT			0x3056
+#define EGL_WIDTH			0x3057
+#define EGL_LARGEST_PBUFFER		0x3058
+#define EGL_TEXTURE_FORMAT		0x3080
+#define EGL_TEXTURE_TARGET		0x3081
+#define EGL_MIPMAP_TEXTURE		0x3082
+#define EGL_MIPMAP_LEVEL		0x3083
+#define EGL_RENDER_BUFFER		0x3086
+#define EGL_VG_COLORSPACE		0x3087
+#define EGL_VG_ALPHA_FORMAT		0x3088
+#define EGL_HORIZONTAL_RESOLUTION	0x3090
+#define EGL_VERTICAL_RESOLUTION		0x3091
+#define EGL_PIXEL_ASPECT_RATIO		0x3092
+#define EGL_SWAP_BEHAVIOR		0x3093
+#define EGL_MULTISAMPLE_RESOLVE		0x3099
+
+/* EGL_RENDER_BUFFER values / BindTexImage / ReleaseTexImage buffer targets */
+#define EGL_BACK_BUFFER			0x3084
+#define EGL_SINGLE_BUFFER		0x3085
+
+/* OpenVG color spaces */
+#define EGL_VG_COLORSPACE_sRGB		0x3089	/* EGL_VG_COLORSPACE value */
+#define EGL_VG_COLORSPACE_LINEAR	0x308A	/* EGL_VG_COLORSPACE value */
+
+/* OpenVG alpha formats */
+#define EGL_VG_ALPHA_FORMAT_NONPRE	0x308B	/* EGL_ALPHA_FORMAT value */
+#define EGL_VG_ALPHA_FORMAT_PRE		0x308C	/* EGL_ALPHA_FORMAT value */
+
+/* Constant scale factor by which fractional display resolutions &
+ * aspect ratio are scaled when queried as integer values.
+ */
+#define EGL_DISPLAY_SCALING		10000
+
+/* Unknown display resolution/aspect ratio */
+#define EGL_UNKNOWN			((EGLint)-1)
+
+/* Back buffer swap behaviors */
+#define EGL_BUFFER_PRESERVED		0x3094	/* EGL_SWAP_BEHAVIOR value */
+#define EGL_BUFFER_DESTROYED		0x3095	/* EGL_SWAP_BEHAVIOR value */
+
+/* CreatePbufferFromClientBuffer buffer types */
+#define EGL_OPENVG_IMAGE		0x3096
+
+/* QueryContext targets */
+#define EGL_CONTEXT_CLIENT_TYPE		0x3097
+
+/* CreateContext attributes */
+#define EGL_CONTEXT_CLIENT_VERSION	0x3098
+
+/* Multisample resolution behaviors */
+#define EGL_MULTISAMPLE_RESOLVE_DEFAULT 0x309A	/* EGL_MULTISAMPLE_RESOLVE value */
+#define EGL_MULTISAMPLE_RESOLVE_BOX	0x309B	/* EGL_MULTISAMPLE_RESOLVE value */
+
+/* BindAPI/QueryAPI targets */
+#define EGL_OPENGL_ES_API		0x30A0
+#define EGL_OPENVG_API			0x30A1
+#define EGL_OPENGL_API			0x30A2
+
+/* GetCurrentSurface targets */
+#define EGL_DRAW			0x3059
+#define EGL_READ			0x305A
+
+/* WaitNative engines */
+#define EGL_CORE_NATIVE_ENGINE		0x305B
+
+/* EGL 1.2 tokens renamed for consistency in EGL 1.3 */
+#define EGL_COLORSPACE			EGL_VG_COLORSPACE
+#define EGL_ALPHA_FORMAT		EGL_VG_ALPHA_FORMAT
+#define EGL_COLORSPACE_sRGB		EGL_VG_COLORSPACE_sRGB
+#define EGL_COLORSPACE_LINEAR		EGL_VG_COLORSPACE_LINEAR
+#define EGL_ALPHA_FORMAT_NONPRE		EGL_VG_ALPHA_FORMAT_NONPRE
+#define EGL_ALPHA_FORMAT_PRE		EGL_VG_ALPHA_FORMAT_PRE
+
+/* EGL extensions must request enum blocks from the Khronos
+ * API Registrar, who maintains the enumerant registry. Submit
+ * a bug in Khronos Bugzilla against task "Registry".
+ */
+
+
+
+/* EGL Functions */
+
+EGLAPI EGLint EGLAPIENTRY eglGetError(void);
+
+EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id);
+EGLAPI EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor);
+EGLAPI EGLBoolean EGLAPIENTRY eglTerminate(EGLDisplay dpy);
+
+EGLAPI const char * EGLAPIENTRY eglQueryString(EGLDisplay dpy, EGLint name);
+
+EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs(EGLDisplay dpy, EGLConfig *configs,
+			 EGLint config_size, EGLint *num_config);
+EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list,
+			   EGLConfig *configs, EGLint config_size,
+			   EGLint *num_config);
+EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib(EGLDisplay dpy, EGLConfig config,
+			      EGLint attribute, EGLint *value);
+
+EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config,
+				  EGLNativeWindowType win,
+				  const EGLint *attrib_list);
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config,
+				   const EGLint *attrib_list);
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config,
+				  EGLNativePixmapType pixmap,
+				  const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface(EGLDisplay dpy, EGLSurface surface);
+EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface(EGLDisplay dpy, EGLSurface surface,
+			   EGLint attribute, EGLint *value);
+
+EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI(EGLenum api);
+EGLAPI EGLenum EGLAPIENTRY eglQueryAPI(void);
+
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient(void);
+
+EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread(void);
+
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer(
+	      EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer,
+	      EGLConfig config, const EGLint *attrib_list);
+
+EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface,
+			    EGLint attribute, EGLint value);
+EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer);
+EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage(EGLDisplay dpy, EGLSurface surface, EGLint buffer);
+
+
+EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval(EGLDisplay dpy, EGLint interval);
+
+
+EGLAPI EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig config,
+			    EGLContext share_context,
+			    const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext(EGLDisplay dpy, EGLContext ctx);
+EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw,
+			  EGLSurface read, EGLContext ctx);
+
+EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext(void);
+EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface(EGLint readdraw);
+EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay(void);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext(EGLDisplay dpy, EGLContext ctx,
+			   EGLint attribute, EGLint *value);
+
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL(void);
+EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative(EGLint engine);
+EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface surface);
+EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy, EGLSurface surface,
+			  EGLNativePixmapType target);
+
+/* This is a generic function pointer type, whose name indicates it must
+ * be cast to the proper type *and calling convention* before use.
+ */
+typedef void (*__eglMustCastToProperFunctionPointerType)(void);
+
+/* Now, define eglGetProcAddress using the generic function ptr. type */
+EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY
+       eglGetProcAddress(const char *procname);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __egl_h_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/EGL/eglext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,233 @@
+#ifndef __eglext_h_
+#define __eglext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2007-2009 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.
+*/
+
+#include <EGL/eglplatform.h>
+
+/*************************************************************/
+
+/* Header file version number */
+/* Current version at http://www.khronos.org/registry/egl/ */
+/* $Revision: 10185 $ on $Date: 2010-01-22 11:38:01 -0800 (Fri, 22 Jan 2010) $ */
+#define EGL_EGLEXT_VERSION 5
+
+#ifndef EGL_KHR_config_attribs
+#define EGL_KHR_config_attribs 1
+#define EGL_CONFORMANT_KHR			0x3042	/* EGLConfig attribute */
+#define EGL_VG_COLORSPACE_LINEAR_BIT_KHR	0x0020	/* EGL_SURFACE_TYPE bitfield */
+#define EGL_VG_ALPHA_FORMAT_PRE_BIT_KHR		0x0040	/* EGL_SURFACE_TYPE bitfield */
+#endif
+
+#ifndef EGL_KHR_lock_surface
+#define EGL_KHR_lock_surface 1
+#define EGL_READ_SURFACE_BIT_KHR		0x0001	/* EGL_LOCK_USAGE_HINT_KHR bitfield */
+#define EGL_WRITE_SURFACE_BIT_KHR		0x0002	/* EGL_LOCK_USAGE_HINT_KHR bitfield */
+#define EGL_LOCK_SURFACE_BIT_KHR		0x0080	/* EGL_SURFACE_TYPE bitfield */
+#define EGL_OPTIMAL_FORMAT_BIT_KHR		0x0100	/* EGL_SURFACE_TYPE bitfield */
+#define EGL_MATCH_FORMAT_KHR			0x3043	/* EGLConfig attribute */
+#define EGL_FORMAT_RGB_565_EXACT_KHR		0x30C0	/* EGL_MATCH_FORMAT_KHR value */
+#define EGL_FORMAT_RGB_565_KHR			0x30C1	/* EGL_MATCH_FORMAT_KHR value */
+#define EGL_FORMAT_RGBA_8888_EXACT_KHR		0x30C2	/* EGL_MATCH_FORMAT_KHR value */
+#define EGL_FORMAT_RGBA_8888_KHR		0x30C3	/* EGL_MATCH_FORMAT_KHR value */
+#define EGL_MAP_PRESERVE_PIXELS_KHR		0x30C4	/* eglLockSurfaceKHR attribute */
+#define EGL_LOCK_USAGE_HINT_KHR			0x30C5	/* eglLockSurfaceKHR attribute */
+#define EGL_BITMAP_POINTER_KHR			0x30C6	/* eglQuerySurface attribute */
+#define EGL_BITMAP_PITCH_KHR			0x30C7	/* eglQuerySurface attribute */
+#define EGL_BITMAP_ORIGIN_KHR			0x30C8	/* eglQuerySurface attribute */
+#define EGL_BITMAP_PIXEL_RED_OFFSET_KHR		0x30C9	/* eglQuerySurface attribute */
+#define EGL_BITMAP_PIXEL_GREEN_OFFSET_KHR	0x30CA	/* eglQuerySurface attribute */
+#define EGL_BITMAP_PIXEL_BLUE_OFFSET_KHR	0x30CB	/* eglQuerySurface attribute */
+#define EGL_BITMAP_PIXEL_ALPHA_OFFSET_KHR	0x30CC	/* eglQuerySurface attribute */
+#define EGL_BITMAP_PIXEL_LUMINANCE_OFFSET_KHR	0x30CD	/* eglQuerySurface attribute */
+#define EGL_LOWER_LEFT_KHR			0x30CE	/* EGL_BITMAP_ORIGIN_KHR value */
+#define EGL_UPPER_LEFT_KHR			0x30CF	/* EGL_BITMAP_ORIGIN_KHR value */
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglLockSurfaceKHR (EGLDisplay display, EGLSurface surface, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglUnlockSurfaceKHR (EGLDisplay display, EGLSurface surface);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLLOCKSURFACEKHRPROC) (EGLDisplay display, EGLSurface surface, const EGLint *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNLOCKSURFACEKHRPROC) (EGLDisplay display, EGLSurface surface);
+#endif
+
+#ifndef EGL_KHR_image
+#define EGL_KHR_image 1
+#define EGL_NATIVE_PIXMAP_KHR			0x30B0	/* eglCreateImageKHR target */
+typedef void *EGLImageKHR;
+#define EGL_NO_IMAGE_KHR			((EGLImageKHR)0)
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR (EGLDisplay dpy, EGLImageKHR image);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);
+#endif
+
+#ifndef EGL_KHR_vg_parent_image
+#define EGL_KHR_vg_parent_image 1
+#define EGL_VG_PARENT_IMAGE_KHR			0x30BA	/* eglCreateImageKHR target */
+#endif
+
+#ifndef EGL_KHR_gl_texture_2D_image
+#define EGL_KHR_gl_texture_2D_image 1
+#define EGL_GL_TEXTURE_2D_KHR			0x30B1	/* eglCreateImageKHR target */
+#define EGL_GL_TEXTURE_LEVEL_KHR		0x30BC	/* eglCreateImageKHR attribute */
+#endif
+
+#ifndef EGL_KHR_gl_texture_cubemap_image
+#define EGL_KHR_gl_texture_cubemap_image 1
+#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR	0x30B3	/* eglCreateImageKHR target */
+#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR	0x30B4	/* eglCreateImageKHR target */
+#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR	0x30B5	/* eglCreateImageKHR target */
+#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR	0x30B6	/* eglCreateImageKHR target */
+#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR	0x30B7	/* eglCreateImageKHR target */
+#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR	0x30B8	/* eglCreateImageKHR target */
+#endif
+
+#ifndef EGL_KHR_gl_texture_3D_image
+#define EGL_KHR_gl_texture_3D_image 1
+#define EGL_GL_TEXTURE_3D_KHR			0x30B2	/* eglCreateImageKHR target */
+#define EGL_GL_TEXTURE_ZOFFSET_KHR		0x30BD	/* eglCreateImageKHR attribute */
+#endif
+
+#ifndef EGL_KHR_gl_renderbuffer_image
+#define EGL_KHR_gl_renderbuffer_image 1
+#define EGL_GL_RENDERBUFFER_KHR			0x30B9	/* eglCreateImageKHR target */
+#endif
+
+#ifndef EGL_KHR_reusable_sync
+#define EGL_KHR_reusable_sync 1
+
+typedef void* EGLSyncKHR;
+typedef khronos_utime_nanoseconds_t EGLTimeKHR;
+
+#define EGL_SYNC_STATUS_KHR			0x30F1
+#define EGL_SIGNALED_KHR			0x30F2
+#define EGL_UNSIGNALED_KHR			0x30F3
+#define EGL_TIMEOUT_EXPIRED_KHR			0x30F5
+#define EGL_CONDITION_SATISFIED_KHR		0x30F6
+#define EGL_SYNC_TYPE_KHR			0x30F7
+#define EGL_SYNC_REUSABLE_KHR			0x30FA
+#define EGL_SYNC_FLUSH_COMMANDS_BIT_KHR		0x0001	/* eglClientWaitSyncKHR <flags> bitfield */
+#define EGL_FOREVER_KHR				0xFFFFFFFFFFFFFFFFull
+#define EGL_NO_SYNC_KHR				((EGLSyncKHR)0)
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync);
+EGLAPI EGLint EGLAPIENTRY eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
+EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode);
+EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLSyncKHR (EGLAPIENTRYP PFNEGLCREATESYNCKHRPROC) (EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync);
+typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value);
+#endif
+
+#ifndef EGL_KHR_image_base
+#define EGL_KHR_image_base 1
+/* Most interfaces defined by EGL_KHR_image_pixmap above */
+#define EGL_IMAGE_PRESERVED_KHR			0x30D2	/* eglCreateImageKHR attribute */
+#endif
+
+#ifndef EGL_KHR_image_pixmap
+#define EGL_KHR_image_pixmap 1
+/* Interfaces defined by EGL_KHR_image above */
+#endif
+
+#ifndef EGL_IMG_context_priority
+#define EGL_IMG_context_priority 1
+#define EGL_CONTEXT_PRIORITY_LEVEL_IMG		0x3100
+#define EGL_CONTEXT_PRIORITY_HIGH_IMG		0x3101
+#define EGL_CONTEXT_PRIORITY_MEDIUM_IMG		0x3102
+#define EGL_CONTEXT_PRIORITY_LOW_IMG		0x3103
+#endif
+
+#ifndef EGL_NV_coverage_sample
+#define EGL_NV_coverage_sample 1
+#define EGL_COVERAGE_BUFFERS_NV 0x30E0
+#define EGL_COVERAGE_SAMPLES_NV 0x30E1
+#endif
+
+#ifndef EGL_NV_depth_nonlinear
+#define EGL_NV_depth_nonlinear 1
+#define EGL_DEPTH_ENCODING_NV 0x30E2
+#define EGL_DEPTH_ENCODING_NONE_NV 0
+#define EGL_DEPTH_ENCODING_NONLINEAR_NV 0x30E3
+#endif
+
+#ifndef EGL_NV_sync
+#define EGL_NV_sync 1
+#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_NV	0x30E6
+#define EGL_SYNC_STATUS_NV			0x30E7
+#define EGL_SIGNALED_NV				0x30E8
+#define EGL_UNSIGNALED_NV			0x30E9
+#define EGL_SYNC_FLUSH_COMMANDS_BIT_NV		0x0001
+#define EGL_FOREVER_NV				0xFFFFFFFFFFFFFFFFull
+#define EGL_ALREADY_SIGNALED_NV			0x30EA
+#define EGL_TIMEOUT_EXPIRED_NV			0x30EB
+#define EGL_CONDITION_SATISFIED_NV		0x30EC
+#define EGL_SYNC_TYPE_NV			0x30ED
+#define EGL_SYNC_CONDITION_NV			0x30EE
+#define EGL_SYNC_FENCE_NV			0x30EF
+#define EGL_NO_SYNC_NV				((EGLSyncNV)0)
+typedef void* EGLSyncNV;
+typedef unsigned long long EGLTimeNV;
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLSyncNV eglCreateFenceSyncNV (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list);
+EGLBoolean eglDestroySyncNV (EGLSyncNV sync);
+EGLBoolean eglFenceNV (EGLSyncNV sync);
+EGLint eglClientWaitSyncNV (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout);
+EGLBoolean eglSignalSyncNV (EGLSyncNV sync, EGLenum mode);
+EGLBoolean eglGetSyncAttribNV (EGLSyncNV sync, EGLint attribute, EGLint *value);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLSyncNV (EGLAPIENTRYP PFNEGLCREATEFENCESYNCNVPROC) (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCNVPROC) (EGLSyncNV sync);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLFENCENVPROC) (EGLSyncNV sync);
+typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCNVPROC) (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCNVPROC) (EGLSyncNV sync, EGLenum mode);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBNVPROC) (EGLSyncNV sync, EGLint attribute, EGLint *value);
+#endif
+
+/* Platsim related functions (non-standard)*/
+
+EGLAPI void EGLAPIENTRY eglPlatsimSetProcessInformation( EGLint process, EGLint thread );
+
+EGLAPI EGLint EGLAPIENTRY eglPlatsimGetError();
+
+EGLAPI void EGLAPIENTRY eglPlatsimSetSurfaceParams( EGLDisplay display, EGLSurface surface, EGLint width, EGLint height,
+    EGLint stride, void* buffer0, void *buffer1);
+
+EGLAPI EGLNativePixmapType EGLAPIENTRY eglPlatsimGetPixmapSurfaceBitmap( EGLDisplay display, EGLSurface surface);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/EGL/eglplatform.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,111 @@
+#ifndef __eglplatform_h_
+#define __eglplatform_h_
+
+/*
+** Copyright (c) 2007-2009 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.
+*/
+
+/* Platform-specific types and definitions for egl.h
+ * $Revision: 9724 $ on $Date: 2009-12-02 02:05:33 -0800 (Wed, 02 Dec 2009) $
+ *
+ * Adopters may modify khrplatform.h and this file to suit their platform.
+ * You are encouraged to submit all modifications to the Khronos group so that
+ * they can be included in future versions of this file.  Please submit changes
+ * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
+ * by filing a bug against product "EGL" component "Registry".
+ */
+
+#include <KHR/khrplatform.h>
+
+/* Macros used in EGL function prototype declarations.
+ *
+ * EGL functions should be prototyped as:
+ *
+ * EGLAPI return-type EGLAPIENTRY eglFunction(arguments);
+ * typedef return-type (EXPAPIENTRYP PFNEGLFUNCTIONPROC) (arguments);
+ *
+ * KHRONOS_APICALL and KHRONOS_APIENTRY are defined in KHR/khrplatform.h
+ */
+
+#ifndef EGLAPI
+#define EGLAPI KHRONOS_APICALL
+#endif
+
+#ifndef EGLAPIENTRY
+#define EGLAPIENTRY  KHRONOS_APIENTRY
+#endif
+#define EGLAPIENTRYP EGLAPIENTRY*
+
+/* The types NativeDisplayType, NativeWindowType, and NativePixmapType
+ * are aliases of window-system-dependent types, such as X Display * or
+ * Windows Device Context. They must be defined in platform-specific
+ * code below. The EGL-prefixed versions of Native*Type are the same
+ * types, renamed in EGL 1.3 so all types in the API start with "EGL".
+ */
+
+#if defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif
+#include <windows.h>
+#include <assert.h>
+
+typedef HDC     EGLNativeDisplayType;
+typedef HBITMAP EGLNativePixmapType;
+typedef HWND    EGLNativeWindowType;
+
+#elif defined(__WINSCW__) || defined(__SYMBIAN32__)  /* Symbian */
+
+typedef int   EGLNativeDisplayType;
+typedef void *EGLNativeWindowType;
+typedef void *EGLNativePixmapType;
+
+#elif defined(__unix__)
+
+/* X11 (tentative)  */
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+
+typedef Display *EGLNativeDisplayType;
+typedef Pixmap   EGLNativePixmapType;
+typedef Window   EGLNativeWindowType;
+
+#else
+#error "Platform not recognized"
+#endif
+
+/* EGL 1.2 types, renamed for consistency in EGL 1.3 */
+typedef EGLNativeDisplayType NativeDisplayType;
+typedef EGLNativePixmapType  NativePixmapType;
+typedef EGLNativeWindowType  NativeWindowType;
+
+
+/* Define EGLint. This must be a signed integral type large enough to contain
+ * all legal attribute names and values passed into and out of EGL, whether
+ * their type is boolean, bitmask, enumerant (symbolic constant), integer,
+ * handle, or other.  While in general a 32-bit integer will suffice, if
+ * handles are 64 bit types, then EGLint should be defined as a signed 64-bit
+ * integer type.
+ */
+typedef khronos_int32_t EGLint;
+
+#endif /* __eglplatform_h */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GL/glext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,10073 @@
+#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-03-11 11:19:31 -0800 (Thu, 11 Mar 2010) $ */
+/* Current version at http://www.opengl.org/registry/ */
+#define GL_GLEXT_VERSION 60
+/* 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 */
+/* Would reuse tokens from ARB_draw_instanced, but it has 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 */
+/* Would reuse tokens from ARB_draw_elements_base_vertex, but it has none */
+/* Would reuse tokens from ARB_fragment_coord_conventions, but it has 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
+/* 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 */
+/* Would reuse tokens from ARB_explicit_attrib_location, but it has none */
+/* Reuse tokens from ARB_occlusion_query2 */
+/* reuse GL_ANY_SAMPLES_PASSED */
+/* Reuse tokens from ARB_sampler_objects */
+/* reuse GL_SAMPLER_BINDING */
+/* Would reuse tokens from ARB_shader_bit_encoding, but it has 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
+/* 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 */
+/* Would reuse tokens from ARB_texture_buffer_object_rgb32, but it has 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_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                 0x8C36
+#define GL_MIN_SAMPLE_SHADING_VALUE       0x8C37
+#endif
+
+#ifndef GL_ARB_texture_cube_map_array
+#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
+#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
+#define GL_MAX_VERTEX_STREAMS             0x8E71
+#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
+#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            0x8768
+#define GL_ELEMENT_ARRAY_TYPE_APPLE       0x8769
+#define GL_ELEMENT_ARRAY_POINTER_APPLE    0x876A
+#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_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
+#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
+#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
+
+
+/*************************************************************/
+
+#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 ARB_sync
+typedef int64_t GLint64;
+typedef uint64_t GLuint64;
+typedef struct __GLsync *GLsync;
+#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, GLint *first, 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, GLint *first, 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 frontfunc, GLenum backfunc, 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 frontfunc, GLenum backfunc, 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 glProgramParameteri (GLuint program, GLenum pname, GLint value);
+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 PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value);
+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 */
+#endif
+
+#ifndef GL_VERSION_4_0
+#define GL_VERSION_4_0 1
+/* OpenGL 4.0 also reuses entry points from these extensions: */
+/* 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_transform_feedback2 */
+/* ARB_transform_feedback3 */
+#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 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 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_ARB_sample_shading
+#define GL_ARB_sample_shading 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMinSampleShading (GLclampf value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC) (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_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_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 (GLenum 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 glGetSamplerParameterIfv (GLuint sampler, GLenum pname, GLfloat *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) (GLenum 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 PFNGLGETSAMPLERPARAMETERIFVPROC) (GLuint sampler, GLenum pname, GLfloat *params);
+#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_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);
+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 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);
+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_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_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_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, GLint *first, 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, GLint *first, 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 GLchar* *varyings, 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);
+#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 GLchar* *varyings, 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);
+#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 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);
+#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 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);
+#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, void *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, void *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
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GL/glut.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,716 @@
+#ifndef __glut_h__
+#define __glut_h__
+
+/* Copyright (c) Mark J. Kilgard, 1994, 1995, 1996, 1998. */
+
+/* This program is freely distributable without licensing fees  and is
+   provided without guarantee or warrantee expressed or  implied. This
+   program is -not- in the public domain. */
+
+#if defined(_WIN32)
+
+/* GLUT 3.7 now tries to avoid including <windows.h>
+   to avoid name space pollution, but Win32's <GL/gl.h> 
+   needs APIENTRY and WINGDIAPI defined properly. */
+# if 0
+   /* This would put tons of macros and crap in our clean name space. */
+#  define  WIN32_LEAN_AND_MEAN
+#  include <windows.h>
+# else
+   /* XXX This is from Win32's <windef.h> */
+#  ifndef APIENTRY
+#   define GLUT_APIENTRY_DEFINED
+#   if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) || defined(__BORLANDC__) || defined(__LCC__)
+#    define APIENTRY    __stdcall
+#   else
+#    define APIENTRY
+#   endif
+#  endif
+   /* XXX This is from Win32's <winnt.h> */
+#  ifndef CALLBACK
+#   if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS) || defined(__LCC__)
+#    define CALLBACK __stdcall
+#   else
+#    define CALLBACK
+#   endif
+#  endif
+   /* XXX Hack for lcc compiler.  It doesn't support __declspec(dllimport), just __stdcall. */
+#  if defined( __LCC__ )
+#   undef WINGDIAPI
+#   define WINGDIAPI __stdcall
+#  else
+   /* XXX This is from Win32's <wingdi.h> and <winnt.h> */
+#   ifndef WINGDIAPI
+#    define GLUT_WINGDIAPI_DEFINED
+#    define WINGDIAPI __declspec(dllimport)
+#   endif
+#  endif
+   /* XXX This is from Win32's <ctype.h> */
+#  ifndef _WCHAR_T_DEFINED
+typedef unsigned short wchar_t;
+#   define _WCHAR_T_DEFINED
+#  endif
+# endif
+
+/* To disable automatic library usage for GLUT, define GLUT_NO_LIB_PRAGMA
+   in your compile preprocessor options. */
+# if !defined(GLUT_BUILDING_LIB) && !defined(GLUT_NO_LIB_PRAGMA)
+#  pragma comment (lib, "winmm.lib")      /* link with Windows MultiMedia lib */
+/* To enable automatic SGI OpenGL for Windows library usage for GLUT,
+   define GLUT_USE_SGI_OPENGL in your compile preprocessor options.  */
+#  ifdef GLUT_USE_SGI_OPENGL
+#   pragma comment (lib, "opengl.lib")    /* link with SGI OpenGL for Windows lib */
+#   pragma comment (lib, "glu.lib")       /* link with SGI OpenGL Utility lib */
+#   pragma comment (lib, "glut.lib")      /* link with Win32 GLUT for SGI OpenGL lib */
+#  else
+#   pragma comment (lib, "opengl32.lib")  /* link with Microsoft OpenGL lib */
+#   pragma comment (lib, "glu32.lib")     /* link with Microsoft OpenGL Utility lib */
+#   pragma comment (lib, "glut32.lib")    /* link with Win32 GLUT lib */
+#  endif
+# endif
+
+/* To disable supression of annoying warnings about floats being promoted
+   to doubles, define GLUT_NO_WARNING_DISABLE in your compile preprocessor
+   options. */
+# ifndef GLUT_NO_WARNING_DISABLE
+#  pragma warning (disable:4244)  /* Disable bogus VC++ 4.2 conversion warnings. */
+#  pragma warning (disable:4305)  /* VC++ 5.0 version of above warning. */
+# endif
+
+/* Win32 has an annoying issue where there are multiple C run-time
+   libraries (CRTs).  If the executable is linked with a different CRT
+   from the GLUT DLL, the GLUT DLL will not share the same CRT static
+   data seen by the executable.  In particular, atexit callbacks registered
+   in the executable will not be called if GLUT calls its (different)
+   exit routine).  GLUT is typically built with the
+   "/MD" option (the CRT with multithreading DLL support), but the Visual
+   C++ linker default is "/ML" (the single threaded CRT).
+
+   One workaround to this issue is requiring users to always link with
+   the same CRT as GLUT is compiled with.  That requires users supply a
+   non-standard option.  GLUT 3.7 has its own built-in workaround where
+   the executable's "exit" function pointer is covertly passed to GLUT.
+   GLUT then calls the executable's exit function pointer to ensure that
+   any "atexit" calls registered by the application are called if GLUT
+   needs to exit.
+
+   Note that the __glut*WithExit routines should NEVER be called directly.
+   To avoid the atexit workaround, #define GLUT_DISABLE_ATEXIT_HACK. */
+
+/* XXX This is from Win32's <process.h> */
+# if !defined(_MSC_VER) && !defined(__cdecl)
+   /* Define __cdecl for non-Microsoft compilers. */
+#  define __cdecl
+#  define GLUT_DEFINED___CDECL
+# endif
+# ifndef _CRTIMP
+#  ifdef _NTSDK
+    /* Definition compatible with NT SDK */
+#   define _CRTIMP
+#  else
+    /* Current definition */
+#   ifdef _DLL
+#    define _CRTIMP __declspec(dllimport)
+#   else
+#    define _CRTIMP
+#   endif
+#  endif
+#  define GLUT_DEFINED__CRTIMP
+# endif
+
+/* GLUT API entry point declarations for Win32. */
+# ifdef GLUT_BUILDING_LIB
+#  define GLUTAPI __declspec(dllexport)
+# else
+#  ifdef _DLL
+#   define GLUTAPI __declspec(dllimport)
+#  else
+#   define GLUTAPI extern
+#  endif
+# endif
+
+/* GLUT callback calling convention for Win32. */
+# define GLUTCALLBACK __cdecl
+
+#endif  /* _WIN32 */
+
+#include <GL/gl.h>
+#include <GL/glu.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(_WIN32)
+# ifndef GLUT_BUILDING_LIB
+extern _CRTIMP void __cdecl exit(int);
+# endif
+#else
+/* non-Win32 case. */
+/* Define APIENTRY and CALLBACK to nothing if we aren't on Win32. */
+# define APIENTRY
+# define GLUT_APIENTRY_DEFINED
+# define CALLBACK
+/* Define GLUTAPI and GLUTCALLBACK as below if we aren't on Win32. */
+# define GLUTAPI extern
+# define GLUTCALLBACK
+/* Prototype exit for the non-Win32 case (see above). */
+//extern void exit(int);
+#endif
+
+/**
+ GLUT API revision history:
+ 
+ GLUT_API_VERSION is updated to reflect incompatible GLUT
+ API changes (interface changes, semantic changes, deletions,
+ or additions).
+ 
+ GLUT_API_VERSION=1  First public release of GLUT.  11/29/94
+
+ GLUT_API_VERSION=2  Added support for OpenGL/GLX multisampling,
+ extension.  Supports new input devices like tablet, dial and button
+ box, and Spaceball.  Easy to query OpenGL extensions.
+
+ GLUT_API_VERSION=3  glutMenuStatus added.
+
+ GLUT_API_VERSION=4  glutInitDisplayString, glutWarpPointer,
+ glutBitmapLength, glutStrokeLength, glutWindowStatusFunc, dynamic
+ video resize subAPI, glutPostWindowRedisplay, glutKeyboardUpFunc,
+ glutSpecialUpFunc, glutIgnoreKeyRepeat, glutSetKeyRepeat,
+ glutJoystickFunc, glutForceJoystickFunc (NOT FINALIZED!).
+**/
+#ifndef GLUT_API_VERSION  /* allow this to be overriden */
+#define GLUT_API_VERSION		3
+#endif
+
+/**
+ GLUT implementation revision history:
+ 
+ GLUT_XLIB_IMPLEMENTATION is updated to reflect both GLUT
+ API revisions and implementation revisions (ie, bug fixes).
+
+ GLUT_XLIB_IMPLEMENTATION=1  mjk's first public release of
+ GLUT Xlib-based implementation.  11/29/94
+
+ GLUT_XLIB_IMPLEMENTATION=2  mjk's second public release of
+ GLUT Xlib-based implementation providing GLUT version 2 
+ interfaces.
+
+ GLUT_XLIB_IMPLEMENTATION=3  mjk's GLUT 2.2 images. 4/17/95
+
+ GLUT_XLIB_IMPLEMENTATION=4  mjk's GLUT 2.3 images. 6/?/95
+
+ GLUT_XLIB_IMPLEMENTATION=5  mjk's GLUT 3.0 images. 10/?/95
+
+ GLUT_XLIB_IMPLEMENTATION=7  mjk's GLUT 3.1+ with glutWarpPoitner.  7/24/96
+
+ GLUT_XLIB_IMPLEMENTATION=8  mjk's GLUT 3.1+ with glutWarpPoitner
+ and video resize.  1/3/97
+
+ GLUT_XLIB_IMPLEMENTATION=9 mjk's GLUT 3.4 release with early GLUT 4 routines.
+
+ GLUT_XLIB_IMPLEMENTATION=11 Mesa 2.5's GLUT 3.6 release.
+
+ GLUT_XLIB_IMPLEMENTATION=12 mjk's GLUT 3.6 release with early GLUT 4 routines + signal handling.
+
+ GLUT_XLIB_IMPLEMENTATION=13 mjk's GLUT 3.7 beta with GameGLUT support.
+
+ GLUT_XLIB_IMPLEMENTATION=14 mjk's GLUT 3.7 beta with f90gl friend interface.
+
+ GLUT_XLIB_IMPLEMENTATION=15 mjk's GLUT 3.7 beta sync'ed with Mesa <GL/glut.h>
+**/
+#ifndef GLUT_XLIB_IMPLEMENTATION  /* Allow this to be overriden. */
+#define GLUT_XLIB_IMPLEMENTATION	15
+#endif
+
+/* Display mode bit masks. */
+#define GLUT_RGB			0
+#define GLUT_RGBA			GLUT_RGB
+#define GLUT_INDEX			1
+#define GLUT_SINGLE			0
+#define GLUT_DOUBLE			2
+#define GLUT_ACCUM			4
+#define GLUT_ALPHA			8
+#define GLUT_DEPTH			16
+#define GLUT_STENCIL			32
+#if (GLUT_API_VERSION >= 2)
+#define GLUT_MULTISAMPLE		128
+#define GLUT_STEREO			256
+#endif
+#if (GLUT_API_VERSION >= 3)
+#define GLUT_LUMINANCE			512
+#endif
+
+/* Mouse buttons. */
+#define GLUT_LEFT_BUTTON		0
+#define GLUT_MIDDLE_BUTTON		1
+#define GLUT_RIGHT_BUTTON		2
+
+/* Mouse button  state. */
+#define GLUT_DOWN			0
+#define GLUT_UP				1
+
+#if (GLUT_API_VERSION >= 2)
+/* function keys */
+#define GLUT_KEY_F1			1
+#define GLUT_KEY_F2			2
+#define GLUT_KEY_F3			3
+#define GLUT_KEY_F4			4
+#define GLUT_KEY_F5			5
+#define GLUT_KEY_F6			6
+#define GLUT_KEY_F7			7
+#define GLUT_KEY_F8			8
+#define GLUT_KEY_F9			9
+#define GLUT_KEY_F10			10
+#define GLUT_KEY_F11			11
+#define GLUT_KEY_F12			12
+/* directional keys */
+#define GLUT_KEY_LEFT			100
+#define GLUT_KEY_UP			101
+#define GLUT_KEY_RIGHT			102
+#define GLUT_KEY_DOWN			103
+#define GLUT_KEY_PAGE_UP		104
+#define GLUT_KEY_PAGE_DOWN		105
+#define GLUT_KEY_HOME			106
+#define GLUT_KEY_END			107
+#define GLUT_KEY_INSERT			108
+#endif
+
+/* Entry/exit  state. */
+#define GLUT_LEFT			0
+#define GLUT_ENTERED			1
+
+/* Menu usage  state. */
+#define GLUT_MENU_NOT_IN_USE		0
+#define GLUT_MENU_IN_USE		1
+
+/* Visibility  state. */
+#define GLUT_NOT_VISIBLE		0
+#define GLUT_VISIBLE			1
+
+/* Window status  state. */
+#define GLUT_HIDDEN			0
+#define GLUT_FULLY_RETAINED		1
+#define GLUT_PARTIALLY_RETAINED		2
+#define GLUT_FULLY_COVERED		3
+
+/* Color index component selection values. */
+#define GLUT_RED			0
+#define GLUT_GREEN			1
+#define GLUT_BLUE			2
+
+#if defined(_WIN32)
+/* Stroke font constants (use these in GLUT program). */
+#define GLUT_STROKE_ROMAN		((void*)0)
+#define GLUT_STROKE_MONO_ROMAN		((void*)1)
+
+/* Bitmap font constants (use these in GLUT program). */
+#define GLUT_BITMAP_9_BY_15		((void*)2)
+#define GLUT_BITMAP_8_BY_13		((void*)3)
+#define GLUT_BITMAP_TIMES_ROMAN_10	((void*)4)
+#define GLUT_BITMAP_TIMES_ROMAN_24	((void*)5)
+#if (GLUT_API_VERSION >= 3)
+#define GLUT_BITMAP_HELVETICA_10	((void*)6)
+#define GLUT_BITMAP_HELVETICA_12	((void*)7)
+#define GLUT_BITMAP_HELVETICA_18	((void*)8)
+#endif
+#else
+/* Stroke font opaque addresses (use constants instead in source code). */
+GLUTAPI void *glutStrokeRoman;
+GLUTAPI void *glutStrokeMonoRoman;
+
+/* Stroke font constants (use these in GLUT program). */
+#define GLUT_STROKE_ROMAN		(&glutStrokeRoman)
+#define GLUT_STROKE_MONO_ROMAN		(&glutStrokeMonoRoman)
+
+/* Bitmap font opaque addresses (use constants instead in source code). */
+GLUTAPI void *glutBitmap9By15;
+GLUTAPI void *glutBitmap8By13;
+GLUTAPI void *glutBitmapTimesRoman10;
+GLUTAPI void *glutBitmapTimesRoman24;
+GLUTAPI void *glutBitmapHelvetica10;
+GLUTAPI void *glutBitmapHelvetica12;
+GLUTAPI void *glutBitmapHelvetica18;
+
+/* Bitmap font constants (use these in GLUT program). */
+#define GLUT_BITMAP_9_BY_15		(&glutBitmap9By15)
+#define GLUT_BITMAP_8_BY_13		(&glutBitmap8By13)
+#define GLUT_BITMAP_TIMES_ROMAN_10	(&glutBitmapTimesRoman10)
+#define GLUT_BITMAP_TIMES_ROMAN_24	(&glutBitmapTimesRoman24)
+#if (GLUT_API_VERSION >= 3)
+#define GLUT_BITMAP_HELVETICA_10	(&glutBitmapHelvetica10)
+#define GLUT_BITMAP_HELVETICA_12	(&glutBitmapHelvetica12)
+#define GLUT_BITMAP_HELVETICA_18	(&glutBitmapHelvetica18)
+#endif
+#endif
+
+/* glutGet parameters. */
+#define GLUT_WINDOW_X			((GLenum) 100)
+#define GLUT_WINDOW_Y			((GLenum) 101)
+#define GLUT_WINDOW_WIDTH		((GLenum) 102)
+#define GLUT_WINDOW_HEIGHT		((GLenum) 103)
+#define GLUT_WINDOW_BUFFER_SIZE		((GLenum) 104)
+#define GLUT_WINDOW_STENCIL_SIZE	((GLenum) 105)
+#define GLUT_WINDOW_DEPTH_SIZE		((GLenum) 106)
+#define GLUT_WINDOW_RED_SIZE		((GLenum) 107)
+#define GLUT_WINDOW_GREEN_SIZE		((GLenum) 108)
+#define GLUT_WINDOW_BLUE_SIZE		((GLenum) 109)
+#define GLUT_WINDOW_ALPHA_SIZE		((GLenum) 110)
+#define GLUT_WINDOW_ACCUM_RED_SIZE	((GLenum) 111)
+#define GLUT_WINDOW_ACCUM_GREEN_SIZE	((GLenum) 112)
+#define GLUT_WINDOW_ACCUM_BLUE_SIZE	((GLenum) 113)
+#define GLUT_WINDOW_ACCUM_ALPHA_SIZE	((GLenum) 114)
+#define GLUT_WINDOW_DOUBLEBUFFER	((GLenum) 115)
+#define GLUT_WINDOW_RGBA		((GLenum) 116)
+#define GLUT_WINDOW_PARENT		((GLenum) 117)
+#define GLUT_WINDOW_NUM_CHILDREN	((GLenum) 118)
+#define GLUT_WINDOW_COLORMAP_SIZE	((GLenum) 119)
+#if (GLUT_API_VERSION >= 2)
+#define GLUT_WINDOW_NUM_SAMPLES		((GLenum) 120)
+#define GLUT_WINDOW_STEREO		((GLenum) 121)
+#endif
+#if (GLUT_API_VERSION >= 3)
+#define GLUT_WINDOW_CURSOR		((GLenum) 122)
+#endif
+#define GLUT_SCREEN_WIDTH		((GLenum) 200)
+#define GLUT_SCREEN_HEIGHT		((GLenum) 201)
+#define GLUT_SCREEN_WIDTH_MM		((GLenum) 202)
+#define GLUT_SCREEN_HEIGHT_MM		((GLenum) 203)
+#define GLUT_MENU_NUM_ITEMS		((GLenum) 300)
+#define GLUT_DISPLAY_MODE_POSSIBLE	((GLenum) 400)
+#define GLUT_INIT_WINDOW_X		((GLenum) 500)
+#define GLUT_INIT_WINDOW_Y		((GLenum) 501)
+#define GLUT_INIT_WINDOW_WIDTH		((GLenum) 502)
+#define GLUT_INIT_WINDOW_HEIGHT		((GLenum) 503)
+#define GLUT_INIT_DISPLAY_MODE		((GLenum) 504)
+#if (GLUT_API_VERSION >= 2)
+#define GLUT_ELAPSED_TIME		((GLenum) 700)
+#endif
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13)
+#define GLUT_WINDOW_FORMAT_ID		((GLenum) 123)
+#endif
+
+#if (GLUT_API_VERSION >= 2)
+/* glutDeviceGet parameters. */
+#define GLUT_HAS_KEYBOARD		((GLenum) 600)
+#define GLUT_HAS_MOUSE			((GLenum) 601)
+#define GLUT_HAS_SPACEBALL		((GLenum) 602)
+#define GLUT_HAS_DIAL_AND_BUTTON_BOX	((GLenum) 603)
+#define GLUT_HAS_TABLET			((GLenum) 604)
+#define GLUT_NUM_MOUSE_BUTTONS		((GLenum) 605)
+#define GLUT_NUM_SPACEBALL_BUTTONS	((GLenum) 606)
+#define GLUT_NUM_BUTTON_BOX_BUTTONS	((GLenum) 607)
+#define GLUT_NUM_DIALS			((GLenum) 608)
+#define GLUT_NUM_TABLET_BUTTONS		((GLenum) 609)
+#endif
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13)
+#define GLUT_DEVICE_IGNORE_KEY_REPEAT   ((GLenum) 610)
+#define GLUT_DEVICE_KEY_REPEAT          ((GLenum) 611)
+#define GLUT_HAS_JOYSTICK		((GLenum) 612)
+#define GLUT_OWNS_JOYSTICK		((GLenum) 613)
+#define GLUT_JOYSTICK_BUTTONS		((GLenum) 614)
+#define GLUT_JOYSTICK_AXES		((GLenum) 615)
+#define GLUT_JOYSTICK_POLL_RATE		((GLenum) 616)
+#endif
+
+#if (GLUT_API_VERSION >= 3)
+/* glutLayerGet parameters. */
+#define GLUT_OVERLAY_POSSIBLE           ((GLenum) 800)
+#define GLUT_LAYER_IN_USE		((GLenum) 801)
+#define GLUT_HAS_OVERLAY		((GLenum) 802)
+#define GLUT_TRANSPARENT_INDEX		((GLenum) 803)
+#define GLUT_NORMAL_DAMAGED		((GLenum) 804)
+#define GLUT_OVERLAY_DAMAGED		((GLenum) 805)
+
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
+/* glutVideoResizeGet parameters. */
+#define GLUT_VIDEO_RESIZE_POSSIBLE	((GLenum) 900)
+#define GLUT_VIDEO_RESIZE_IN_USE	((GLenum) 901)
+#define GLUT_VIDEO_RESIZE_X_DELTA	((GLenum) 902)
+#define GLUT_VIDEO_RESIZE_Y_DELTA	((GLenum) 903)
+#define GLUT_VIDEO_RESIZE_WIDTH_DELTA	((GLenum) 904)
+#define GLUT_VIDEO_RESIZE_HEIGHT_DELTA	((GLenum) 905)
+#define GLUT_VIDEO_RESIZE_X		((GLenum) 906)
+#define GLUT_VIDEO_RESIZE_Y		((GLenum) 907)
+#define GLUT_VIDEO_RESIZE_WIDTH		((GLenum) 908)
+#define GLUT_VIDEO_RESIZE_HEIGHT	((GLenum) 909)
+#endif
+
+/* glutUseLayer parameters. */
+#define GLUT_NORMAL			((GLenum) 0)
+#define GLUT_OVERLAY			((GLenum) 1)
+
+/* glutGetModifiers return mask. */
+#define GLUT_ACTIVE_SHIFT               1
+#define GLUT_ACTIVE_CTRL                2
+#define GLUT_ACTIVE_ALT                 4
+
+/* glutSetCursor parameters. */
+/* Basic arrows. */
+#define GLUT_CURSOR_RIGHT_ARROW		0
+#define GLUT_CURSOR_LEFT_ARROW		1
+/* Symbolic cursor shapes. */
+#define GLUT_CURSOR_INFO		2
+#define GLUT_CURSOR_DESTROY		3
+#define GLUT_CURSOR_HELP		4
+#define GLUT_CURSOR_CYCLE		5
+#define GLUT_CURSOR_SPRAY		6
+#define GLUT_CURSOR_WAIT		7
+#define GLUT_CURSOR_TEXT		8
+#define GLUT_CURSOR_CROSSHAIR		9
+/* Directional cursors. */
+#define GLUT_CURSOR_UP_DOWN		10
+#define GLUT_CURSOR_LEFT_RIGHT		11
+/* Sizing cursors. */
+#define GLUT_CURSOR_TOP_SIDE		12
+#define GLUT_CURSOR_BOTTOM_SIDE		13
+#define GLUT_CURSOR_LEFT_SIDE		14
+#define GLUT_CURSOR_RIGHT_SIDE		15
+#define GLUT_CURSOR_TOP_LEFT_CORNER	16
+#define GLUT_CURSOR_TOP_RIGHT_CORNER	17
+#define GLUT_CURSOR_BOTTOM_RIGHT_CORNER	18
+#define GLUT_CURSOR_BOTTOM_LEFT_CORNER	19
+/* Inherit from parent window. */
+#define GLUT_CURSOR_INHERIT		100
+/* Blank cursor. */
+#define GLUT_CURSOR_NONE		101
+/* Fullscreen crosshair (if available). */
+#define GLUT_CURSOR_FULL_CROSSHAIR	102
+#endif
+
+/* GLUT initialization sub-API. */
+GLUTAPI void APIENTRY glutInit(int *argcp, char **argv);
+#if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK)
+GLUTAPI void APIENTRY __glutInitWithExit(int *argcp, char **argv, void (__cdecl *exitfunc)(int));
+#ifndef GLUT_BUILDING_LIB
+static void APIENTRY glutInit_ATEXIT_HACK(int *argcp, char **argv) { __glutInitWithExit(argcp, argv, exit); }
+#define glutInit glutInit_ATEXIT_HACK
+#endif
+#endif
+GLUTAPI void APIENTRY glutInitDisplayMode(unsigned int mode);
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
+GLUTAPI void APIENTRY glutInitDisplayString(const char *string);
+#endif
+GLUTAPI void APIENTRY glutInitWindowPosition(int x, int y);
+GLUTAPI void APIENTRY glutInitWindowSize(int width, int height);
+GLUTAPI void APIENTRY glutMainLoop(void);
+
+/* GLUT window sub-API. */
+GLUTAPI int APIENTRY glutCreateWindow(const char *title);
+#if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK)
+GLUTAPI int APIENTRY __glutCreateWindowWithExit(const char *title, void (__cdecl *exitfunc)(int));
+#ifndef GLUT_BUILDING_LIB
+static int APIENTRY glutCreateWindow_ATEXIT_HACK(const char *title) { return __glutCreateWindowWithExit(title, exit); }
+#define glutCreateWindow glutCreateWindow_ATEXIT_HACK
+#endif
+#endif
+GLUTAPI int APIENTRY glutCreateSubWindow(int win, int x, int y, int width, int height);
+GLUTAPI void APIENTRY glutDestroyWindow(int win);
+GLUTAPI void APIENTRY glutPostRedisplay(void);
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 11)
+GLUTAPI void APIENTRY glutPostWindowRedisplay(int win);
+#endif
+GLUTAPI void APIENTRY glutSwapBuffers(void);
+GLUTAPI int APIENTRY glutGetWindow(void);
+GLUTAPI void APIENTRY glutSetWindow(int win);
+GLUTAPI void APIENTRY glutSetWindowTitle(const char *title);
+GLUTAPI void APIENTRY glutSetIconTitle(const char *title);
+GLUTAPI void APIENTRY glutPositionWindow(int x, int y);
+GLUTAPI void APIENTRY glutReshapeWindow(int width, int height);
+GLUTAPI void APIENTRY glutPopWindow(void);
+GLUTAPI void APIENTRY glutPushWindow(void);
+GLUTAPI void APIENTRY glutIconifyWindow(void);
+GLUTAPI void APIENTRY glutShowWindow(void);
+GLUTAPI void APIENTRY glutHideWindow(void);
+#if (GLUT_API_VERSION >= 3)
+GLUTAPI void APIENTRY glutFullScreen(void);
+GLUTAPI void APIENTRY glutSetCursor(int cursor);
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
+GLUTAPI void APIENTRY glutWarpPointer(int x, int y);
+#endif
+
+/* GLUT overlay sub-API. */
+GLUTAPI void APIENTRY glutEstablishOverlay(void);
+GLUTAPI void APIENTRY glutRemoveOverlay(void);
+GLUTAPI void APIENTRY glutUseLayer(GLenum layer);
+GLUTAPI void APIENTRY glutPostOverlayRedisplay(void);
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 11)
+GLUTAPI void APIENTRY glutPostWindowOverlayRedisplay(int win);
+#endif
+GLUTAPI void APIENTRY glutShowOverlay(void);
+GLUTAPI void APIENTRY glutHideOverlay(void);
+#endif
+
+/* GLUT menu sub-API. */
+GLUTAPI int APIENTRY glutCreateMenu(void (GLUTCALLBACK *func)(int));
+#if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK)
+GLUTAPI int APIENTRY __glutCreateMenuWithExit(void (GLUTCALLBACK *func)(int), void (__cdecl *exitfunc)(int));
+#ifndef GLUT_BUILDING_LIB
+static int APIENTRY glutCreateMenu_ATEXIT_HACK(void (GLUTCALLBACK *func)(int)) { return __glutCreateMenuWithExit(func, exit); }
+#define glutCreateMenu glutCreateMenu_ATEXIT_HACK
+#endif
+#endif
+GLUTAPI void APIENTRY glutDestroyMenu(int menu);
+GLUTAPI int APIENTRY glutGetMenu(void);
+GLUTAPI void APIENTRY glutSetMenu(int menu);
+GLUTAPI void APIENTRY glutAddMenuEntry(const char *label, int value);
+GLUTAPI void APIENTRY glutAddSubMenu(const char *label, int submenu);
+GLUTAPI void APIENTRY glutChangeToMenuEntry(int item, const char *label, int value);
+GLUTAPI void APIENTRY glutChangeToSubMenu(int item, const char *label, int submenu);
+GLUTAPI void APIENTRY glutRemoveMenuItem(int item);
+GLUTAPI void APIENTRY glutAttachMenu(int button);
+GLUTAPI void APIENTRY glutDetachMenu(int button);
+
+/* GLUT window callback sub-API. */
+GLUTAPI void APIENTRY glutDisplayFunc(void (GLUTCALLBACK *func)(void));
+GLUTAPI void APIENTRY glutReshapeFunc(void (GLUTCALLBACK *func)(int width, int height));
+GLUTAPI void APIENTRY glutKeyboardFunc(void (GLUTCALLBACK *func)(unsigned char key, int x, int y));
+GLUTAPI void APIENTRY glutMouseFunc(void (GLUTCALLBACK *func)(int button, int state, int x, int y));
+GLUTAPI void APIENTRY glutMotionFunc(void (GLUTCALLBACK *func)(int x, int y));
+GLUTAPI void APIENTRY glutPassiveMotionFunc(void (GLUTCALLBACK *func)(int x, int y));
+GLUTAPI void APIENTRY glutEntryFunc(void (GLUTCALLBACK *func)(int state));
+GLUTAPI void APIENTRY glutVisibilityFunc(void (GLUTCALLBACK *func)(int state));
+GLUTAPI void APIENTRY glutIdleFunc(void (GLUTCALLBACK *func)(void));
+GLUTAPI void APIENTRY glutTimerFunc(unsigned int millis, void (GLUTCALLBACK *func)(int value), int value);
+GLUTAPI void APIENTRY glutMenuStateFunc(void (GLUTCALLBACK *func)(int state));
+#if (GLUT_API_VERSION >= 2)
+GLUTAPI void APIENTRY glutSpecialFunc(void (GLUTCALLBACK *func)(int key, int x, int y));
+GLUTAPI void APIENTRY glutSpaceballMotionFunc(void (GLUTCALLBACK *func)(int x, int y, int z));
+GLUTAPI void APIENTRY glutSpaceballRotateFunc(void (GLUTCALLBACK *func)(int x, int y, int z));
+GLUTAPI void APIENTRY glutSpaceballButtonFunc(void (GLUTCALLBACK *func)(int button, int state));
+GLUTAPI void APIENTRY glutButtonBoxFunc(void (GLUTCALLBACK *func)(int button, int state));
+GLUTAPI void APIENTRY glutDialsFunc(void (GLUTCALLBACK *func)(int dial, int value));
+GLUTAPI void APIENTRY glutTabletMotionFunc(void (GLUTCALLBACK *func)(int x, int y));
+GLUTAPI void APIENTRY glutTabletButtonFunc(void (GLUTCALLBACK *func)(int button, int state, int x, int y));
+#if (GLUT_API_VERSION >= 3)
+GLUTAPI void APIENTRY glutMenuStatusFunc(void (GLUTCALLBACK *func)(int status, int x, int y));
+GLUTAPI void APIENTRY glutOverlayDisplayFunc(void (GLUTCALLBACK *func)(void));
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
+GLUTAPI void APIENTRY glutWindowStatusFunc(void (GLUTCALLBACK *func)(int state));
+#endif
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13)
+GLUTAPI void APIENTRY glutKeyboardUpFunc(void (GLUTCALLBACK *func)(unsigned char key, int x, int y));
+GLUTAPI void APIENTRY glutSpecialUpFunc(void (GLUTCALLBACK *func)(int key, int x, int y));
+GLUTAPI void APIENTRY glutJoystickFunc(void (GLUTCALLBACK *func)(unsigned int buttonMask, int x, int y, int z), int pollInterval);
+#endif
+#endif
+#endif
+
+/* GLUT color index sub-API. */
+GLUTAPI void APIENTRY glutSetColor(int, GLfloat red, GLfloat green, GLfloat blue);
+GLUTAPI GLfloat APIENTRY glutGetColor(int ndx, int component);
+GLUTAPI void APIENTRY glutCopyColormap(int win);
+
+/* GLUT state retrieval sub-API. */
+GLUTAPI int APIENTRY glutGet(GLenum type);
+GLUTAPI int APIENTRY glutDeviceGet(GLenum type);
+#if (GLUT_API_VERSION >= 2)
+/* GLUT extension support sub-API */
+GLUTAPI int APIENTRY glutExtensionSupported(const char *name);
+#endif
+#if (GLUT_API_VERSION >= 3)
+GLUTAPI int APIENTRY glutGetModifiers(void);
+GLUTAPI int APIENTRY glutLayerGet(GLenum type);
+#endif
+
+/* GLUT font sub-API */
+GLUTAPI void APIENTRY glutBitmapCharacter(void *font, int character);
+GLUTAPI int APIENTRY glutBitmapWidth(void *font, int character);
+GLUTAPI void APIENTRY glutStrokeCharacter(void *font, int character);
+GLUTAPI int APIENTRY glutStrokeWidth(void *font, int character);
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
+GLUTAPI int APIENTRY glutBitmapLength(void *font, const unsigned char *string);
+GLUTAPI int APIENTRY glutStrokeLength(void *font, const unsigned char *string);
+#endif
+
+/* GLUT pre-built models sub-API */
+GLUTAPI void APIENTRY glutWireSphere(GLdouble radius, GLint slices, GLint stacks);
+GLUTAPI void APIENTRY glutSolidSphere(GLdouble radius, GLint slices, GLint stacks);
+GLUTAPI void APIENTRY glutWireCone(GLdouble base, GLdouble height, GLint slices, GLint stacks);
+GLUTAPI void APIENTRY glutSolidCone(GLdouble base, GLdouble height, GLint slices, GLint stacks);
+GLUTAPI void APIENTRY glutWireCube(GLdouble size);
+GLUTAPI void APIENTRY glutSolidCube(GLdouble size);
+GLUTAPI void APIENTRY glutWireTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings);
+GLUTAPI void APIENTRY glutSolidTorus(GLdouble innerRadius, GLdouble outerRadius, GLint sides, GLint rings);
+GLUTAPI void APIENTRY glutWireDodecahedron(void);
+GLUTAPI void APIENTRY glutSolidDodecahedron(void);
+GLUTAPI void APIENTRY glutWireTeapot(GLdouble size);
+GLUTAPI void APIENTRY glutSolidTeapot(GLdouble size);
+GLUTAPI void APIENTRY glutWireOctahedron(void);
+GLUTAPI void APIENTRY glutSolidOctahedron(void);
+GLUTAPI void APIENTRY glutWireTetrahedron(void);
+GLUTAPI void APIENTRY glutSolidTetrahedron(void);
+GLUTAPI void APIENTRY glutWireIcosahedron(void);
+GLUTAPI void APIENTRY glutSolidIcosahedron(void);
+
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 9)
+/* GLUT video resize sub-API. */
+GLUTAPI int APIENTRY glutVideoResizeGet(GLenum param);
+GLUTAPI void APIENTRY glutSetupVideoResizing(void);
+GLUTAPI void APIENTRY glutStopVideoResizing(void);
+GLUTAPI void APIENTRY glutVideoResize(int x, int y, int width, int height);
+GLUTAPI void APIENTRY glutVideoPan(int x, int y, int width, int height);
+
+/* GLUT debugging sub-API. */
+GLUTAPI void APIENTRY glutReportErrors(void);
+#endif
+
+#if (GLUT_API_VERSION >= 4 || GLUT_XLIB_IMPLEMENTATION >= 13)
+/* GLUT device control sub-API. */
+/* glutSetKeyRepeat modes. */
+#define GLUT_KEY_REPEAT_OFF		0
+#define GLUT_KEY_REPEAT_ON		1
+#define GLUT_KEY_REPEAT_DEFAULT		2
+
+/* Joystick button masks. */
+#define GLUT_JOYSTICK_BUTTON_A		1
+#define GLUT_JOYSTICK_BUTTON_B		2
+#define GLUT_JOYSTICK_BUTTON_C		4
+#define GLUT_JOYSTICK_BUTTON_D		8
+
+GLUTAPI void APIENTRY glutIgnoreKeyRepeat(int ignore);
+GLUTAPI void APIENTRY glutSetKeyRepeat(int repeatMode);
+GLUTAPI void APIENTRY glutForceJoystickFunc(void);
+
+/* GLUT game mode sub-API. */
+/* glutGameModeGet. */
+#define GLUT_GAME_MODE_ACTIVE           ((GLenum) 0)
+#define GLUT_GAME_MODE_POSSIBLE         ((GLenum) 1)
+#define GLUT_GAME_MODE_WIDTH            ((GLenum) 2)
+#define GLUT_GAME_MODE_HEIGHT           ((GLenum) 3)
+#define GLUT_GAME_MODE_PIXEL_DEPTH      ((GLenum) 4)
+#define GLUT_GAME_MODE_REFRESH_RATE     ((GLenum) 5)
+#define GLUT_GAME_MODE_DISPLAY_CHANGED  ((GLenum) 6)
+
+GLUTAPI void APIENTRY glutGameModeString(const char *string);
+GLUTAPI int APIENTRY glutEnterGameMode(void);
+GLUTAPI void APIENTRY glutLeaveGameMode(void);
+GLUTAPI int APIENTRY glutGameModeGet(GLenum mode);
+#endif
+
+#ifdef __cplusplus
+}
+
+#endif
+
+#ifdef GLUT_APIENTRY_DEFINED
+# undef GLUT_APIENTRY_DEFINED
+# undef APIENTRY
+#endif
+
+#ifdef GLUT_WINGDIAPI_DEFINED
+# undef GLUT_WINGDIAPI_DEFINED
+# undef WINGDIAPI
+#endif
+
+#ifdef GLUT_DEFINED___CDECL
+# undef GLUT_DEFINED___CDECL
+# undef __cdecl
+#endif
+
+#ifdef GLUT_DEFINED__CRTIMP
+# undef GLUT_DEFINED__CRTIMP
+# undef _CRTIMP
+#endif
+
+#endif                  /* __glut_h__ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GL/wglext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,878 @@
+#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/05/17 */
+/* Current version at http://www.opengl.org/registry/ */
+#define WGL_WGLEXT_VERSION 19
+
+#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_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_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 NV_video_capture
+#define WGL_UNIQUE_ID_NV               0x20CE
+#define WGL_NUM_VIDEO_CAPTURE_SLOTS_NV 0x20CF
+#endif
+
+#ifndef NV_copy_image
+#endif
+
+#ifndef NV_multisample_coverage
+#define WGL_COVERAGE_SAMPLES_NV        0x2042
+#define WGL_COLOR_SAMPLES_NV           0x20B9
+#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_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_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
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES/egl.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,15 @@
+/*
+ * Skeleton egl.h to provide compatibility for early GLES 1.0
+ * applications. Several early implementations included gl.h
+ * in egl.h leading applications to include only egl.h
+ *
+ * $Revision: 6252 $ on $Date:: 2008-08-06 16:35:08 -0700 #$
+ */
+
+#ifndef __legacy_egl_h_
+#define __legacy_egl_h_
+
+#include <EGL/egl.h>
+#include <GLES/gl.h>
+
+#endif /* __legacy_egl_h_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES/gl.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,770 @@
+#ifndef __gl_h_
+#define __gl_h_
+
+/* $Revision: 10601 $ on $Date:: 2010-03-04 22:15:27 -0800 #$ */
+
+#include <GLES/glplatform.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+typedef void             GLvoid;
+typedef char             GLchar;
+typedef unsigned int     GLenum;
+typedef unsigned char    GLboolean;
+typedef unsigned int     GLbitfield;
+typedef khronos_int8_t   GLbyte;
+typedef short            GLshort;
+typedef int              GLint;
+typedef int              GLsizei;
+typedef khronos_uint8_t  GLubyte;
+typedef unsigned short   GLushort;
+typedef unsigned int     GLuint;
+typedef khronos_float_t  GLfloat;
+typedef khronos_float_t  GLclampf;
+typedef khronos_int32_t  GLfixed;
+typedef khronos_int32_t  GLclampx;
+
+typedef khronos_intptr_t GLintptr;
+typedef khronos_ssize_t  GLsizeiptr;
+
+
+/*************************************************************/
+
+/* OpenGL ES core versions */
+#define GL_VERSION_ES_CM_1_0          1
+#define GL_VERSION_ES_CL_1_0          1
+#define GL_VERSION_ES_CM_1_1          1
+#define GL_VERSION_ES_CL_1_1          1
+
+/* ClearBufferMask */
+#define GL_DEPTH_BUFFER_BIT               0x00000100
+#define GL_STENCIL_BUFFER_BIT             0x00000400
+#define GL_COLOR_BUFFER_BIT               0x00004000
+
+/* Boolean */
+#define GL_FALSE                          0
+#define GL_TRUE                           1
+
+/* BeginMode */
+#define GL_POINTS                         0x0000
+#define GL_LINES                          0x0001
+#define GL_LINE_LOOP                      0x0002
+#define GL_LINE_STRIP                     0x0003
+#define GL_TRIANGLES                      0x0004
+#define GL_TRIANGLE_STRIP                 0x0005
+#define GL_TRIANGLE_FAN                   0x0006
+
+/* AlphaFunction */
+#define GL_NEVER                          0x0200
+#define GL_LESS                           0x0201
+#define GL_EQUAL                          0x0202
+#define GL_LEQUAL                         0x0203
+#define GL_GREATER                        0x0204
+#define GL_NOTEQUAL                       0x0205
+#define GL_GEQUAL                         0x0206
+#define GL_ALWAYS                         0x0207
+
+/* BlendingFactorDest */
+#define GL_ZERO                           0
+#define GL_ONE                            1
+#define GL_SRC_COLOR                      0x0300
+#define GL_ONE_MINUS_SRC_COLOR            0x0301
+#define GL_SRC_ALPHA                      0x0302
+#define GL_ONE_MINUS_SRC_ALPHA            0x0303
+#define GL_DST_ALPHA                      0x0304
+#define GL_ONE_MINUS_DST_ALPHA            0x0305
+
+/* BlendingFactorSrc */
+/*      GL_ZERO */
+/*      GL_ONE */
+#define GL_DST_COLOR                      0x0306
+#define GL_ONE_MINUS_DST_COLOR            0x0307
+#define GL_SRC_ALPHA_SATURATE             0x0308
+/*      GL_SRC_ALPHA */
+/*      GL_ONE_MINUS_SRC_ALPHA */
+/*      GL_DST_ALPHA */
+/*      GL_ONE_MINUS_DST_ALPHA */
+
+/* ClipPlaneName */
+#define GL_CLIP_PLANE0                    0x3000
+#define GL_CLIP_PLANE1                    0x3001
+#define GL_CLIP_PLANE2                    0x3002
+#define GL_CLIP_PLANE3                    0x3003
+#define GL_CLIP_PLANE4                    0x3004
+#define GL_CLIP_PLANE5                    0x3005
+
+/* ColorMaterialFace */
+/*      GL_FRONT_AND_BACK */
+
+/* ColorMaterialParameter */
+/*      GL_AMBIENT_AND_DIFFUSE */
+
+/* ColorPointerType */
+/*      GL_UNSIGNED_BYTE */
+/*      GL_FLOAT */
+/*      GL_FIXED */
+
+/* CullFaceMode */
+#define GL_FRONT                          0x0404
+#define GL_BACK                           0x0405
+#define GL_FRONT_AND_BACK                 0x0408
+
+/* DepthFunction */
+/*      GL_NEVER */
+/*      GL_LESS */
+/*      GL_EQUAL */
+/*      GL_LEQUAL */
+/*      GL_GREATER */
+/*      GL_NOTEQUAL */
+/*      GL_GEQUAL */
+/*      GL_ALWAYS */
+
+/* EnableCap */
+#define GL_FOG                            0x0B60
+#define GL_LIGHTING                       0x0B50
+#define GL_TEXTURE_2D                     0x0DE1
+#define GL_CULL_FACE                      0x0B44
+#define GL_ALPHA_TEST                     0x0BC0
+#define GL_BLEND                          0x0BE2
+#define GL_COLOR_LOGIC_OP                 0x0BF2
+#define GL_DITHER                         0x0BD0
+#define GL_STENCIL_TEST                   0x0B90
+#define GL_DEPTH_TEST                     0x0B71
+/*      GL_LIGHT0 */
+/*      GL_LIGHT1 */
+/*      GL_LIGHT2 */
+/*      GL_LIGHT3 */
+/*      GL_LIGHT4 */
+/*      GL_LIGHT5 */
+/*      GL_LIGHT6 */
+/*      GL_LIGHT7 */
+#define GL_POINT_SMOOTH                   0x0B10
+#define GL_LINE_SMOOTH                    0x0B20
+#define GL_SCISSOR_TEST                   0x0C11
+#define GL_COLOR_MATERIAL                 0x0B57
+#define GL_NORMALIZE                      0x0BA1
+#define GL_RESCALE_NORMAL                 0x803A
+#define GL_POLYGON_OFFSET_FILL            0x8037
+#define GL_VERTEX_ARRAY                   0x8074
+#define GL_NORMAL_ARRAY                   0x8075
+#define GL_COLOR_ARRAY                    0x8076
+#define GL_TEXTURE_COORD_ARRAY            0x8078
+#define GL_MULTISAMPLE                    0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE            0x809F
+#define GL_SAMPLE_COVERAGE                0x80A0
+
+/* ErrorCode */
+#define GL_NO_ERROR                       0
+#define GL_INVALID_ENUM                   0x0500
+#define GL_INVALID_VALUE                  0x0501
+#define GL_INVALID_OPERATION              0x0502
+#define GL_STACK_OVERFLOW                 0x0503
+#define GL_STACK_UNDERFLOW                0x0504
+#define GL_OUT_OF_MEMORY                  0x0505
+
+/* FogMode */
+/*      GL_LINEAR */
+#define GL_EXP                            0x0800
+#define GL_EXP2                           0x0801
+
+/* FogParameter */
+#define GL_FOG_DENSITY                    0x0B62
+#define GL_FOG_START                      0x0B63
+#define GL_FOG_END                        0x0B64
+#define GL_FOG_MODE                       0x0B65
+#define GL_FOG_COLOR                      0x0B66
+
+/* FrontFaceDirection */
+#define GL_CW                             0x0900
+#define GL_CCW                            0x0901
+
+/* GetPName */
+#define GL_CURRENT_COLOR                  0x0B00
+#define GL_CURRENT_NORMAL                 0x0B02
+#define GL_CURRENT_TEXTURE_COORDS         0x0B03
+#define GL_POINT_SIZE                     0x0B11
+#define GL_POINT_SIZE_MIN                 0x8126
+#define GL_POINT_SIZE_MAX                 0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE      0x8128
+#define GL_POINT_DISTANCE_ATTENUATION     0x8129
+#define GL_SMOOTH_POINT_SIZE_RANGE        0x0B12
+#define GL_LINE_WIDTH                     0x0B21
+#define GL_SMOOTH_LINE_WIDTH_RANGE        0x0B22
+#define GL_ALIASED_POINT_SIZE_RANGE       0x846D
+#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E
+#define GL_CULL_FACE_MODE                 0x0B45
+#define GL_FRONT_FACE                     0x0B46
+#define GL_SHADE_MODEL                    0x0B54
+#define GL_DEPTH_RANGE                    0x0B70
+#define GL_DEPTH_WRITEMASK                0x0B72
+#define GL_DEPTH_CLEAR_VALUE              0x0B73
+#define GL_DEPTH_FUNC                     0x0B74
+#define GL_STENCIL_CLEAR_VALUE            0x0B91
+#define GL_STENCIL_FUNC                   0x0B92
+#define GL_STENCIL_VALUE_MASK             0x0B93
+#define GL_STENCIL_FAIL                   0x0B94
+#define GL_STENCIL_PASS_DEPTH_FAIL        0x0B95
+#define GL_STENCIL_PASS_DEPTH_PASS        0x0B96
+#define GL_STENCIL_REF                    0x0B97
+#define GL_STENCIL_WRITEMASK              0x0B98
+#define GL_MATRIX_MODE                    0x0BA0
+#define GL_VIEWPORT                       0x0BA2
+#define GL_MODELVIEW_STACK_DEPTH          0x0BA3
+#define GL_PROJECTION_STACK_DEPTH         0x0BA4
+#define GL_TEXTURE_STACK_DEPTH            0x0BA5
+#define GL_MODELVIEW_MATRIX               0x0BA6
+#define GL_PROJECTION_MATRIX              0x0BA7
+#define GL_TEXTURE_MATRIX                 0x0BA8
+#define GL_ALPHA_TEST_FUNC                0x0BC1
+#define GL_ALPHA_TEST_REF                 0x0BC2
+#define GL_BLEND_DST                      0x0BE0
+#define GL_BLEND_SRC                      0x0BE1
+#define GL_LOGIC_OP_MODE                  0x0BF0
+#define GL_SCISSOR_BOX                    0x0C10
+#define GL_SCISSOR_TEST                   0x0C11
+#define GL_COLOR_CLEAR_VALUE              0x0C22
+#define GL_COLOR_WRITEMASK                0x0C23
+#define GL_UNPACK_ALIGNMENT               0x0CF5
+#define GL_PACK_ALIGNMENT                 0x0D05
+#define GL_MAX_LIGHTS                     0x0D31
+#define GL_MAX_CLIP_PLANES                0x0D32
+#define GL_MAX_TEXTURE_SIZE               0x0D33
+#define GL_MAX_MODELVIEW_STACK_DEPTH      0x0D36
+#define GL_MAX_PROJECTION_STACK_DEPTH     0x0D38
+#define GL_MAX_TEXTURE_STACK_DEPTH        0x0D39
+#define GL_MAX_VIEWPORT_DIMS              0x0D3A
+#define GL_MAX_TEXTURE_UNITS              0x84E2
+#define GL_SUBPIXEL_BITS                  0x0D50
+#define GL_RED_BITS                       0x0D52
+#define GL_GREEN_BITS                     0x0D53
+#define GL_BLUE_BITS                      0x0D54
+#define GL_ALPHA_BITS                     0x0D55
+#define GL_DEPTH_BITS                     0x0D56
+#define GL_STENCIL_BITS                   0x0D57
+#define GL_POLYGON_OFFSET_UNITS           0x2A00
+#define GL_POLYGON_OFFSET_FILL            0x8037
+#define GL_POLYGON_OFFSET_FACTOR          0x8038
+#define GL_TEXTURE_BINDING_2D             0x8069
+#define GL_VERTEX_ARRAY_SIZE              0x807A
+#define GL_VERTEX_ARRAY_TYPE              0x807B
+#define GL_VERTEX_ARRAY_STRIDE            0x807C
+#define GL_NORMAL_ARRAY_TYPE              0x807E
+#define GL_NORMAL_ARRAY_STRIDE            0x807F
+#define GL_COLOR_ARRAY_SIZE               0x8081
+#define GL_COLOR_ARRAY_TYPE               0x8082
+#define GL_COLOR_ARRAY_STRIDE             0x8083
+#define GL_TEXTURE_COORD_ARRAY_SIZE       0x8088
+#define GL_TEXTURE_COORD_ARRAY_TYPE       0x8089
+#define GL_TEXTURE_COORD_ARRAY_STRIDE     0x808A
+#define GL_VERTEX_ARRAY_POINTER           0x808E
+#define GL_NORMAL_ARRAY_POINTER           0x808F
+#define GL_COLOR_ARRAY_POINTER            0x8090
+#define GL_TEXTURE_COORD_ARRAY_POINTER    0x8092
+#define GL_SAMPLE_BUFFERS                 0x80A8
+#define GL_SAMPLES                        0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE          0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT         0x80AB
+
+/* GetTextureParameter */
+/*      GL_TEXTURE_MAG_FILTER */
+/*      GL_TEXTURE_MIN_FILTER */
+/*      GL_TEXTURE_WRAP_S */
+/*      GL_TEXTURE_WRAP_T */
+
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3
+
+/* HintMode */
+#define GL_DONT_CARE                      0x1100
+#define GL_FASTEST                        0x1101
+#define GL_NICEST                         0x1102
+
+/* HintTarget */
+#define GL_PERSPECTIVE_CORRECTION_HINT    0x0C50
+#define GL_POINT_SMOOTH_HINT              0x0C51
+#define GL_LINE_SMOOTH_HINT               0x0C52
+#define GL_FOG_HINT                       0x0C54
+#define GL_GENERATE_MIPMAP_HINT           0x8192
+
+/* LightModelParameter */
+#define GL_LIGHT_MODEL_AMBIENT            0x0B53
+#define GL_LIGHT_MODEL_TWO_SIDE           0x0B52
+
+/* LightParameter */
+#define GL_AMBIENT                        0x1200
+#define GL_DIFFUSE                        0x1201
+#define GL_SPECULAR                       0x1202
+#define GL_POSITION                       0x1203
+#define GL_SPOT_DIRECTION                 0x1204
+#define GL_SPOT_EXPONENT                  0x1205
+#define GL_SPOT_CUTOFF                    0x1206
+#define GL_CONSTANT_ATTENUATION           0x1207
+#define GL_LINEAR_ATTENUATION             0x1208
+#define GL_QUADRATIC_ATTENUATION          0x1209
+
+/* DataType */
+#define GL_BYTE                           0x1400
+#define GL_UNSIGNED_BYTE                  0x1401
+#define GL_SHORT                          0x1402
+#define GL_UNSIGNED_SHORT                 0x1403
+#define GL_FLOAT                          0x1406
+#define GL_FIXED                          0x140C
+
+/* LogicOp */
+#define GL_CLEAR                          0x1500
+#define GL_AND                            0x1501
+#define GL_AND_REVERSE                    0x1502
+#define GL_COPY                           0x1503
+#define GL_AND_INVERTED                   0x1504
+#define GL_NOOP                           0x1505
+#define GL_XOR                            0x1506
+#define GL_OR                             0x1507
+#define GL_NOR                            0x1508
+#define GL_EQUIV                          0x1509
+#define GL_INVERT                         0x150A
+#define GL_OR_REVERSE                     0x150B
+#define GL_COPY_INVERTED                  0x150C
+#define GL_OR_INVERTED                    0x150D
+#define GL_NAND                           0x150E
+#define GL_SET                            0x150F
+
+/* MaterialFace */
+/*      GL_FRONT_AND_BACK */
+
+/* MaterialParameter */
+#define GL_EMISSION                       0x1600
+#define GL_SHININESS                      0x1601
+#define GL_AMBIENT_AND_DIFFUSE            0x1602
+/*      GL_AMBIENT */
+/*      GL_DIFFUSE */
+/*      GL_SPECULAR */
+
+/* MatrixMode */
+#define GL_MODELVIEW                      0x1700
+#define GL_PROJECTION                     0x1701
+#define GL_TEXTURE                        0x1702
+
+/* NormalPointerType */
+/*      GL_BYTE */
+/*      GL_SHORT */
+/*      GL_FLOAT */
+/*      GL_FIXED */
+
+/* PixelFormat */
+#define GL_ALPHA                          0x1906
+#define GL_RGB                            0x1907
+#define GL_RGBA                           0x1908
+#define GL_LUMINANCE                      0x1909
+#define GL_LUMINANCE_ALPHA                0x190A
+
+/* PixelStoreParameter */
+#define GL_UNPACK_ALIGNMENT               0x0CF5
+#define GL_PACK_ALIGNMENT                 0x0D05
+
+/* PixelType */
+/*      GL_UNSIGNED_BYTE */
+#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034
+#define GL_UNSIGNED_SHORT_5_6_5           0x8363
+
+/* ShadingModel */
+#define GL_FLAT                           0x1D00
+#define GL_SMOOTH                         0x1D01
+
+/* StencilFunction */
+/*      GL_NEVER */
+/*      GL_LESS */
+/*      GL_EQUAL */
+/*      GL_LEQUAL */
+/*      GL_GREATER */
+/*      GL_NOTEQUAL */
+/*      GL_GEQUAL */
+/*      GL_ALWAYS */
+
+/* StencilOp */
+/*      GL_ZERO */
+#define GL_KEEP                           0x1E00
+#define GL_REPLACE                        0x1E01
+#define GL_INCR                           0x1E02
+#define GL_DECR                           0x1E03
+/*      GL_INVERT */
+
+/* StringName */
+#define GL_VENDOR                         0x1F00
+#define GL_RENDERER                       0x1F01
+#define GL_VERSION                        0x1F02
+#define GL_EXTENSIONS                     0x1F03
+
+/* TexCoordPointerType */
+/*      GL_SHORT */
+/*      GL_FLOAT */
+/*      GL_FIXED */
+/*      GL_BYTE */
+
+/* TextureEnvMode */
+#define GL_MODULATE                       0x2100
+#define GL_DECAL                          0x2101
+/*      GL_BLEND */
+#define GL_ADD                            0x0104
+/*      GL_REPLACE */
+
+/* TextureEnvParameter */
+#define GL_TEXTURE_ENV_MODE               0x2200
+#define GL_TEXTURE_ENV_COLOR              0x2201
+
+/* TextureEnvTarget */
+#define GL_TEXTURE_ENV                    0x2300
+
+/* TextureMagFilter */
+#define GL_NEAREST                        0x2600
+#define GL_LINEAR                         0x2601
+
+/* TextureMinFilter */
+/*      GL_NEAREST */
+/*      GL_LINEAR */
+#define GL_NEAREST_MIPMAP_NEAREST         0x2700
+#define GL_LINEAR_MIPMAP_NEAREST          0x2701
+#define GL_NEAREST_MIPMAP_LINEAR          0x2702
+#define GL_LINEAR_MIPMAP_LINEAR           0x2703
+
+/* TextureParameterName */
+#define GL_TEXTURE_MAG_FILTER             0x2800
+#define GL_TEXTURE_MIN_FILTER             0x2801
+#define GL_TEXTURE_WRAP_S                 0x2802
+#define GL_TEXTURE_WRAP_T                 0x2803
+#define GL_GENERATE_MIPMAP                0x8191
+
+/* TextureTarget */
+/*      GL_TEXTURE_2D */
+
+/* TextureUnit */
+#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_CLIENT_ACTIVE_TEXTURE          0x84E1
+
+/* TextureWrapMode */
+#define GL_REPEAT                         0x2901
+#define GL_CLAMP_TO_EDGE                  0x812F
+
+/* VertexPointerType */
+/*      GL_SHORT */
+/*      GL_FLOAT */
+/*      GL_FIXED */
+/*      GL_BYTE */
+
+/* LightName */
+#define GL_LIGHT0                         0x4000
+#define GL_LIGHT1                         0x4001
+#define GL_LIGHT2                         0x4002
+#define GL_LIGHT3                         0x4003
+#define GL_LIGHT4                         0x4004
+#define GL_LIGHT5                         0x4005
+#define GL_LIGHT6                         0x4006
+#define GL_LIGHT7                         0x4007
+
+/* Buffer Objects */
+#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_ARRAY_BUFFER_BINDING        0x8896
+#define GL_NORMAL_ARRAY_BUFFER_BINDING        0x8897
+#define GL_COLOR_ARRAY_BUFFER_BINDING         0x8898
+#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A
+
+#define GL_STATIC_DRAW                    0x88E4
+#define GL_DYNAMIC_DRAW                   0x88E8
+
+#define GL_BUFFER_SIZE                    0x8764
+#define GL_BUFFER_USAGE                   0x8765
+
+/* Texture combine + dot3 */
+#define GL_SUBTRACT                       0x84E7
+#define GL_COMBINE                        0x8570
+#define GL_COMBINE_RGB                    0x8571
+#define GL_COMBINE_ALPHA                  0x8572
+#define GL_RGB_SCALE                      0x8573
+#define GL_ADD_SIGNED                     0x8574
+#define GL_INTERPOLATE                    0x8575
+#define GL_CONSTANT                       0x8576
+#define GL_PRIMARY_COLOR                  0x8577
+#define GL_PREVIOUS                       0x8578
+#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_ALPHA_SCALE                    0x0D1C
+
+#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
+
+#define GL_DOT3_RGB                       0x86AE
+#define GL_DOT3_RGBA                      0x86AF
+
+/*------------------------------------------------------------------------*
+ * required OES extension tokens
+ *------------------------------------------------------------------------*/
+
+/* OES_read_format */
+#ifndef GL_OES_read_format
+#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES                   0x8B9A
+#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES                 0x8B9B
+#endif
+
+/* GL_OES_compressed_paletted_texture */
+#ifndef GL_OES_compressed_paletted_texture
+#define GL_PALETTE4_RGB8_OES                                    0x8B90
+#define GL_PALETTE4_RGBA8_OES                                   0x8B91
+#define GL_PALETTE4_R5_G6_B5_OES                                0x8B92
+#define GL_PALETTE4_RGBA4_OES                                   0x8B93
+#define GL_PALETTE4_RGB5_A1_OES                                 0x8B94
+#define GL_PALETTE8_RGB8_OES                                    0x8B95
+#define GL_PALETTE8_RGBA8_OES                                   0x8B96
+#define GL_PALETTE8_R5_G6_B5_OES                                0x8B97
+#define GL_PALETTE8_RGBA4_OES                                   0x8B98
+#define GL_PALETTE8_RGB5_A1_OES                                 0x8B99
+#endif
+
+/* OES_point_size_array */
+#ifndef GL_OES_point_size_array
+#define GL_POINT_SIZE_ARRAY_OES                                 0x8B9C
+#define GL_POINT_SIZE_ARRAY_TYPE_OES                            0x898A
+#define GL_POINT_SIZE_ARRAY_STRIDE_OES                          0x898B
+#define GL_POINT_SIZE_ARRAY_POINTER_OES                         0x898C
+#define GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES                  0x8B9F
+#endif
+
+/* GL_OES_point_sprite */
+#ifndef GL_OES_point_sprite
+#define GL_POINT_SPRITE_OES                                     0x8861
+#define GL_COORD_REPLACE_OES                                    0x8862
+#endif
+
+/*************************************************************/
+
+/* Available only in Common profile */
+GL_API void GL_APIENTRY glAlphaFunc (GLenum func, GLclampf ref);
+GL_API void GL_APIENTRY glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+GL_API void GL_APIENTRY glClearDepthf (GLclampf depth);
+GL_API void GL_APIENTRY glClipPlanef (GLenum plane, const GLfloat *equation);
+GL_API void GL_APIENTRY glColor4f (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+GL_API void GL_APIENTRY glDepthRangef (GLclampf zNear, GLclampf zFar);
+GL_API void GL_APIENTRY glFogf (GLenum pname, GLfloat param);
+GL_API void GL_APIENTRY glFogfv (GLenum pname, const GLfloat *params);
+GL_API void GL_APIENTRY glFrustumf (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar);
+GL_API void GL_APIENTRY glGetClipPlanef (GLenum pname, GLfloat eqn[4]);
+GL_API void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat *params);
+GL_API void GL_APIENTRY glGetLightfv (GLenum light, GLenum pname, GLfloat *params);
+GL_API void GL_APIENTRY glGetMaterialfv (GLenum face, GLenum pname, GLfloat *params);
+GL_API void GL_APIENTRY glGetTexEnvfv (GLenum env, GLenum pname, GLfloat *params);
+GL_API void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params);
+GL_API void GL_APIENTRY glLightModelf (GLenum pname, GLfloat param);
+GL_API void GL_APIENTRY glLightModelfv (GLenum pname, const GLfloat *params);
+GL_API void GL_APIENTRY glLightf (GLenum light, GLenum pname, GLfloat param);
+GL_API void GL_APIENTRY glLightfv (GLenum light, GLenum pname, const GLfloat *params);
+GL_API void GL_APIENTRY glLineWidth (GLfloat width);
+GL_API void GL_APIENTRY glLoadMatrixf (const GLfloat *m);
+GL_API void GL_APIENTRY glMaterialf (GLenum face, GLenum pname, GLfloat param);
+GL_API void GL_APIENTRY glMaterialfv (GLenum face, GLenum pname, const GLfloat *params);
+GL_API void GL_APIENTRY glMultMatrixf (const GLfloat *m);
+GL_API void GL_APIENTRY glMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+GL_API void GL_APIENTRY glNormal3f (GLfloat nx, GLfloat ny, GLfloat nz);
+GL_API void GL_APIENTRY glOrthof (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar);
+GL_API void GL_APIENTRY glPointParameterf (GLenum pname, GLfloat param);
+GL_API void GL_APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params);
+GL_API void GL_APIENTRY glPointSize (GLfloat size);
+GL_API void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units);
+GL_API void GL_APIENTRY glRotatef (GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+GL_API void GL_APIENTRY glScalef (GLfloat x, GLfloat y, GLfloat z);
+GL_API void GL_APIENTRY glTexEnvf (GLenum target, GLenum pname, GLfloat param);
+GL_API void GL_APIENTRY glTexEnvfv (GLenum target, GLenum pname, const GLfloat *params);
+GL_API void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param);
+GL_API void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params);
+GL_API void GL_APIENTRY glTranslatef (GLfloat x, GLfloat y, GLfloat z);
+
+/* Available in both Common and Common-Lite profiles */
+GL_API void GL_APIENTRY glActiveTexture (GLenum texture);
+GL_API void GL_APIENTRY glAlphaFuncx (GLenum func, GLclampx ref);
+GL_API void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer);
+GL_API void GL_APIENTRY glBindTexture (GLenum target, GLuint texture);
+GL_API void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor);
+GL_API void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
+GL_API void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+GL_API void GL_APIENTRY glClear (GLbitfield mask);
+GL_API void GL_APIENTRY glClearColorx (GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha);
+GL_API void GL_APIENTRY glClearDepthx (GLclampx depth);
+GL_API void GL_APIENTRY glClearStencil (GLint s);
+GL_API void GL_APIENTRY glClientActiveTexture (GLenum texture);
+GL_API void GL_APIENTRY glClipPlanex (GLenum plane, const GLfixed *equation);
+GL_API void GL_APIENTRY glColor4ub (GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+GL_API void GL_APIENTRY glColor4x (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);
+GL_API void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+GL_API void GL_APIENTRY glColorPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GL_API void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+GL_API void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+GL_API void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+GL_API void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GL_API void GL_APIENTRY glCullFace (GLenum mode);
+GL_API void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
+GL_API void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
+GL_API void GL_APIENTRY glDepthFunc (GLenum func);
+GL_API void GL_APIENTRY glDepthMask (GLboolean flag);
+GL_API void GL_APIENTRY glDepthRangex (GLclampx zNear, GLclampx zFar);
+GL_API void GL_APIENTRY glDisable (GLenum cap);
+GL_API void GL_APIENTRY glDisableClientState (GLenum array);
+GL_API void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count);
+GL_API void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+GL_API void GL_APIENTRY glEnable (GLenum cap);
+GL_API void GL_APIENTRY glEnableClientState (GLenum array);
+GL_API void GL_APIENTRY glFinish (void);
+GL_API void GL_APIENTRY glFlush (void);
+GL_API void GL_APIENTRY glFogx (GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glFogxv (GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glFrontFace (GLenum mode);
+GL_API void GL_APIENTRY glFrustumx (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar);
+GL_API void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean *params);
+GL_API void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params);
+GL_API void GL_APIENTRY glGetClipPlanex (GLenum pname, GLfixed eqn[4]);
+GL_API void GL_APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
+GL_API void GL_APIENTRY glGenTextures (GLsizei n, GLuint *textures);
+GL_API GLenum GL_APIENTRY glGetError (void);
+GL_API void GL_APIENTRY glGetFixedv (GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glGetIntegerv (GLenum pname, GLint *params);
+GL_API void GL_APIENTRY glGetLightxv (GLenum light, GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glGetMaterialxv (GLenum face, GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glGetPointerv (GLenum pname, GLvoid **params);
+GL_API const GLubyte * GL_APIENTRY glGetString (GLenum name);
+GL_API void GL_APIENTRY glGetTexEnviv (GLenum env, GLenum pname, GLint *params);
+GL_API void GL_APIENTRY glGetTexEnvxv (GLenum env, GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params);
+GL_API void GL_APIENTRY glGetTexParameterxv (GLenum target, GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glHint (GLenum target, GLenum mode);
+GL_API GLboolean GL_APIENTRY glIsBuffer (GLuint buffer);
+GL_API GLboolean GL_APIENTRY glIsEnabled (GLenum cap);
+GL_API GLboolean GL_APIENTRY glIsTexture (GLuint texture);
+GL_API void GL_APIENTRY glLightModelx (GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glLightModelxv (GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glLightx (GLenum light, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glLightxv (GLenum light, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glLineWidthx (GLfixed width);
+GL_API void GL_APIENTRY glLoadIdentity (void);
+GL_API void GL_APIENTRY glLoadMatrixx (const GLfixed *m);
+GL_API void GL_APIENTRY glLogicOp (GLenum opcode);
+GL_API void GL_APIENTRY glMaterialx (GLenum face, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glMaterialxv (GLenum face, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glMatrixMode (GLenum mode);
+GL_API void GL_APIENTRY glMultMatrixx (const GLfixed *m);
+GL_API void GL_APIENTRY glMultiTexCoord4x (GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q);
+GL_API void GL_APIENTRY glNormal3x (GLfixed nx, GLfixed ny, GLfixed nz);
+GL_API void GL_APIENTRY glNormalPointer (GLenum type, GLsizei stride, const GLvoid *pointer);
+GL_API void GL_APIENTRY glOrthox (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar);
+GL_API void GL_APIENTRY glPixelStorei (GLenum pname, GLint param);
+GL_API void GL_APIENTRY glPointParameterx (GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glPointParameterxv (GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glPointSizex (GLfixed size);
+GL_API void GL_APIENTRY glPolygonOffsetx (GLfixed factor, GLfixed units);
+GL_API void GL_APIENTRY glPopMatrix (void);
+GL_API void GL_APIENTRY glPushMatrix (void);
+GL_API void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+GL_API void GL_APIENTRY glRotatex (GLfixed angle, GLfixed x, GLfixed y, GLfixed z);
+GL_API void GL_APIENTRY glSampleCoverage (GLclampf value, GLboolean invert);
+GL_API void GL_APIENTRY glSampleCoveragex (GLclampx value, GLboolean invert);
+GL_API void GL_APIENTRY glScalex (GLfixed x, GLfixed y, GLfixed z);
+GL_API void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
+GL_API void GL_APIENTRY glShadeModel (GLenum mode);
+GL_API void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask);
+GL_API void GL_APIENTRY glStencilMask (GLuint mask);
+GL_API void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass);
+GL_API void GL_APIENTRY glTexCoordPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GL_API void GL_APIENTRY glTexEnvi (GLenum target, GLenum pname, GLint param);
+GL_API void GL_APIENTRY glTexEnvx (GLenum target, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glTexEnviv (GLenum target, GLenum pname, const GLint *params);
+GL_API void GL_APIENTRY glTexEnvxv (GLenum target, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GL_API void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
+GL_API void GL_APIENTRY glTexParameterx (GLenum target, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params);
+GL_API void GL_APIENTRY glTexParameterxv (GLenum target, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+GL_API void GL_APIENTRY glTranslatex (GLfixed x, GLfixed y, GLfixed z);
+GL_API void GL_APIENTRY glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GL_API void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
+
+/*------------------------------------------------------------------------*
+ * Required OES extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_OES_read_format */
+#ifndef GL_OES_read_format
+#define GL_OES_read_format 1
+#endif
+
+/* GL_OES_compressed_paletted_texture */
+#ifndef GL_OES_compressed_paletted_texture
+#define GL_OES_compressed_paletted_texture 1
+#endif
+
+/* GL_OES_point_size_array */
+#ifndef GL_OES_point_size_array
+#define GL_OES_point_size_array 1
+GL_API void GL_APIENTRY glPointSizePointerOES (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+/* GL_OES_point_sprite */
+#ifndef GL_OES_point_sprite
+#define GL_OES_point_sprite 1
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gl_h_ */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES/glext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,935 @@
+#ifndef __glext_h_
+#define __glext_h_
+
+/* $Revision: 10601 $ on $Date:: 2010-03-04 22:15:27 -0800 #$ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+#ifndef GL_APIENTRYP
+#   define GL_APIENTRYP GL_APIENTRY*
+#endif
+
+/*------------------------------------------------------------------------*
+ * OES extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_OES_blend_equation_separate */
+#ifndef GL_OES_blend_equation_separate
+/* BLEND_EQUATION_RGB_OES same as BLEND_EQUATION_OES */
+#define GL_BLEND_EQUATION_RGB_OES                               0x8009
+#define GL_BLEND_EQUATION_ALPHA_OES                             0x883D
+#endif
+
+/* GL_OES_blend_func_separate */
+#ifndef GL_OES_blend_func_separate
+#define GL_BLEND_DST_RGB_OES                                    0x80C8
+#define GL_BLEND_SRC_RGB_OES                                    0x80C9
+#define GL_BLEND_DST_ALPHA_OES                                  0x80CA
+#define GL_BLEND_SRC_ALPHA_OES                                  0x80CB
+#endif
+
+/* GL_OES_blend_subtract */
+#ifndef GL_OES_blend_subtract
+#define GL_BLEND_EQUATION_OES                                   0x8009
+#define GL_FUNC_ADD_OES                                         0x8006
+#define GL_FUNC_SUBTRACT_OES                                    0x800A
+#define GL_FUNC_REVERSE_SUBTRACT_OES                            0x800B
+#endif
+
+/* GL_OES_compressed_ETC1_RGB8_texture */
+#ifndef GL_OES_compressed_ETC1_RGB8_texture
+#define GL_ETC1_RGB8_OES                                        0x8D64
+#endif
+
+/* GL_OES_depth24 */
+#ifndef GL_OES_depth24
+#define GL_DEPTH_COMPONENT24_OES                                0x81A6
+#endif
+
+/* GL_OES_depth32 */
+#ifndef GL_OES_depth32
+#define GL_DEPTH_COMPONENT32_OES                                0x81A7
+#endif
+
+/* GL_OES_draw_texture */
+#ifndef GL_OES_draw_texture
+#define GL_TEXTURE_CROP_RECT_OES                                0x8B9D
+#endif
+
+/* GL_OES_EGL_image */
+#ifndef GL_OES_EGL_image
+typedef void* GLeglImageOES;
+#endif
+
+/* GL_OES_element_index_uint */
+#ifndef GL_OES_element_index_uint
+#define GL_UNSIGNED_INT                                         0x1405
+#endif
+
+/* GL_OES_fixed_point */
+#ifndef GL_OES_fixed_point
+#define GL_FIXED_OES                                            0x140C
+#endif
+
+/* GL_OES_framebuffer_object */
+#ifndef GL_OES_framebuffer_object
+#define GL_NONE_OES                                             0
+#define GL_FRAMEBUFFER_OES                                      0x8D40
+#define GL_RENDERBUFFER_OES                                     0x8D41
+#define GL_RGBA4_OES                                            0x8056
+#define GL_RGB5_A1_OES                                          0x8057
+#define GL_RGB565_OES                                           0x8D62
+#define GL_DEPTH_COMPONENT16_OES                                0x81A5
+#define GL_RENDERBUFFER_WIDTH_OES                               0x8D42
+#define GL_RENDERBUFFER_HEIGHT_OES                              0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT_OES                     0x8D44
+#define GL_RENDERBUFFER_RED_SIZE_OES                            0x8D50
+#define GL_RENDERBUFFER_GREEN_SIZE_OES                          0x8D51
+#define GL_RENDERBUFFER_BLUE_SIZE_OES                           0x8D52
+#define GL_RENDERBUFFER_ALPHA_SIZE_OES                          0x8D53
+#define GL_RENDERBUFFER_DEPTH_SIZE_OES                          0x8D54
+#define GL_RENDERBUFFER_STENCIL_SIZE_OES                        0x8D55
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES               0x8CD0
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES               0x8CD1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES             0x8CD2
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES     0x8CD3
+#define GL_COLOR_ATTACHMENT0_OES                                0x8CE0
+#define GL_DEPTH_ATTACHMENT_OES                                 0x8D00
+#define GL_STENCIL_ATTACHMENT_OES                               0x8D20
+#define GL_FRAMEBUFFER_COMPLETE_OES                             0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES                0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES        0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES                0x8CD9
+#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES                   0x8CDA
+#define GL_FRAMEBUFFER_UNSUPPORTED_OES                          0x8CDD
+#define GL_FRAMEBUFFER_BINDING_OES                              0x8CA6
+#define GL_RENDERBUFFER_BINDING_OES                             0x8CA7
+#define GL_MAX_RENDERBUFFER_SIZE_OES                            0x84E8
+#define GL_INVALID_FRAMEBUFFER_OPERATION_OES                    0x0506
+#endif
+
+/* GL_OES_mapbuffer */
+#ifndef GL_OES_mapbuffer
+#define GL_WRITE_ONLY_OES                                       0x88B9
+#define GL_BUFFER_ACCESS_OES                                    0x88BB
+#define GL_BUFFER_MAPPED_OES                                    0x88BC
+#define GL_BUFFER_MAP_POINTER_OES                               0x88BD
+#endif
+
+/* GL_OES_matrix_get */
+#ifndef GL_OES_matrix_get
+#define GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES               0x898D
+#define GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES              0x898E
+#define GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES                 0x898F
+#endif
+
+/* GL_OES_matrix_palette */
+#ifndef GL_OES_matrix_palette
+#define GL_MAX_VERTEX_UNITS_OES                                 0x86A4
+#define GL_MAX_PALETTE_MATRICES_OES                             0x8842
+#define GL_MATRIX_PALETTE_OES                                   0x8840
+#define GL_MATRIX_INDEX_ARRAY_OES                               0x8844
+#define GL_WEIGHT_ARRAY_OES                                     0x86AD
+#define GL_CURRENT_PALETTE_MATRIX_OES                           0x8843
+#define GL_MATRIX_INDEX_ARRAY_SIZE_OES                          0x8846
+#define GL_MATRIX_INDEX_ARRAY_TYPE_OES                          0x8847
+#define GL_MATRIX_INDEX_ARRAY_STRIDE_OES                        0x8848
+#define GL_MATRIX_INDEX_ARRAY_POINTER_OES                       0x8849
+#define GL_MATRIX_INDEX_ARRAY_BUFFER_BINDING_OES                0x8B9E
+#define GL_WEIGHT_ARRAY_SIZE_OES                                0x86AB
+#define GL_WEIGHT_ARRAY_TYPE_OES                                0x86A9
+#define GL_WEIGHT_ARRAY_STRIDE_OES                              0x86AA
+#define GL_WEIGHT_ARRAY_POINTER_OES                             0x86AC
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING_OES                      0x889E
+#endif
+
+/* GL_OES_packed_depth_stencil */
+#ifndef GL_OES_packed_depth_stencil
+#define GL_DEPTH_STENCIL_OES                                    0x84F9
+#define GL_UNSIGNED_INT_24_8_OES                                0x84FA
+#define GL_DEPTH24_STENCIL8_OES                                 0x88F0
+#endif
+
+/* GL_OES_rgb8_rgba8 */
+#ifndef GL_OES_rgb8_rgba8
+#define GL_RGB8_OES                                             0x8051
+#define GL_RGBA8_OES                                            0x8058
+#endif
+
+/* GL_OES_stencil1 */
+#ifndef GL_OES_stencil1
+#define GL_STENCIL_INDEX1_OES                                   0x8D46
+#endif
+
+/* GL_OES_stencil4 */
+#ifndef GL_OES_stencil4
+#define GL_STENCIL_INDEX4_OES                                   0x8D47
+#endif
+
+/* GL_OES_stencil8 */
+#ifndef GL_OES_stencil8
+#define GL_STENCIL_INDEX8_OES                                   0x8D48
+#endif
+
+/* GL_OES_stencil_wrap */
+#ifndef GL_OES_stencil_wrap
+#define GL_INCR_WRAP_OES                                        0x8507
+#define GL_DECR_WRAP_OES                                        0x8508
+#endif
+
+/* GL_OES_texture_cube_map */
+#ifndef GL_OES_texture_cube_map
+#define GL_NORMAL_MAP_OES                                       0x8511
+#define GL_REFLECTION_MAP_OES                                   0x8512
+#define GL_TEXTURE_CUBE_MAP_OES                                 0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP_OES                         0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_OES                      0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_OES                      0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_OES                      0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_OES                      0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_OES                      0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_OES                      0x851A
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_OES                        0x851C
+#define GL_TEXTURE_GEN_MODE_OES                                 0x2500
+#define GL_TEXTURE_GEN_STR_OES                                  0x8D60
+#endif
+
+/* GL_OES_texture_mirrored_repeat */
+#ifndef GL_OES_texture_mirrored_repeat
+#define GL_MIRRORED_REPEAT_OES                                  0x8370
+#endif
+
+/* GL_OES_vertex_array_object */
+#ifndef GL_OES_vertex_array_object
+#define GL_VERTEX_ARRAY_BINDING_OES                             0x85B5
+#endif
+
+/*------------------------------------------------------------------------*
+ * AMD extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_AMD_compressed_3DC_texture */
+#ifndef GL_AMD_compressed_3DC_texture
+#define GL_3DC_X_AMD                                            0x87F9
+#define GL_3DC_XY_AMD                                           0x87FA
+#endif
+
+/* GL_AMD_compressed_ATC_texture */
+#ifndef GL_AMD_compressed_ATC_texture
+#define GL_ATC_RGB_AMD                                          0x8C92
+#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD                          0x8C93
+#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD                      0x87EE
+#endif
+
+/*------------------------------------------------------------------------*
+ * APPLE extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_APPLE_texture_2D_limited_npot */
+/* No new tokens introduced by this extension. */
+
+/*------------------------------------------------------------------------*
+ * EXT extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_EXT_blend_minmax */
+#ifndef GL_EXT_blend_minmax
+#define GL_MIN_EXT                                              0x8007
+#define GL_MAX_EXT                                              0x8008
+#endif
+
+/* GL_EXT_discard_framebuffer */
+#ifndef GL_EXT_discard_framebuffer
+#define GL_COLOR_EXT                                            0x1800
+#define GL_DEPTH_EXT                                            0x1801
+#define GL_STENCIL_EXT                                          0x1802
+#endif
+
+/* GL_EXT_multi_draw_arrays */
+/* No new tokens introduced by this extension. */
+
+/* GL_EXT_read_format_bgra */
+#ifndef GL_EXT_read_format_bgra
+#define GL_BGRA_EXT                                             0x80E1
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT                       0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT                       0x8366
+#endif
+
+/* GL_EXT_texture_filter_anisotropic */
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT                           0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT                       0x84FF
+#endif
+
+/* GL_EXT_texture_format_BGRA8888 */
+#ifndef GL_EXT_texture_format_BGRA8888
+#define GL_BGRA_EXT                                             0x80E1
+#endif
+
+/* GL_EXT_texture_lod_bias */
+#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
+
+/*------------------------------------------------------------------------*
+ * IMG extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_IMG_read_format */
+#ifndef GL_IMG_read_format
+#define GL_BGRA_IMG                                             0x80E1
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG                       0x8365
+#endif
+
+/* GL_IMG_texture_compression_pvrtc */
+#ifndef GL_IMG_texture_compression_pvrtc
+#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG                      0x8C00
+#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG                      0x8C01
+#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG                     0x8C02
+#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG                     0x8C03
+#endif
+
+/* GL_IMG_texture_env_enhanced_fixed_function */
+#ifndef GL_IMG_texture_env_enhanced_fixed_function
+#define GL_MODULATE_COLOR_IMG                                   0x8C04
+#define GL_RECIP_ADD_SIGNED_ALPHA_IMG                           0x8C05
+#define GL_TEXTURE_ALPHA_MODULATE_IMG                           0x8C06
+#define GL_FACTOR_ALPHA_MODULATE_IMG                            0x8C07
+#define GL_FRAGMENT_ALPHA_MODULATE_IMG                          0x8C08
+#define GL_ADD_BLEND_IMG                                        0x8C09
+#define GL_DOT3_RGBA_IMG                                        0x86AF
+#endif
+
+/* GL_IMG_user_clip_plane */
+#ifndef GL_IMG_user_clip_plane
+#define GL_CLIP_PLANE0_IMG                                      0x3000
+#define GL_CLIP_PLANE1_IMG                                      0x3001
+#define GL_CLIP_PLANE2_IMG                                      0x3002
+#define GL_CLIP_PLANE3_IMG                                      0x3003
+#define GL_CLIP_PLANE4_IMG                                      0x3004
+#define GL_CLIP_PLANE5_IMG                                      0x3005
+#define GL_MAX_CLIP_PLANES_IMG                                  0x0D32
+#endif
+
+/*------------------------------------------------------------------------*
+ * NV extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_NV_fence */
+#ifndef GL_NV_fence
+#define GL_ALL_COMPLETED_NV                                     0x84F2
+#define GL_FENCE_STATUS_NV                                      0x84F3
+#define GL_FENCE_CONDITION_NV                                   0x84F4
+#endif
+
+/*------------------------------------------------------------------------*
+ * QCOM extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_QCOM_driver_control */
+/* No new tokens introduced by this extension. */
+
+/* GL_QCOM_extended_get */
+#ifndef GL_QCOM_extended_get
+#define GL_TEXTURE_WIDTH_QCOM                                   0x8BD2
+#define GL_TEXTURE_HEIGHT_QCOM                                  0x8BD3
+#define GL_TEXTURE_DEPTH_QCOM                                   0x8BD4
+#define GL_TEXTURE_INTERNAL_FORMAT_QCOM                         0x8BD5
+#define GL_TEXTURE_FORMAT_QCOM                                  0x8BD6
+#define GL_TEXTURE_TYPE_QCOM                                    0x8BD7
+#define GL_TEXTURE_IMAGE_VALID_QCOM                             0x8BD8
+#define GL_TEXTURE_NUM_LEVELS_QCOM                              0x8BD9
+#define GL_TEXTURE_TARGET_QCOM                                  0x8BDA
+#define GL_TEXTURE_OBJECT_VALID_QCOM                            0x8BDB
+#define GL_STATE_RESTORE                                        0x8BDC
+#endif
+
+/* GL_QCOM_extended_get2 */
+/* No new tokens introduced by this extension. */
+
+/* GL_QCOM_perfmon_global_mode */
+#ifndef GL_QCOM_perfmon_global_mode
+#define GL_PERFMON_GLOBAL_MODE_QCOM                             0x8FA0
+#endif
+
+/* GL_QCOM_writeonly_rendering */
+#ifndef GL_QCOM_writeonly_rendering
+#define GL_WRITEONLY_RENDERING_QCOM                             0x8823
+#endif
+
+/* GL_QCOM_tiled_rendering */
+#ifndef GL_QCOM_tiled_rendering
+#define GL_COLOR_BUFFER_BIT0_QCOM                               0x00000001
+#define GL_COLOR_BUFFER_BIT1_QCOM                               0x00000002
+#define GL_COLOR_BUFFER_BIT2_QCOM                               0x00000004
+#define GL_COLOR_BUFFER_BIT3_QCOM                               0x00000008
+#define GL_COLOR_BUFFER_BIT4_QCOM                               0x00000010
+#define GL_COLOR_BUFFER_BIT5_QCOM                               0x00000020
+#define GL_COLOR_BUFFER_BIT6_QCOM                               0x00000040
+#define GL_COLOR_BUFFER_BIT7_QCOM                               0x00000080
+#define GL_DEPTH_BUFFER_BIT0_QCOM                               0x00000100
+#define GL_DEPTH_BUFFER_BIT1_QCOM                               0x00000200
+#define GL_DEPTH_BUFFER_BIT2_QCOM                               0x00000400
+#define GL_DEPTH_BUFFER_BIT3_QCOM                               0x00000800
+#define GL_DEPTH_BUFFER_BIT4_QCOM                               0x00001000
+#define GL_DEPTH_BUFFER_BIT5_QCOM                               0x00002000
+#define GL_DEPTH_BUFFER_BIT6_QCOM                               0x00004000
+#define GL_DEPTH_BUFFER_BIT7_QCOM                               0x00008000
+#define GL_STENCIL_BUFFER_BIT0_QCOM                             0x00010000
+#define GL_STENCIL_BUFFER_BIT1_QCOM                             0x00020000
+#define GL_STENCIL_BUFFER_BIT2_QCOM                             0x00040000
+#define GL_STENCIL_BUFFER_BIT3_QCOM                             0x00080000
+#define GL_STENCIL_BUFFER_BIT4_QCOM                             0x00100000
+#define GL_STENCIL_BUFFER_BIT5_QCOM                             0x00200000
+#define GL_STENCIL_BUFFER_BIT6_QCOM                             0x00400000
+#define GL_STENCIL_BUFFER_BIT7_QCOM                             0x00800000
+#define GL_MULTISAMPLE_BUFFER_BIT0_QCOM                         0x01000000
+#define GL_MULTISAMPLE_BUFFER_BIT1_QCOM                         0x02000000
+#define GL_MULTISAMPLE_BUFFER_BIT2_QCOM                         0x04000000
+#define GL_MULTISAMPLE_BUFFER_BIT3_QCOM                         0x08000000
+#define GL_MULTISAMPLE_BUFFER_BIT4_QCOM                         0x10000000
+#define GL_MULTISAMPLE_BUFFER_BIT5_QCOM                         0x20000000
+#define GL_MULTISAMPLE_BUFFER_BIT6_QCOM                         0x40000000
+#define GL_MULTISAMPLE_BUFFER_BIT7_QCOM                         0x80000000
+#endif
+
+/*------------------------------------------------------------------------*
+ * End of extension tokens, start of corresponding extension functions
+ *------------------------------------------------------------------------*/
+
+/*------------------------------------------------------------------------*
+ * OES extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_OES_blend_equation_separate */
+#ifndef GL_OES_blend_equation_separate
+#define GL_OES_blend_equation_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glBlendEquationSeparateOES (GLenum modeRGB, GLenum modeAlpha);
+#endif
+typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEOESPROC) (GLenum modeRGB, GLenum modeAlpha);
+#endif
+
+/* GL_OES_blend_func_separate */
+#ifndef GL_OES_blend_func_separate
+#define GL_OES_blend_func_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glBlendFuncSeparateOES (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+#endif
+typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEOESPROC) (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+#endif
+
+/* GL_OES_blend_subtract */
+#ifndef GL_OES_blend_subtract
+#define GL_OES_blend_subtract 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glBlendEquationOES (GLenum mode);
+#endif
+typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONOESPROC) (GLenum mode);
+#endif
+
+/* GL_OES_byte_coordinates */
+#ifndef GL_OES_byte_coordinates
+#define GL_OES_byte_coordinates 1
+#endif
+
+/* GL_OES_compressed_ETC1_RGB8_texture */
+#ifndef GL_OES_compressed_ETC1_RGB8_texture
+#define GL_OES_compressed_ETC1_RGB8_texture 1
+#endif
+
+/* GL_OES_depth24 */
+#ifndef GL_OES_depth24
+#define GL_OES_depth24 1
+#endif
+
+/* GL_OES_depth32 */
+#ifndef GL_OES_depth32
+#define GL_OES_depth32 1
+#endif
+
+/* GL_OES_EGL_image */
+#ifndef GL_OES_EGL_image
+#define GL_OES_EGL_image 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image);
+GL_API void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image);
+#endif
+typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
+typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
+#endif
+
+/* GL_OES_element_index_uint */
+#ifndef GL_OES_element_index_uint
+#define GL_OES_element_index_uint 1
+#endif
+
+/* GL_OES_extended_matrix_palette */
+#ifndef GL_OES_extended_matrix_palette
+#define GL_OES_extended_matrix_palette 1
+#endif
+
+/* GL_OES_fbo_render_mipmap */
+#ifndef GL_OES_fbo_render_mipmap
+#define GL_OES_fbo_render_mipmap 1
+#endif
+
+/* GL_OES_fixed_point */
+#ifndef GL_OES_fixed_point
+#define GL_OES_fixed_point 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glAlphaFuncxOES (GLenum func, GLclampx ref);
+GL_API void GL_APIENTRY glClearColorxOES (GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha);
+GL_API void GL_APIENTRY glClearDepthxOES (GLclampx depth);
+GL_API void GL_APIENTRY glClipPlanexOES (GLenum plane, const GLfixed *equation);
+GL_API void GL_APIENTRY glColor4xOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);
+GL_API void GL_APIENTRY glDepthRangexOES (GLclampx zNear, GLclampx zFar);
+GL_API void GL_APIENTRY glFogxOES (GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glFogxvOES (GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glFrustumxOES (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar);
+GL_API void GL_APIENTRY glGetClipPlanexOES (GLenum pname, GLfixed eqn[4]);
+GL_API void GL_APIENTRY glGetFixedvOES (GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glGetLightxvOES (GLenum light, GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glGetMaterialxvOES (GLenum face, GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glGetTexEnvxvOES (GLenum env, GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glGetTexParameterxvOES (GLenum target, GLenum pname, GLfixed *params);
+GL_API void GL_APIENTRY glLightModelxOES (GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glLightModelxvOES (GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glLightxOES (GLenum light, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glLightxvOES (GLenum light, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glLineWidthxOES (GLfixed width);
+GL_API void GL_APIENTRY glLoadMatrixxOES (const GLfixed *m);
+GL_API void GL_APIENTRY glMaterialxOES (GLenum face, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glMaterialxvOES (GLenum face, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glMultMatrixxOES (const GLfixed *m);
+GL_API void GL_APIENTRY glMultiTexCoord4xOES (GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q);
+GL_API void GL_APIENTRY glNormal3xOES (GLfixed nx, GLfixed ny, GLfixed nz);
+GL_API void GL_APIENTRY glOrthoxOES (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar);
+GL_API void GL_APIENTRY glPointParameterxOES (GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glPointParameterxvOES (GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glPointSizexOES (GLfixed size);
+GL_API void GL_APIENTRY glPolygonOffsetxOES (GLfixed factor, GLfixed units);
+GL_API void GL_APIENTRY glRotatexOES (GLfixed angle, GLfixed x, GLfixed y, GLfixed z);
+GL_API void GL_APIENTRY glSampleCoveragexOES (GLclampx value, GLboolean invert);
+GL_API void GL_APIENTRY glScalexOES (GLfixed x, GLfixed y, GLfixed z);
+GL_API void GL_APIENTRY glTexEnvxOES (GLenum target, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glTexEnvxvOES (GLenum target, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glTexParameterxOES (GLenum target, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glTexParameterxvOES (GLenum target, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glTranslatexOES (GLfixed x, GLfixed y, GLfixed z);
+#endif
+typedef void (GL_APIENTRYP PFNGLALPHAFUNCXOESPROC) (GLenum func, GLclampx ref);
+typedef void (GL_APIENTRYP PFNGLCLEARCOLORXOESPROC) (GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha);
+typedef void (GL_APIENTRYP PFNGLCLEARDEPTHXOESPROC) (GLclampx depth);
+typedef void (GL_APIENTRYP PFNGLCLIPPLANEXOESPROC) (GLenum plane, const GLfixed *equation);
+typedef void (GL_APIENTRYP PFNGLCOLOR4XOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha);
+typedef void (GL_APIENTRYP PFNGLDEPTHRANGEXOESPROC) (GLclampx zNear, GLclampx zFar);
+typedef void (GL_APIENTRYP PFNGLFOGXOESPROC) (GLenum pname, GLfixed param);
+typedef void (GL_APIENTRYP PFNGLFOGXVOESPROC) (GLenum pname, const GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLFRUSTUMXOESPROC) (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar);
+typedef void (GL_APIENTRYP PFNGLGETCLIPPLANEXOESPROC) (GLenum pname, GLfixed eqn[4]);
+typedef void (GL_APIENTRYP PFNGLGETFIXEDVOESPROC) (GLenum pname, GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLGETLIGHTXVOESPROC) (GLenum light, GLenum pname, GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLGETMATERIALXVOESPROC) (GLenum face, GLenum pname, GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXENVXVOESPROC) (GLenum env, GLenum pname, GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLLIGHTMODELXOESPROC) (GLenum pname, GLfixed param);
+typedef void (GL_APIENTRYP PFNGLLIGHTMODELXVOESPROC) (GLenum pname, const GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed param);
+typedef void (GL_APIENTRYP PFNGLLIGHTXVOESPROC) (GLenum light, GLenum pname, const GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLLINEWIDTHXOESPROC) (GLfixed width);
+typedef void (GL_APIENTRYP PFNGLLOADMATRIXXOESPROC) (const GLfixed *m);
+typedef void (GL_APIENTRYP PFNGLMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param);
+typedef void (GL_APIENTRYP PFNGLMATERIALXVOESPROC) (GLenum face, GLenum pname, const GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLMULTMATRIXXOESPROC) (const GLfixed *m);
+typedef void (GL_APIENTRYP PFNGLMULTITEXCOORD4XOESPROC) (GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q);
+typedef void (GL_APIENTRYP PFNGLNORMAL3XOESPROC) (GLfixed nx, GLfixed ny, GLfixed nz);
+typedef void (GL_APIENTRYP PFNGLORTHOXOESPROC) (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar);
+typedef void (GL_APIENTRYP PFNGLPOINTPARAMETERXOESPROC) (GLenum pname, GLfixed param);
+typedef void (GL_APIENTRYP PFNGLPOINTPARAMETERXVOESPROC) (GLenum pname, const GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLPOINTSIZEXOESPROC) (GLfixed size);
+typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETXOESPROC) (GLfixed factor, GLfixed units);
+typedef void (GL_APIENTRYP PFNGLROTATEXOESPROC) (GLfixed angle, GLfixed x, GLfixed y, GLfixed z);
+typedef void (GL_APIENTRYP PFNGLSAMPLECOVERAGEXOESPROC) (GLclampx value, GLboolean invert);
+typedef void (GL_APIENTRYP PFNGLSCALEXOESPROC) (GLfixed x, GLfixed y, GLfixed z);
+typedef void (GL_APIENTRYP PFNGLTEXENVXOESPROC) (GLenum target, GLenum pname, GLfixed param);
+typedef void (GL_APIENTRYP PFNGLTEXENVXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param);
+typedef void (GL_APIENTRYP PFNGLTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLTRANSLATEXOESPROC) (GLfixed x, GLfixed y, GLfixed z);
+#endif
+
+/* GL_OES_framebuffer_object */
+#ifndef GL_OES_framebuffer_object
+#define GL_OES_framebuffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API GLboolean GL_APIENTRY glIsRenderbufferOES (GLuint renderbuffer);
+GL_API void GL_APIENTRY glBindRenderbufferOES (GLenum target, GLuint renderbuffer);
+GL_API void GL_APIENTRY glDeleteRenderbuffersOES (GLsizei n, const GLuint* renderbuffers);
+GL_API void GL_APIENTRY glGenRenderbuffersOES (GLsizei n, GLuint* renderbuffers);
+GL_API void GL_APIENTRY glRenderbufferStorageOES (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+GL_API void GL_APIENTRY glGetRenderbufferParameterivOES (GLenum target, GLenum pname, GLint* params);
+GL_API GLboolean GL_APIENTRY glIsFramebufferOES (GLuint framebuffer);
+GL_API void GL_APIENTRY glBindFramebufferOES (GLenum target, GLuint framebuffer);
+GL_API void GL_APIENTRY glDeleteFramebuffersOES (GLsizei n, const GLuint* framebuffers);
+GL_API void GL_APIENTRY glGenFramebuffersOES (GLsizei n, GLuint* framebuffers);
+GL_API GLenum GL_APIENTRY glCheckFramebufferStatusOES (GLenum target);
+GL_API void GL_APIENTRY glFramebufferRenderbufferOES (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+GL_API void GL_APIENTRY glFramebufferTexture2DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GL_API void GL_APIENTRY glGetFramebufferAttachmentParameterivOES (GLenum target, GLenum attachment, GLenum pname, GLint* params);
+GL_API void GL_APIENTRY glGenerateMipmapOES (GLenum target);
+#endif
+typedef GLboolean (GL_APIENTRYP PFNGLISRENDERBUFFEROESPROC) (GLuint renderbuffer);
+typedef void (GL_APIENTRYP PFNGLBINDRENDERBUFFEROESPROC) (GLenum target, GLuint renderbuffer);
+typedef void (GL_APIENTRYP PFNGLDELETERENDERBUFFERSOESPROC) (GLsizei n, const GLuint* renderbuffers);
+typedef void (GL_APIENTRYP PFNGLGENRENDERBUFFERSOESPROC) (GLsizei n, GLuint* renderbuffers);
+typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVOESPROC) (GLenum target, GLenum pname, GLint* params);
+typedef GLboolean (GL_APIENTRYP PFNGLISFRAMEBUFFEROESPROC) (GLuint framebuffer);
+typedef void (GL_APIENTRYP PFNGLBINDFRAMEBUFFEROESPROC) (GLenum target, GLuint framebuffer);
+typedef void (GL_APIENTRYP PFNGLDELETEFRAMEBUFFERSOESPROC) (GLsizei n, const GLuint* framebuffers);
+typedef void (GL_APIENTRYP PFNGLGENFRAMEBUFFERSOESPROC) (GLsizei n, GLuint* framebuffers);
+typedef GLenum (GL_APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSOESPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEROESPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DOESPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+typedef void (GL_APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOESPROC) (GLenum target, GLenum attachment, GLenum pname, GLint* params);
+typedef void (GL_APIENTRYP PFNGLGENERATEMIPMAPOESPROC) (GLenum target);
+#endif
+
+/* GL_OES_mapbuffer */
+#ifndef GL_OES_mapbuffer
+#define GL_OES_mapbuffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void* GL_APIENTRY glMapBufferOES (GLenum target, GLenum access);
+GL_API GLboolean GL_APIENTRY glUnmapBufferOES (GLenum target);
+GL_API void GL_APIENTRY glGetBufferPointervOES (GLenum target, GLenum pname, GLvoid ** params);
+#endif
+typedef void* (GL_APIENTRYP PFNGLMAPBUFFEROESPROC) (GLenum target, GLenum access);
+typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFEROESPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVOESPROC) (GLenum target, GLenum pname, GLvoid ** params);
+#endif
+
+/* GL_OES_matrix_get */
+#ifndef GL_OES_matrix_get
+#define GL_OES_matrix_get 1
+#endif
+
+/* GL_OES_packed_depth_stencil */
+#ifndef GL_OES_packed_depth_stencil
+#define GL_OES_packed_depth_stencil 1
+#endif
+
+/* GL_OES_rgb8_rgba8 */
+#ifndef GL_OES_rgb8_rgba8
+#define GL_OES_rgb8_rgba8 1
+#endif
+
+/* GL_OES_single_precision */
+#ifndef GL_OES_single_precision
+#define GL_OES_single_precision 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glDepthRangefOES (GLclampf zNear, GLclampf zFar);
+GL_API void GL_APIENTRY glFrustumfOES (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar);
+GL_API void GL_APIENTRY glOrthofOES (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar);
+GL_API void GL_APIENTRY glClipPlanefOES (GLenum plane, const GLfloat *equation);
+GL_API void GL_APIENTRY glGetClipPlanefOES (GLenum pname, GLfloat eqn[4]);
+GL_API void GL_APIENTRY glClearDepthfOES (GLclampf depth);
+#endif
+typedef void (GL_APIENTRYP PFNGLDEPTHRANGEFOESPROC) (GLclampf zNear, GLclampf zFar);
+typedef void (GL_APIENTRYP PFNGLFRUSTUMFOESPROC) (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar);
+typedef void (GL_APIENTRYP PFNGLORTHOFOESPROC) (GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar);
+typedef void (GL_APIENTRYP PFNGLCLIPPLANEFOESPROC) (GLenum plane, const GLfloat *equation);
+typedef void (GL_APIENTRYP PFNGLGETCLIPPLANEFOESPROC) (GLenum pname, GLfloat eqn[4]);
+typedef void (GL_APIENTRYP PFNGLCLEARDEPTHFOESPROC) (GLclampf depth);
+#endif
+
+/* GL_OES_stencil1 */
+#ifndef GL_OES_stencil1
+#define GL_OES_stencil1 1
+#endif
+
+/* GL_OES_stencil4 */
+#ifndef GL_OES_stencil4
+#define GL_OES_stencil4 1
+#endif
+
+/* GL_OES_stencil8 */
+#ifndef GL_OES_stencil8
+#define GL_OES_stencil8 1
+#endif
+
+/* GL_OES_stencil_wrap */
+#ifndef GL_OES_stencil_wrap
+#define GL_OES_stencil_wrap 1
+#endif
+
+/* GL_OES_texture_cube_map */
+#ifndef GL_OES_texture_cube_map
+#define GL_OES_texture_cube_map 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glTexGenfOES (GLenum coord, GLenum pname, GLfloat param);
+GL_API void GL_APIENTRY glTexGenfvOES (GLenum coord, GLenum pname, const GLfloat *params);
+GL_API void GL_APIENTRY glTexGeniOES (GLenum coord, GLenum pname, GLint param);
+GL_API void GL_APIENTRY glTexGenivOES (GLenum coord, GLenum pname, const GLint *params);
+GL_API void GL_APIENTRY glTexGenxOES (GLenum coord, GLenum pname, GLfixed param);
+GL_API void GL_APIENTRY glTexGenxvOES (GLenum coord, GLenum pname, const GLfixed *params);
+GL_API void GL_APIENTRY glGetTexGenfvOES (GLenum coord, GLenum pname, GLfloat *params);
+GL_API void GL_APIENTRY glGetTexGenivOES (GLenum coord, GLenum pname, GLint *params);
+GL_API void GL_APIENTRY glGetTexGenxvOES (GLenum coord, GLenum pname, GLfixed *params);
+#endif
+typedef void (GL_APIENTRYP PFNGLTEXGENFOESPROC) (GLenum coord, GLenum pname, GLfloat param);
+typedef void (GL_APIENTRYP PFNGLTEXGENFVOESPROC) (GLenum coord, GLenum pname, const GLfloat *params);
+typedef void (GL_APIENTRYP PFNGLTEXGENIOESPROC) (GLenum coord, GLenum pname, GLint param);
+typedef void (GL_APIENTRYP PFNGLTEXGENIVOESPROC) (GLenum coord, GLenum pname, const GLint *params);
+typedef void (GL_APIENTRYP PFNGLTEXGENXOESPROC) (GLenum coord, GLenum pname, GLfixed param);
+typedef void (GL_APIENTRYP PFNGLTEXGENXVOESPROC) (GLenum coord, GLenum pname, const GLfixed *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXGENFVOESPROC) (GLenum coord, GLenum pname, GLfloat *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXGENIVOESPROC) (GLenum coord, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLGETTEXGENXVOESPROC) (GLenum coord, GLenum pname, GLfixed *params);
+#endif
+
+/* GL_OES_texture_env_crossbar */
+#ifndef GL_OES_texture_env_crossbar
+#define GL_OES_texture_env_crossbar 1
+#endif
+
+/* GL_OES_texture_mirrored_repeat */
+#ifndef GL_OES_texture_mirrored_repeat
+#define GL_OES_texture_mirrored_repeat 1
+#endif
+
+/* GL_OES_vertex_array_object */
+#ifndef GL_OES_vertex_array_object
+#define GL_OES_vertex_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glBindVertexArrayOES (GLuint array);
+GL_API void GL_APIENTRY glDeleteVertexArraysOES (GLsizei n, const GLuint *arrays);
+GL_API void GL_APIENTRY glGenVertexArraysOES (GLsizei n, GLuint *arrays);
+GL_API GLboolean GL_APIENTRY glIsVertexArrayOES (GLuint array);
+#endif
+typedef void (GL_APIENTRYP PFNGLBINDVERTEXARRAYOESPROC) (GLuint array);
+typedef void (GL_APIENTRYP PFNGLDELETEVERTEXARRAYSOESPROC) (GLsizei n, const GLuint *arrays);
+typedef void (GL_APIENTRYP PFNGLGENVERTEXARRAYSOESPROC) (GLsizei n, GLuint *arrays);
+typedef GLboolean (GL_APIENTRYP PFNGLISVERTEXARRAYOESPROC) (GLuint array);
+#endif
+
+/*------------------------------------------------------------------------*
+ * AMD extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_AMD_compressed_3DC_texture */
+#ifndef GL_AMD_compressed_3DC_texture
+#define GL_AMD_compressed_3DC_texture 1
+#endif
+
+/* GL_AMD_compressed_ATC_texture */
+#ifndef GL_AMD_compressed_ATC_texture
+#define GL_AMD_compressed_ATC_texture 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * APPLE extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_APPLE_texture_2D_limited_npot */
+#ifndef GL_APPLE_texture_2D_limited_npot
+#define GL_APPLE_texture_2D_limited_npot 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * EXT extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_EXT_blend_minmax */
+#ifndef GL_EXT_blend_minmax
+#define GL_EXT_blend_minmax 1
+#endif
+
+/* GL_EXT_discard_framebuffer */
+#ifndef GL_EXT_discard_framebuffer
+#define GL_EXT_discard_framebuffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glDiscardFramebufferEXT (GLenum target, GLsizei numAttachments, const GLenum *attachments);
+#endif
+typedef void (GL_APIENTRYP PFNGLDISCARDFRAMEBUFFEREXTPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments);
+#endif
+
+/* GL_EXT_multi_draw_arrays */
+#ifndef GL_EXT_multi_draw_arrays
+#define GL_EXT_multi_draw_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei);
+GL_API void GL_APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+#endif
+
+/* GL_EXT_read_format_bgra */
+#ifndef GL_EXT_read_format_bgra
+#define GL_EXT_read_format_bgra 1
+#endif
+
+/* GL_EXT_texture_filter_anisotropic */
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_EXT_texture_filter_anisotropic 1
+#endif
+
+/* GL_EXT_texture_format_BGRA8888 */
+#ifndef GL_EXT_texture_format_BGRA8888
+#define GL_EXT_texture_format_BGRA8888 1
+#endif
+
+/* GL_EXT_texture_lod_bias */
+#ifndef GL_EXT_texture_lod_bias
+#define GL_EXT_texture_lod_bias 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * IMG extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_IMG_read_format */
+#ifndef GL_IMG_read_format
+#define GL_IMG_read_format 1
+#endif
+
+/* GL_IMG_texture_compression_pvrtc */
+#ifndef GL_IMG_texture_compression_pvrtc
+#define GL_IMG_texture_compression_pvrtc 1
+#endif
+
+/* GL_IMG_texture_env_enhanced_fixed_function */
+#ifndef GL_IMG_texture_env_enhanced_fixed_function
+#define GL_IMG_texture_env_enhanced_fixed_function 1
+#endif
+
+/* GL_IMG_user_clip_plane */
+#ifndef GL_IMG_user_clip_plane
+#define GL_IMG_user_clip_plane 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glClipPlanefIMG (GLenum, const GLfloat *);
+GL_API void GL_APIENTRY glClipPlanexIMG (GLenum, const GLfixed *);
+#endif
+typedef void (GL_APIENTRYP PFNGLCLIPPLANEFIMGPROC) (GLenum p, const GLfloat *eqn);
+typedef void (GL_APIENTRYP PFNGLCLIPPLANEXIMGPROC) (GLenum p, const GLfixed *eqn);
+#endif
+
+/*------------------------------------------------------------------------*
+ * NV extension functions
+ *------------------------------------------------------------------------*/
+
+/* NV_fence */
+#ifndef GL_NV_fence
+#define GL_NV_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glDeleteFencesNV (GLsizei, const GLuint *);
+GL_API void GL_APIENTRY glGenFencesNV (GLsizei, GLuint *);
+GL_API GLboolean GL_APIENTRY glIsFenceNV (GLuint);
+GL_API GLboolean GL_APIENTRY glTestFenceNV (GLuint);
+GL_API void GL_APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *);
+GL_API void GL_APIENTRY glFinishFenceNV (GLuint);
+GL_API void GL_APIENTRY glSetFenceNV (GLuint, GLenum);
+#endif
+typedef void (GL_APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
+typedef void (GL_APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
+typedef GLboolean (GL_APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
+typedef GLboolean (GL_APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
+typedef void (GL_APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
+typedef void (GL_APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
+#endif
+
+/*------------------------------------------------------------------------*
+ * QCOM extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_QCOM_driver_control */
+#ifndef GL_QCOM_driver_control
+#define GL_QCOM_driver_control 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glGetDriverControlsQCOM (GLint *num, GLsizei size, GLuint *driverControls);
+GL_API void GL_APIENTRY glGetDriverControlStringQCOM (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString);
+GL_API void GL_APIENTRY glEnableDriverControlQCOM (GLuint driverControl);
+GL_API void GL_APIENTRY glDisableDriverControlQCOM (GLuint driverControl);
+#endif
+typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSQCOMPROC) (GLint *num, GLsizei size, GLuint *driverControls);
+typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSTRINGQCOMPROC) (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString);
+typedef void (GL_APIENTRYP PFNGLENABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
+typedef void (GL_APIENTRYP PFNGLDISABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
+#endif
+
+/* GL_QCOM_extended_get */
+#ifndef GL_QCOM_extended_get
+#define GL_QCOM_extended_get 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glExtGetTexturesQCOM (GLuint *textures, GLint maxTextures, GLint *numTextures);
+GL_API void GL_APIENTRY glExtGetBuffersQCOM (GLuint *buffers, GLint maxBuffers, GLint *numBuffers);
+GL_API void GL_APIENTRY glExtGetRenderbuffersQCOM (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers);
+GL_API void GL_APIENTRY glExtGetFramebuffersQCOM (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers);
+GL_API void GL_APIENTRY glExtGetTexLevelParameterivQCOM (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params);
+GL_API void GL_APIENTRY glExtTexObjectStateOverrideiQCOM (GLenum target, GLenum pname, GLint param);
+GL_API void GL_APIENTRY glExtGetTexSubImageQCOM (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLvoid *texels);
+GL_API void GL_APIENTRY glExtGetBufferPointervQCOM (GLenum target, GLvoid **params);
+#endif
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXTURESQCOMPROC) (GLuint *textures, GLint maxTextures, GLint *numTextures);
+typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERSQCOMPROC) (GLuint *buffers, GLint maxBuffers, GLint *numBuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETRENDERBUFFERSQCOMPROC) (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETFRAMEBUFFERSQCOMPROC) (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC) (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXSUBIMAGEQCOMPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLvoid *texels);
+typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERPOINTERVQCOMPROC) (GLenum target, GLvoid **params);
+#endif
+
+/* GL_QCOM_extended_get2 */
+#ifndef GL_QCOM_extended_get2
+#define GL_QCOM_extended_get2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glExtGetShadersQCOM (GLuint *shaders, GLint maxShaders, GLint *numShaders);
+GL_API void GL_APIENTRY glExtGetProgramsQCOM (GLuint *programs, GLint maxPrograms, GLint *numPrograms);
+GL_API GLboolean GL_APIENTRY glExtIsProgramBinaryQCOM (GLuint program);
+GL_API void GL_APIENTRY glExtGetProgramBinarySourceQCOM (GLuint program, GLenum shadertype, GLchar *source, GLint *length);
+#endif
+typedef void (GL_APIENTRYP PFNGLEXTGETSHADERSQCOMPROC) (GLuint *shaders, GLint maxShaders, GLint *numShaders);
+typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMSQCOMPROC) (GLuint *programs, GLint maxPrograms, GLint *numPrograms);
+typedef GLboolean (GL_APIENTRYP PFNGLEXTISPROGRAMBINARYQCOMPROC) (GLuint program);
+typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC) (GLuint program, GLenum shadertype, GLchar *source, GLint *length);
+#endif
+
+/* GL_QCOM_perfmon_global_mode */
+#ifndef GL_QCOM_perfmon_global_mode
+#define GL_QCOM_perfmon_global_mode 1
+#endif
+
+/* GL_QCOM_writeonly_rendering */
+#ifndef GL_QCOM_writeonly_rendering
+#define GL_QCOM_writeonly_rendering 1
+#endif
+
+/* GL_QCOM_tiled_rendering */
+#ifndef GL_QCOM_tiled_rendering
+#define GL_QCOM_tiled_rendering 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_API void GL_APIENTRY glStartTilingQCOM (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask);
+GL_API void GL_APIENTRY glEndTilingQCOM (GLbitfield preserveMask);
+#endif
+typedef void (GL_APIENTRYP PFNGLSTARTTILINGQCOMPROC) (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask);
+typedef void (GL_APIENTRYP PFNGLENDTILINGQCOMPROC) (GLbitfield preserveMask);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __glext_h_ */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES/glextplatform.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,124 @@
+/*
+** Copyright (c) 2007-2009 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.
+*/
+
+#ifndef glextplatform_h
+#define glextplatform_h
+
+/**
+@publishedAll
+@released
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** The following defines were in gl.h in OpenGL ES 1.0.  To keep backwards 
+** compatibility they are defined in this file which is always included at
+** the end of gl.h. Undefine guard definitions as required to enable 
+** OpenGL ES 1.1 glext.h functionality.
+**
+** We have also added __SOFTFP decorations for call-by-value float functions
+*/
+
+/* Renamed for OpenGL ES 1.1 */
+
+#define GL_WRITE_ONLY                               0x88B9
+#define GL_BUFFER_ACCESS                            0x88BB
+
+
+/* Removed for OpenGL ES 1.1 */
+
+/* OpenGL ES core versions */
+#define GL_OES_VERSION_1_0                          1
+#define GL_OES_VERSION_1_1                          1
+
+/* BeginMode */
+#define GL_MAX_ELEMENTS_VERTICES                    0x80E8
+#define GL_MAX_ELEMENTS_INDICES                     0x80E9
+
+/* HintTarget */
+#define GL_POLYGON_SMOOTH_HINT                      0x0C53
+
+
+/* Moved from gl.h to glext.h (optional header) for OpenGL ES 1.1 */
+
+/* GL_OES_byte_coordinates */
+#define GL_OES_byte_coordinates	                    1
+
+/* GL_OES_draw_texture */
+#define GL_OES_draw_texture                         1
+#define GL_TEXTURE_CROP_RECT_OES                    0x8B9D
+GL_API void GL_APIENTRY glDrawTexsOES (GLshort x, GLshort y, GLshort z, GLshort width, GLshort height);
+GL_API void GL_APIENTRY glDrawTexiOES (GLint x, GLint y, GLint z, GLint width, GLint height);
+GL_API void GL_APIENTRY glDrawTexxOES (GLfixed x, GLfixed y, GLfixed z, GLfixed width, GLfixed height);
+GL_API void GL_APIENTRY glDrawTexsvOES (const GLshort *coords);
+GL_API void GL_APIENTRY glDrawTexivOES (const GLint *coords);
+GL_API void GL_APIENTRY glDrawTexxvOES (const GLfixed *coords);
+GL_API void GL_APIENTRY glDrawTexfOES (GLfloat x, GLfloat y, GLfloat z, GLfloat width, GLfloat height);// __SOFTFP;
+GL_API void GL_APIENTRY glDrawTexfvOES (const GLfloat *coords);
+
+/* GL_OES_fixed_point */
+#define GL_OES_fixed_point	                        1
+
+/* GL_OES_single_precision */
+#define GL_OES_single_precision                     1
+
+/* OES_matrix_get */
+#define GL_OES_matrix_get	                        1
+#define GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES   0x898D
+#define GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES  0x898E
+#define GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES     0x898F
+
+/* OES_matrix_palette */
+#define GL_OES_matrix_palette	                    1
+#define GL_MAX_VERTEX_UNITS_OES                     0x86A4
+#define GL_MAX_PALETTE_MATRICES_OES                 0x8842
+#define GL_MATRIX_PALETTE_OES                       0x8840
+#define GL_MATRIX_INDEX_ARRAY_OES                   0x8844
+#define GL_WEIGHT_ARRAY_OES                         0x86AD
+#define GL_CURRENT_PALETTE_MATRIX_OES               0x8843
+#define GL_MATRIX_INDEX_ARRAY_SIZE_OES              0x8846
+#define GL_MATRIX_INDEX_ARRAY_TYPE_OES              0x8847
+#define GL_MATRIX_INDEX_ARRAY_STRIDE_OES            0x8848
+#define GL_MATRIX_INDEX_ARRAY_POINTER_OES           0x8849
+#define GL_MATRIX_INDEX_ARRAY_BUFFER_BINDING_OES    0x8B9E
+#define GL_WEIGHT_ARRAY_SIZE_OES                    0x86AB
+#define GL_WEIGHT_ARRAY_TYPE_OES                    0x86A9
+#define GL_WEIGHT_ARRAY_STRIDE_OES                  0x86AA
+#define GL_WEIGHT_ARRAY_POINTER_OES                 0x86AC
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING_OES          0x889E
+GL_API void GL_APIENTRY glCurrentPaletteMatrixOES (GLuint matrixpaletteindex);
+GL_API void GL_APIENTRY glLoadPaletteFromModelViewMatrixOES (void);
+GL_API void GL_APIENTRY glMatrixIndexPointerOES (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GL_API void GL_APIENTRY glWeightPointerOES (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+
+
+GL_API GLbitfield GL_APIENTRY glQueryMatrixxOES (GLfixed mantissa[16], GLint exponent[16]);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* glextplatform_h */
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES/glplatform.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,30 @@
+#ifndef __glplatform_h_
+#define __glplatform_h_
+
+/* $Revision: 10601 $ on $Date:: 2010-03-04 22:15:27 -0800 #$ */
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+/* Platform-specific types and definitions for OpenGL ES 1.X  gl.h
+ *
+ * Adopters may modify khrplatform.h and this file to suit their platform.
+ * You are encouraged to submit all modifications to the Khronos group so that
+ * they can be included in future versions of this file.  Please submit changes
+ * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
+ * by filing a bug against product "OpenGL-ES" component "Registry".
+ */
+
+#include <KHR/khrplatform.h>
+
+#ifndef GL_API
+#define GL_API      KHRONOS_APICALL
+#endif
+
+#ifndef GL_APIENTRY
+#define GL_APIENTRY KHRONOS_APIENTRY
+#endif
+
+#endif /* __glplatform_h_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES2/gl2.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,624 @@
+#ifndef __gl2_h_
+#define __gl2_h_
+
+/* $Revision: 8784 $ on $Date:: 2009-09-02 09:49:17 -0700 #$ */
+
+#include <GLES2/gl2platform.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+/*-------------------------------------------------------------------------
+ * Data type definitions
+ *-----------------------------------------------------------------------*/
+
+typedef void             GLvoid;
+typedef unsigned int     GLenum;
+typedef unsigned char    GLboolean;
+typedef unsigned int     GLbitfield;
+typedef khronos_int8_t   GLbyte;
+typedef short            GLshort;
+typedef int              GLint;
+typedef int              GLsizei;
+typedef khronos_uint8_t  GLubyte;
+typedef unsigned short   GLushort;
+typedef unsigned int     GLuint;
+typedef khronos_float_t  GLfloat;
+typedef khronos_float_t  GLclampf;
+typedef khronos_int32_t  GLfixed;
+
+/* Nonstandard, required by clutter! */
+typedef khronos_int32_t  GLclampx;
+
+/* GL types for handling large vertex buffer objects */
+typedef khronos_intptr_t GLintptr;
+typedef khronos_ssize_t  GLsizeiptr;
+
+/* OpenGL ES core versions */
+#define GL_ES_VERSION_2_0                 1
+
+/* ClearBufferMask */
+#define GL_DEPTH_BUFFER_BIT               0x00000100
+#define GL_STENCIL_BUFFER_BIT             0x00000400
+#define GL_COLOR_BUFFER_BIT               0x00004000
+
+/* Boolean */
+#define GL_FALSE                          0
+#define GL_TRUE                           1
+
+/* BeginMode */
+#define GL_POINTS                         0x0000
+#define GL_LINES                          0x0001
+#define GL_LINE_LOOP                      0x0002
+#define GL_LINE_STRIP                     0x0003
+#define GL_TRIANGLES                      0x0004
+#define GL_TRIANGLE_STRIP                 0x0005
+#define GL_TRIANGLE_FAN                   0x0006
+
+/* AlphaFunction (not supported in ES20) */
+/*      GL_NEVER */
+/*      GL_LESS */
+/*      GL_EQUAL */
+/*      GL_LEQUAL */
+/*      GL_GREATER */
+/*      GL_NOTEQUAL */
+/*      GL_GEQUAL */
+/*      GL_ALWAYS */
+
+/* BlendingFactorDest */
+#define GL_ZERO                           0
+#define GL_ONE                            1
+#define GL_SRC_COLOR                      0x0300
+#define GL_ONE_MINUS_SRC_COLOR            0x0301
+#define GL_SRC_ALPHA                      0x0302
+#define GL_ONE_MINUS_SRC_ALPHA            0x0303
+#define GL_DST_ALPHA                      0x0304
+#define GL_ONE_MINUS_DST_ALPHA            0x0305
+
+/* BlendingFactorSrc */
+/*      GL_ZERO */
+/*      GL_ONE */
+#define GL_DST_COLOR                      0x0306
+#define GL_ONE_MINUS_DST_COLOR            0x0307
+#define GL_SRC_ALPHA_SATURATE             0x0308
+/*      GL_SRC_ALPHA */
+/*      GL_ONE_MINUS_SRC_ALPHA */
+/*      GL_DST_ALPHA */
+/*      GL_ONE_MINUS_DST_ALPHA */
+
+/* BlendEquationSeparate */
+#define GL_FUNC_ADD                       0x8006
+#define GL_BLEND_EQUATION                 0x8009
+#define GL_BLEND_EQUATION_RGB             0x8009    /* same as BLEND_EQUATION */
+#define GL_BLEND_EQUATION_ALPHA           0x883D
+
+/* BlendSubtract */
+#define GL_FUNC_SUBTRACT                  0x800A
+#define GL_FUNC_REVERSE_SUBTRACT          0x800B
+
+/* Separate Blend Functions */
+#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_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
+
+/* Buffer Objects */
+#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_STREAM_DRAW                    0x88E0
+#define GL_STATIC_DRAW                    0x88E4
+#define GL_DYNAMIC_DRAW                   0x88E8
+
+#define GL_BUFFER_SIZE                    0x8764
+#define GL_BUFFER_USAGE                   0x8765
+
+#define GL_CURRENT_VERTEX_ATTRIB          0x8626
+
+/* CullFaceMode */
+#define GL_FRONT                          0x0404
+#define GL_BACK                           0x0405
+#define GL_FRONT_AND_BACK                 0x0408
+
+/* DepthFunction */
+/*      GL_NEVER */
+/*      GL_LESS */
+/*      GL_EQUAL */
+/*      GL_LEQUAL */
+/*      GL_GREATER */
+/*      GL_NOTEQUAL */
+/*      GL_GEQUAL */
+/*      GL_ALWAYS */
+
+/* EnableCap */
+#define GL_TEXTURE_2D                     0x0DE1
+#define GL_CULL_FACE                      0x0B44
+#define GL_BLEND                          0x0BE2
+#define GL_DITHER                         0x0BD0
+#define GL_STENCIL_TEST                   0x0B90
+#define GL_DEPTH_TEST                     0x0B71
+#define GL_SCISSOR_TEST                   0x0C11
+#define GL_POLYGON_OFFSET_FILL            0x8037
+#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
+#define GL_SAMPLE_COVERAGE                0x80A0
+
+/* ErrorCode */
+#define GL_NO_ERROR                       0
+#define GL_INVALID_ENUM                   0x0500
+#define GL_INVALID_VALUE                  0x0501
+#define GL_INVALID_OPERATION              0x0502
+#define GL_OUT_OF_MEMORY                  0x0505
+
+/* FrontFaceDirection */
+#define GL_CW                             0x0900
+#define GL_CCW                            0x0901
+
+/* GetPName */
+#define GL_LINE_WIDTH                     0x0B21
+#define GL_ALIASED_POINT_SIZE_RANGE       0x846D
+#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E
+#define GL_CULL_FACE_MODE                 0x0B45
+#define GL_FRONT_FACE                     0x0B46
+#define GL_DEPTH_RANGE                    0x0B70
+#define GL_DEPTH_WRITEMASK                0x0B72
+#define GL_DEPTH_CLEAR_VALUE              0x0B73
+#define GL_DEPTH_FUNC                     0x0B74
+#define GL_STENCIL_CLEAR_VALUE            0x0B91
+#define GL_STENCIL_FUNC                   0x0B92
+#define GL_STENCIL_FAIL                   0x0B94
+#define GL_STENCIL_PASS_DEPTH_FAIL        0x0B95
+#define GL_STENCIL_PASS_DEPTH_PASS        0x0B96
+#define GL_STENCIL_REF                    0x0B97
+#define GL_STENCIL_VALUE_MASK             0x0B93
+#define GL_STENCIL_WRITEMASK              0x0B98
+#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_STENCIL_BACK_REF               0x8CA3
+#define GL_STENCIL_BACK_VALUE_MASK        0x8CA4
+#define GL_STENCIL_BACK_WRITEMASK         0x8CA5
+#define GL_VIEWPORT                       0x0BA2
+#define GL_SCISSOR_BOX                    0x0C10
+/*      GL_SCISSOR_TEST */
+#define GL_COLOR_CLEAR_VALUE              0x0C22
+#define GL_COLOR_WRITEMASK                0x0C23
+#define GL_UNPACK_ALIGNMENT               0x0CF5
+#define GL_PACK_ALIGNMENT                 0x0D05
+#define GL_MAX_TEXTURE_SIZE               0x0D33
+#define GL_MAX_VIEWPORT_DIMS              0x0D3A
+#define GL_SUBPIXEL_BITS                  0x0D50
+#define GL_RED_BITS                       0x0D52
+#define GL_GREEN_BITS                     0x0D53
+#define GL_BLUE_BITS                      0x0D54
+#define GL_ALPHA_BITS                     0x0D55
+#define GL_DEPTH_BITS                     0x0D56
+#define GL_STENCIL_BITS                   0x0D57
+#define GL_POLYGON_OFFSET_UNITS           0x2A00
+/*      GL_POLYGON_OFFSET_FILL */
+#define GL_POLYGON_OFFSET_FACTOR          0x8038
+#define GL_TEXTURE_BINDING_2D             0x8069
+#define GL_SAMPLE_BUFFERS                 0x80A8
+#define GL_SAMPLES                        0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE          0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT         0x80AB
+
+/* GetTextureParameter */
+/*      GL_TEXTURE_MAG_FILTER */
+/*      GL_TEXTURE_MIN_FILTER */
+/*      GL_TEXTURE_WRAP_S */
+/*      GL_TEXTURE_WRAP_T */
+
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3
+
+/* HintMode */
+#define GL_DONT_CARE                      0x1100
+#define GL_FASTEST                        0x1101
+#define GL_NICEST                         0x1102
+
+/* HintTarget */
+#define GL_GENERATE_MIPMAP_HINT            0x8192
+
+/* DataType */
+#define GL_BYTE                           0x1400
+#define GL_UNSIGNED_BYTE                  0x1401
+#define GL_SHORT                          0x1402
+#define GL_UNSIGNED_SHORT                 0x1403
+#define GL_INT                            0x1404
+#define GL_UNSIGNED_INT                   0x1405
+#define GL_FLOAT                          0x1406
+#define GL_FIXED                          0x140C
+
+/* PixelFormat */
+#define GL_DEPTH_COMPONENT                0x1902
+#define GL_ALPHA                          0x1906
+#define GL_RGB                            0x1907
+#define GL_RGBA                           0x1908
+#define GL_LUMINANCE                      0x1909
+#define GL_LUMINANCE_ALPHA                0x190A
+
+/* PixelType */
+/*      GL_UNSIGNED_BYTE */
+#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034
+#define GL_UNSIGNED_SHORT_5_6_5           0x8363
+
+/* Shaders */
+#define GL_FRAGMENT_SHADER                  0x8B30
+#define GL_VERTEX_SHADER                    0x8B31
+#define GL_MAX_VERTEX_ATTRIBS               0x8869
+#define GL_MAX_VERTEX_UNIFORM_VECTORS       0x8DFB
+#define GL_MAX_VARYING_VECTORS              0x8DFC
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS   0x8B4C
+#define GL_MAX_TEXTURE_IMAGE_UNITS          0x8872
+#define GL_MAX_FRAGMENT_UNIFORM_VECTORS     0x8DFD
+#define GL_SHADER_TYPE                      0x8B4F
+#define GL_DELETE_STATUS                    0x8B80
+#define GL_LINK_STATUS                      0x8B82
+#define GL_VALIDATE_STATUS                  0x8B83
+#define GL_ATTACHED_SHADERS                 0x8B85
+#define GL_ACTIVE_UNIFORMS                  0x8B86
+#define GL_ACTIVE_UNIFORM_MAX_LENGTH        0x8B87
+#define GL_ACTIVE_ATTRIBUTES                0x8B89
+#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH      0x8B8A
+#define GL_SHADING_LANGUAGE_VERSION         0x8B8C
+#define GL_CURRENT_PROGRAM                  0x8B8D
+
+/* StencilFunction */
+#define GL_NEVER                          0x0200
+#define GL_LESS                           0x0201
+#define GL_EQUAL                          0x0202
+#define GL_LEQUAL                         0x0203
+#define GL_GREATER                        0x0204
+#define GL_NOTEQUAL                       0x0205
+#define GL_GEQUAL                         0x0206
+#define GL_ALWAYS                         0x0207
+
+/* StencilOp */
+/*      GL_ZERO */
+#define GL_KEEP                           0x1E00
+#define GL_REPLACE                        0x1E01
+#define GL_INCR                           0x1E02
+#define GL_DECR                           0x1E03
+#define GL_INVERT                         0x150A
+#define GL_INCR_WRAP                      0x8507
+#define GL_DECR_WRAP                      0x8508
+
+/* StringName */
+#define GL_VENDOR                         0x1F00
+#define GL_RENDERER                       0x1F01
+#define GL_VERSION                        0x1F02
+#define GL_EXTENSIONS                     0x1F03
+
+/* TextureMagFilter */
+#define GL_NEAREST                        0x2600
+#define GL_LINEAR                         0x2601
+
+/* TextureMinFilter */
+/*      GL_NEAREST */
+/*      GL_LINEAR */
+#define GL_NEAREST_MIPMAP_NEAREST         0x2700
+#define GL_LINEAR_MIPMAP_NEAREST          0x2701
+#define GL_NEAREST_MIPMAP_LINEAR          0x2702
+#define GL_LINEAR_MIPMAP_LINEAR           0x2703
+
+/* TextureParameterName */
+#define GL_TEXTURE_MAG_FILTER             0x2800
+#define GL_TEXTURE_MIN_FILTER             0x2801
+#define GL_TEXTURE_WRAP_S                 0x2802
+#define GL_TEXTURE_WRAP_T                 0x2803
+
+/* TextureTarget */
+/*      GL_TEXTURE_2D */
+#define GL_TEXTURE                        0x1702
+
+#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_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C
+
+/* TextureUnit */
+#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
+
+/* TextureWrapMode */
+#define GL_REPEAT                         0x2901
+#define GL_CLAMP_TO_EDGE                  0x812F
+#define GL_MIRRORED_REPEAT                0x8370
+
+/* Uniform Types */
+#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_2D                     0x8B5E
+#define GL_SAMPLER_CUBE                   0x8B60
+
+/* Vertex Arrays */
+#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_VERTEX_ATTRIB_ARRAY_NORMALIZED     0x886A
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER        0x8645
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
+
+/* Read Format */
+#define GL_IMPLEMENTATION_COLOR_READ_TYPE   0x8B9A
+#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B
+
+/* Shader Source */
+#define GL_COMPILE_STATUS                 0x8B81
+#define GL_INFO_LOG_LENGTH                0x8B84
+#define GL_SHADER_SOURCE_LENGTH           0x8B88
+#define GL_SHADER_COMPILER                0x8DFA
+
+/* Shader Binary */
+#define GL_SHADER_BINARY_FORMATS          0x8DF8
+#define GL_NUM_SHADER_BINARY_FORMATS      0x8DF9
+
+/* Shader Precision-Specified Types */
+#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
+
+/* Framebuffer Object. */
+#define GL_FRAMEBUFFER                    0x8D40
+#define GL_RENDERBUFFER                   0x8D41
+
+#define GL_RGBA4                          0x8056
+#define GL_RGB5_A1                        0x8057
+#define GL_RGB565                         0x8D62
+#define GL_DEPTH_COMPONENT16              0x81A5
+#define GL_STENCIL_INDEX                  0x1901
+#define GL_STENCIL_INDEX8                 0x8D48
+
+#define GL_RENDERBUFFER_WIDTH             0x8D42
+#define GL_RENDERBUFFER_HEIGHT            0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT   0x8D44
+#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_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_COLOR_ATTACHMENT0              0x8CE0
+#define GL_DEPTH_ATTACHMENT               0x8D00
+#define GL_STENCIL_ATTACHMENT             0x8D20
+
+#define GL_NONE                           0
+
+#define GL_FRAMEBUFFER_COMPLETE                      0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT         0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS         0x8CD9
+#define GL_FRAMEBUFFER_UNSUPPORTED                   0x8CDD
+
+#define GL_FRAMEBUFFER_BINDING            0x8CA6
+#define GL_RENDERBUFFER_BINDING           0x8CA7
+#define GL_MAX_RENDERBUFFER_SIZE          0x84E8
+
+#define GL_INVALID_FRAMEBUFFER_OPERATION  0x0506
+
+/*-------------------------------------------------------------------------
+ * GL core functions.
+ *-----------------------------------------------------------------------*/
+
+GL_APICALL void         GL_APIENTRY glActiveTexture (GLenum texture);
+GL_APICALL void         GL_APIENTRY glAttachShader (GLuint program, GLuint shader);
+GL_APICALL void         GL_APIENTRY glBindAttribLocation (GLuint program, GLuint index, const char* name);
+GL_APICALL void         GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer);
+GL_APICALL void         GL_APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer);
+GL_APICALL void         GL_APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer);
+GL_APICALL void         GL_APIENTRY glBindTexture (GLenum target, GLuint texture);
+GL_APICALL void         GL_APIENTRY glBlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+GL_APICALL void         GL_APIENTRY glBlendEquation ( GLenum mode );
+GL_APICALL void         GL_APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
+GL_APICALL void         GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor);
+GL_APICALL void         GL_APIENTRY glBlendFuncSeparate (GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+GL_APICALL void         GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void* data, GLenum usage);
+GL_APICALL void         GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void* data);
+GL_APICALL GLenum       GL_APIENTRY glCheckFramebufferStatus (GLenum target);
+GL_APICALL void         GL_APIENTRY glClear (GLbitfield mask);
+GL_APICALL void         GL_APIENTRY glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+GL_APICALL void         GL_APIENTRY glClearDepthf (GLclampf depth);
+GL_APICALL void         GL_APIENTRY glClearStencil (GLint s);
+GL_APICALL void         GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+GL_APICALL void         GL_APIENTRY glCompileShader (GLuint shader);
+GL_APICALL void         GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data);
+GL_APICALL void         GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data);
+GL_APICALL void         GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+GL_APICALL void         GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL GLuint       GL_APIENTRY glCreateProgram (void);
+GL_APICALL GLuint       GL_APIENTRY glCreateShader (GLenum type);
+GL_APICALL void         GL_APIENTRY glCullFace (GLenum mode);
+GL_APICALL void         GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint* buffers);
+GL_APICALL void         GL_APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint* framebuffers);
+GL_APICALL void         GL_APIENTRY glDeleteProgram (GLuint program);
+GL_APICALL void         GL_APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint* renderbuffers);
+GL_APICALL void         GL_APIENTRY glDeleteShader (GLuint shader);
+GL_APICALL void         GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint* textures);
+GL_APICALL void         GL_APIENTRY glDepthFunc (GLenum func);
+GL_APICALL void         GL_APIENTRY glDepthMask (GLboolean flag);
+GL_APICALL void         GL_APIENTRY glDepthRangef (GLclampf zNear, GLclampf zFar);
+GL_APICALL void         GL_APIENTRY glDetachShader (GLuint program, GLuint shader);
+GL_APICALL void         GL_APIENTRY glDisable (GLenum cap);
+GL_APICALL void         GL_APIENTRY glDisableVertexAttribArray (GLuint index);
+GL_APICALL void         GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count);
+GL_APICALL void         GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void* indices);
+GL_APICALL void         GL_APIENTRY glEnable (GLenum cap);
+GL_APICALL void         GL_APIENTRY glEnableVertexAttribArray (GLuint index);
+GL_APICALL void         GL_APIENTRY glFinish (void);
+GL_APICALL void         GL_APIENTRY glFlush (void);
+GL_APICALL void         GL_APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+GL_APICALL void         GL_APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GL_APICALL void         GL_APIENTRY glFrontFace (GLenum mode);
+GL_APICALL void         GL_APIENTRY glGenBuffers (GLsizei n, GLuint* buffers);
+GL_APICALL void         GL_APIENTRY glGenerateMipmap (GLenum target);
+GL_APICALL void         GL_APIENTRY glGenFramebuffers (GLsizei n, GLuint* framebuffers);
+GL_APICALL void         GL_APIENTRY glGenRenderbuffers (GLsizei n, GLuint* renderbuffers);
+GL_APICALL void         GL_APIENTRY glGenTextures (GLsizei n, GLuint* textures);
+GL_APICALL void         GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name);
+GL_APICALL void         GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name);
+GL_APICALL void         GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders);
+GL_APICALL int          GL_APIENTRY glGetAttribLocation (GLuint program, const char* name);
+GL_APICALL void         GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean* params);
+GL_APICALL void         GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint* params);
+GL_APICALL GLenum       GL_APIENTRY glGetError (void);
+GL_APICALL void         GL_APIENTRY glGetFloatv (GLenum pname, GLfloat* params);
+GL_APICALL void         GL_APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetIntegerv (GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufsize, GLsizei* length, char* infolog);
+GL_APICALL void         GL_APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog);
+GL_APICALL void         GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision);
+GL_APICALL void         GL_APIENTRY glGetShaderSource (GLuint shader, GLsizei bufsize, GLsizei* length, char* source);
+GL_APICALL const GLubyte* GL_APIENTRY glGetString (GLenum name);
+GL_APICALL void         GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat* params);
+GL_APICALL void         GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat* params);
+GL_APICALL void         GL_APIENTRY glGetUniformiv (GLuint program, GLint location, GLint* params);
+GL_APICALL int          GL_APIENTRY glGetUniformLocation (GLuint program, const char* name);
+GL_APICALL void         GL_APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat* params);
+GL_APICALL void         GL_APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint* params);
+GL_APICALL void         GL_APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void** pointer);
+GL_APICALL void         GL_APIENTRY glHint (GLenum target, GLenum mode);
+GL_APICALL GLboolean    GL_APIENTRY glIsBuffer (GLuint buffer);
+GL_APICALL GLboolean    GL_APIENTRY glIsEnabled (GLenum cap);
+GL_APICALL GLboolean    GL_APIENTRY glIsFramebuffer (GLuint framebuffer);
+GL_APICALL GLboolean    GL_APIENTRY glIsProgram (GLuint program);
+GL_APICALL GLboolean    GL_APIENTRY glIsRenderbuffer (GLuint renderbuffer);
+GL_APICALL GLboolean    GL_APIENTRY glIsShader (GLuint shader);
+GL_APICALL GLboolean    GL_APIENTRY glIsTexture (GLuint texture);
+GL_APICALL void         GL_APIENTRY glLineWidth (GLfloat width);
+GL_APICALL void         GL_APIENTRY glLinkProgram (GLuint program);
+GL_APICALL void         GL_APIENTRY glPixelStorei (GLenum pname, GLint param);
+GL_APICALL void         GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units);
+GL_APICALL void         GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
+GL_APICALL void         GL_APIENTRY glReleaseShaderCompiler (void);
+GL_APICALL void         GL_APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+GL_APICALL void         GL_APIENTRY glSampleCoverage (GLclampf value, GLboolean invert);
+GL_APICALL void         GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL void         GL_APIENTRY glShaderBinary (GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length);
+GL_APICALL void         GL_APIENTRY glShaderSource (GLuint shader, GLsizei count, const char** string, const GLint* length);
+GL_APICALL void         GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask);
+GL_APICALL void         GL_APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask);
+GL_APICALL void         GL_APIENTRY glStencilMask (GLuint mask);
+GL_APICALL void         GL_APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask);
+GL_APICALL void         GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass);
+GL_APICALL void         GL_APIENTRY glStencilOpSeparate (GLenum face, GLenum fail, GLenum zfail, GLenum zpass);
+GL_APICALL void         GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels);
+GL_APICALL void         GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param);
+GL_APICALL void         GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat* params);
+GL_APICALL void         GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
+GL_APICALL void         GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint* params);
+GL_APICALL void         GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels);
+GL_APICALL void         GL_APIENTRY glUniform1f (GLint location, GLfloat x);
+GL_APICALL void         GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat* v);
+GL_APICALL void         GL_APIENTRY glUniform1i (GLint location, GLint x);
+GL_APICALL void         GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint* v);
+GL_APICALL void         GL_APIENTRY glUniform2f (GLint location, GLfloat x, GLfloat y);
+GL_APICALL void         GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat* v);
+GL_APICALL void         GL_APIENTRY glUniform2i (GLint location, GLint x, GLint y);
+GL_APICALL void         GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint* v);
+GL_APICALL void         GL_APIENTRY glUniform3f (GLint location, GLfloat x, GLfloat y, GLfloat z);
+GL_APICALL void         GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat* v);
+GL_APICALL void         GL_APIENTRY glUniform3i (GLint location, GLint x, GLint y, GLint z);
+GL_APICALL void         GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint* v);
+GL_APICALL void         GL_APIENTRY glUniform4f (GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GL_APICALL void         GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat* v);
+GL_APICALL void         GL_APIENTRY glUniform4i (GLint location, GLint x, GLint y, GLint z, GLint w);
+GL_APICALL void         GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint* v);
+GL_APICALL void         GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
+GL_APICALL void         GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
+GL_APICALL void         GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value);
+GL_APICALL void         GL_APIENTRY glUseProgram (GLuint program);
+GL_APICALL void         GL_APIENTRY glValidateProgram (GLuint program);
+GL_APICALL void         GL_APIENTRY glVertexAttrib1f (GLuint indx, GLfloat x);
+GL_APICALL void         GL_APIENTRY glVertexAttrib1fv (GLuint indx, const GLfloat* values);
+GL_APICALL void         GL_APIENTRY glVertexAttrib2f (GLuint indx, GLfloat x, GLfloat y);
+GL_APICALL void         GL_APIENTRY glVertexAttrib2fv (GLuint indx, const GLfloat* values);
+GL_APICALL void         GL_APIENTRY glVertexAttrib3f (GLuint indx, GLfloat x, GLfloat y, GLfloat z);
+GL_APICALL void         GL_APIENTRY glVertexAttrib3fv (GLuint indx, const GLfloat* values);
+GL_APICALL void         GL_APIENTRY glVertexAttrib4f (GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GL_APICALL void         GL_APIENTRY glVertexAttrib4fv (GLuint indx, const GLfloat* values);
+GL_APICALL void         GL_APIENTRY glVertexAttribPointer (GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr);
+GL_APICALL void         GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gl2_h_ */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES2/gl2ext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,667 @@
+#ifndef __gl2ext_h_
+#define __gl2ext_h_
+
+/* $Revision: 9499 $ on $Date:: 2009-10-30 13:10:08 -0700 #$ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+#ifndef GL_APIENTRYP
+#   define GL_APIENTRYP GL_APIENTRY*
+#endif
+
+/*------------------------------------------------------------------------*
+ * OES extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_OES_compressed_ETC1_RGB8_texture */
+#ifndef GL_OES_compressed_ETC1_RGB8_texture
+#define GL_ETC1_RGB8_OES                                        0x8D64
+#endif
+
+/* GL_OES_compressed_paletted_texture */
+#ifndef GL_OES_compressed_paletted_texture
+#define GL_PALETTE4_RGB8_OES                                    0x8B90
+#define GL_PALETTE4_RGBA8_OES                                   0x8B91
+#define GL_PALETTE4_R5_G6_B5_OES                                0x8B92
+#define GL_PALETTE4_RGBA4_OES                                   0x8B93
+#define GL_PALETTE4_RGB5_A1_OES                                 0x8B94
+#define GL_PALETTE8_RGB8_OES                                    0x8B95
+#define GL_PALETTE8_RGBA8_OES                                   0x8B96
+#define GL_PALETTE8_R5_G6_B5_OES                                0x8B97
+#define GL_PALETTE8_RGBA4_OES                                   0x8B98
+#define GL_PALETTE8_RGB5_A1_OES                                 0x8B99
+#endif
+
+/* GL_OES_depth24 */
+#ifndef GL_OES_depth24
+#define GL_DEPTH_COMPONENT24_OES                                0x81A6
+#endif
+
+/* GL_OES_depth32 */
+#ifndef GL_OES_depth32
+#define GL_DEPTH_COMPONENT32_OES                                0x81A7
+#endif
+
+/* GL_OES_depth_texture */
+/* No new tokens introduced by this extension. */
+
+/* GL_OES_EGL_image */
+#ifndef GL_OES_EGL_image
+typedef void* GLeglImageOES;
+#endif
+
+/* GL_OES_get_program_binary */
+#ifndef GL_OES_get_program_binary
+#define GL_PROGRAM_BINARY_LENGTH_OES                            0x8741
+#define GL_NUM_PROGRAM_BINARY_FORMATS_OES                       0x87FE
+#define GL_PROGRAM_BINARY_FORMATS_OES                           0x87FF
+#endif
+
+/* GL_OES_mapbuffer */
+#ifndef GL_OES_mapbuffer
+#define GL_WRITE_ONLY_OES                                       0x88B9
+#define GL_BUFFER_ACCESS_OES                                    0x88BB
+#define GL_BUFFER_MAPPED_OES                                    0x88BC
+#define GL_BUFFER_MAP_POINTER_OES                               0x88BD
+#endif
+
+/* GL_OES_packed_depth_stencil */
+#ifndef GL_OES_packed_depth_stencil
+#define GL_DEPTH_STENCIL_OES                                    0x84F9
+#define GL_UNSIGNED_INT_24_8_OES                                0x84FA
+#define GL_DEPTH24_STENCIL8_OES                                 0x88F0
+#endif
+
+/* GL_OES_rgb8_rgba8 */
+#ifndef GL_OES_rgb8_rgba8
+#define GL_RGB8_OES                                             0x8051
+#define GL_RGBA8_OES                                            0x8058
+#endif
+
+/* GL_OES_standard_derivatives */
+#ifndef GL_OES_standard_derivatives
+#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES                  0x8B8B
+#endif
+
+/* GL_OES_stencil1 */
+#ifndef GL_OES_stencil1
+#define GL_STENCIL_INDEX1_OES                                   0x8D46
+#endif
+
+/* GL_OES_stencil4 */
+#ifndef GL_OES_stencil4
+#define GL_STENCIL_INDEX4_OES                                   0x8D47
+#endif
+
+/* GL_OES_texture_3D */
+#ifndef GL_OES_texture_3D
+#define GL_TEXTURE_WRAP_R_OES                                   0x8072
+#define GL_TEXTURE_3D_OES                                       0x806F
+#define GL_TEXTURE_BINDING_3D_OES                               0x806A
+#define GL_MAX_3D_TEXTURE_SIZE_OES                              0x8073
+#define GL_SAMPLER_3D_OES                                       0x8B5F
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES        0x8CD4
+#endif
+
+/* GL_OES_texture_float */
+/* No new tokens introduced by this extension. */
+
+/* GL_OES_texture_float_linear */
+/* No new tokens introduced by this extension. */
+
+/* GL_OES_texture_half_float */
+#ifndef GL_OES_texture_half_float
+#define GL_HALF_FLOAT_OES                                       0x8D61
+#endif
+
+/* GL_OES_texture_half_float_linear */
+/* No new tokens introduced by this extension. */
+
+/* GL_OES_texture_npot */
+/* No new tokens introduced by this extension. */
+
+/* GL_OES_vertex_half_float */
+/* GL_HALF_FLOAT_OES defined in GL_OES_texture_half_float already. */
+
+/* GL_OES_vertex_type_10_10_10_2 */
+#ifndef GL_OES_vertex_type_10_10_10_2
+#define GL_UNSIGNED_INT_10_10_10_2_OES                          0x8DF6
+#define GL_INT_10_10_10_2_OES                                   0x8DF7
+#endif
+
+/*------------------------------------------------------------------------*
+ * AMD extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_AMD_compressed_3DC_texture */
+#ifndef GL_AMD_compressed_3DC_texture
+#define GL_3DC_X_AMD                                            0x87F9
+#define GL_3DC_XY_AMD                                           0x87FA
+#endif
+
+/* GL_AMD_compressed_ATC_texture */
+#ifndef GL_AMD_compressed_ATC_texture
+#define GL_ATC_RGB_AMD                                          0x8C92
+#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD                          0x8C93
+#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD                      0x87EE
+#endif
+
+/* GL_AMD_performance_monitor */
+#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
+
+/* GL_AMD_program_binary_Z400 */
+#ifndef GL_AMD_program_binary_Z400
+#define GL_Z400_BINARY_AMD                                      0x8740
+#endif
+
+/*------------------------------------------------------------------------*
+ * EXT extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_EXT_blend_minmax */
+#ifndef GL_EXT_blend_minmax
+#define GL_MIN_EXT                                              0x8007
+#define GL_MAX_EXT                                              0x8008
+#endif
+
+/* GL_EXT_discard_framebuffer */
+#ifndef GL_EXT_discard_framebuffer
+#define GL_COLOR_EXT                                            0x1800
+#define GL_DEPTH_EXT                                            0x1801
+#define GL_STENCIL_EXT                                          0x1802
+#endif
+
+/* GL_EXT_multi_draw_arrays */
+/* No new tokens introduced by this extension. */
+
+/* GL_EXT_read_format_bgra */
+#ifndef GL_EXT_read_format_bgra
+#define GL_BGRA_EXT                                             0x80E1
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT                       0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT                       0x8366
+#endif
+
+/* GL_EXT_texture_filter_anisotropic */
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT                           0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT                       0x84FF
+#endif
+
+/* GL_EXT_texture_format_BGRA8888 */
+#ifndef GL_EXT_texture_format_BGRA8888
+#define GL_BGRA_EXT                                             0x80E1
+#endif
+
+/* GL_EXT_texture_type_2_10_10_10_REV */
+#ifndef GL_EXT_texture_type_2_10_10_10_REV
+#define GL_UNSIGNED_INT_2_10_10_10_REV_EXT                      0x8368
+#endif
+
+/*------------------------------------------------------------------------*
+ * IMG extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_IMG_program_binary */
+#ifndef GL_IMG_program_binary
+#define GL_SGX_PROGRAM_BINARY_IMG                               0x9130
+#endif
+
+/* GL_IMG_read_format */
+#ifndef GL_IMG_read_format
+#define GL_BGRA_IMG                                             0x80E1
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG                       0x8365
+#endif
+
+/* GL_IMG_shader_binary */
+#ifndef GL_IMG_shader_binary
+#define GL_SGX_BINARY_IMG                                       0x8C0A
+#endif
+
+/* GL_IMG_texture_compression_pvrtc */
+#ifndef GL_IMG_texture_compression_pvrtc
+#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG                      0x8C00
+#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG                      0x8C01
+#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG                     0x8C02
+#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG                     0x8C03
+#endif
+
+/*------------------------------------------------------------------------*
+ * NV extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_NV_fence */
+#ifndef GL_NV_fence
+#define GL_ALL_COMPLETED_NV                                     0x84F2
+#define GL_FENCE_STATUS_NV                                      0x84F3
+#define GL_FENCE_CONDITION_NV                                   0x84F4
+#endif
+
+/*------------------------------------------------------------------------*
+ * QCOM extension tokens
+ *------------------------------------------------------------------------*/
+
+/* GL_QCOM_driver_control */
+/* No new tokens introduced by this extension. */
+
+/* GL_QCOM_extended_get */
+#ifndef GL_QCOM_extended_get
+#define GL_TEXTURE_WIDTH_QCOM                                   0x8BD2
+#define GL_TEXTURE_HEIGHT_QCOM                                  0x8BD3
+#define GL_TEXTURE_DEPTH_QCOM                                   0x8BD4
+#define GL_TEXTURE_INTERNAL_FORMAT_QCOM                         0x8BD5
+#define GL_TEXTURE_FORMAT_QCOM                                  0x8BD6
+#define GL_TEXTURE_TYPE_QCOM                                    0x8BD7
+#define GL_TEXTURE_IMAGE_VALID_QCOM                             0x8BD8
+#define GL_TEXTURE_NUM_LEVELS_QCOM                              0x8BD9
+#define GL_TEXTURE_TARGET_QCOM                                  0x8BDA
+#define GL_TEXTURE_OBJECT_VALID_QCOM                            0x8BDB
+#define GL_STATE_RESTORE                                        0x8BDC
+#endif
+
+/* GL_QCOM_extended_get2 */
+/* No new tokens introduced by this extension. */
+
+/* GL_QCOM_perfmon_global_mode */
+#ifndef GL_QCOM_perfmon_global_mode
+#define GL_PERFMON_GLOBAL_MODE_QCOM                             0x8FA0
+#endif
+
+/* GL_QCOM_writeonly_rendering */
+#ifndef GL_QCOM_writeonly_rendering
+#define GL_WRITEONLY_RENDERING_QCOM                             0x8823
+#endif
+
+/*------------------------------------------------------------------------*
+ * End of extension tokens, start of corresponding extension functions
+ *------------------------------------------------------------------------*/
+
+/*------------------------------------------------------------------------*
+ * OES extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_OES_compressed_ETC1_RGB8_texture */
+#ifndef GL_OES_compressed_ETC1_RGB8_texture
+#define GL_OES_compressed_ETC1_RGB8_texture 1
+#endif
+
+/* GL_OES_compressed_paletted_texture */
+#ifndef GL_OES_compressed_paletted_texture
+#define GL_OES_compressed_paletted_texture 1
+#endif
+
+/* GL_OES_depth24 */
+#ifndef GL_OES_depth24
+#define GL_OES_depth24 1
+#endif
+
+/* GL_OES_depth32 */
+#ifndef GL_OES_depth32
+#define GL_OES_depth32 1
+#endif
+
+/* GL_OES_depth_texture */
+#ifndef GL_OES_depth_texture
+#define GL_OES_depth_texture 1
+#endif
+
+/* GL_OES_EGL_image */
+#ifndef GL_OES_EGL_image
+#define GL_OES_EGL_image 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image);
+GL_APICALL void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image);
+#endif
+typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
+typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
+#endif
+
+/* GL_OES_element_index_uint */
+#ifndef GL_OES_element_index_uint
+#define GL_OES_element_index_uint 1
+#endif
+
+/* GL_OES_fbo_render_mipmap */
+#ifndef GL_OES_fbo_render_mipmap
+#define GL_OES_fbo_render_mipmap 1
+#endif
+
+/* GL_OES_fragment_precision_high */
+#ifndef GL_OES_fragment_precision_high
+#define GL_OES_fragment_precision_high 1
+#endif
+
+/* GL_OES_get_program_binary */
+#ifndef GL_OES_get_program_binary
+#define GL_OES_get_program_binary 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetProgramBinaryOES (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+GL_APICALL void GL_APIENTRY glProgramBinaryOES (GLuint program, GLenum binaryFormat, const void *binary, GLint length);
+#endif
+typedef void (GL_APIENTRYP PFNGLGETPROGRAMBINARYOESPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary);
+typedef void (GL_APIENTRYP PFNGLPROGRAMBINARYOESPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLint length);
+#endif
+
+/* GL_OES_mapbuffer */
+#ifndef GL_OES_mapbuffer
+#define GL_OES_mapbuffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void* GL_APIENTRY glMapBufferOES (GLenum target, GLenum access);
+GL_APICALL GLboolean GL_APIENTRY glUnmapBufferOES (GLenum target);
+GL_APICALL void GL_APIENTRY glGetBufferPointervOES (GLenum target, GLenum pname, void** params);
+#endif
+typedef void* (GL_APIENTRYP PFNGLMAPBUFFEROESPROC) (GLenum target, GLenum access);
+typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFEROESPROC) (GLenum target);
+typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVOESPROC) (GLenum target, GLenum pname, void** params);
+#endif
+
+/* GL_OES_packed_depth_stencil */
+#ifndef GL_OES_packed_depth_stencil
+#define GL_OES_packed_depth_stencil 1
+#endif
+
+/* GL_OES_rgb8_rgba8 */
+#ifndef GL_OES_rgb8_rgba8
+#define GL_OES_rgb8_rgba8 1
+#endif
+
+/* GL_OES_standard_derivatives */
+#ifndef GL_OES_standard_derivatives
+#define GL_OES_standard_derivatives 1
+#endif
+
+/* GL_OES_stencil1 */
+#ifndef GL_OES_stencil1
+#define GL_OES_stencil1 1
+#endif
+
+/* GL_OES_stencil4 */
+#ifndef GL_OES_stencil4
+#define GL_OES_stencil4 1
+#endif
+
+/* GL_OES_texture_3D */
+#ifndef GL_OES_texture_3D
+#define GL_OES_texture_3D 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels);
+GL_APICALL void GL_APIENTRY glTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels);
+GL_APICALL void GL_APIENTRY glCopyTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GL_APICALL void GL_APIENTRY glCompressedTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void* data);
+GL_APICALL void GL_APIENTRY glCompressedTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void* data);
+GL_APICALL void GL_APIENTRY glFramebufferTexture3DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+#endif
+typedef void (GL_APIENTRYP PFNGLTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels);
+typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* pixels);
+typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void* data);
+typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void* data);
+typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DOES) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+#endif
+
+/* GL_OES_texture_float */
+#ifndef GL_OES_texture_float
+#define GL_OES_texture_float 1
+#endif
+
+/* GL_OES_texture_float_linear */
+#ifndef GL_OES_texture_float_linear
+#define GL_OES_texture_float_linear 1
+#endif
+
+/* GL_OES_texture_half_float */
+#ifndef GL_OES_texture_half_float
+#define GL_OES_texture_half_float 1
+#endif
+
+/* GL_OES_texture_half_float_linear */
+#ifndef GL_OES_texture_half_float_linear
+#define GL_OES_texture_half_float_linear 1
+#endif
+
+/* GL_OES_texture_npot */
+#ifndef GL_OES_texture_npot
+#define GL_OES_texture_npot 1
+#endif
+
+/* GL_OES_vertex_half_float */
+#ifndef GL_OES_vertex_half_float
+#define GL_OES_vertex_half_float 1
+#endif
+
+/* GL_OES_vertex_type_10_10_10_2 */
+#ifndef GL_OES_vertex_type_10_10_10_2
+#define GL_OES_vertex_type_10_10_10_2 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * AMD extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_AMD_compressed_3DC_texture */
+#ifndef GL_AMD_compressed_3DC_texture
+#define GL_AMD_compressed_3DC_texture 1
+#endif
+
+/* GL_AMD_compressed_ATC_texture */
+#ifndef GL_AMD_compressed_ATC_texture
+#define GL_AMD_compressed_ATC_texture 1
+#endif
+
+/* AMD_performance_monitor */
+#ifndef GL_AMD_performance_monitor
+#define GL_AMD_performance_monitor 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, char *groupString);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, char *counterString);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data);
+GL_APICALL void GL_APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors);
+GL_APICALL void GL_APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors);
+GL_APICALL void GL_APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList);
+GL_APICALL void GL_APIENTRY glBeginPerfMonitorAMD (GLuint monitor);
+GL_APICALL void GL_APIENTRY glEndPerfMonitorAMD (GLuint monitor);
+GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
+#endif
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, char *groupString);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, char *counterString);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data);
+typedef void (GL_APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
+typedef void (GL_APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
+typedef void (GL_APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *countersList);
+typedef void (GL_APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (GL_APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
+#endif
+
+/* GL_AMD_program_binary_Z400 */
+#ifndef GL_AMD_program_binary_Z400
+#define GL_AMD_program_binary_Z400 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * EXT extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_EXT_blend_minmax */
+#ifndef GL_EXT_blend_minmax
+#define GL_EXT_blend_minmax 1
+#endif
+
+/* GL_EXT_discard_framebuffer */
+#ifndef GL_EXT_discard_framebuffer
+#define GL_EXT_discard_framebuffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDiscardFramebufferEXT (GLenum target, GLsizei numAttachments, const GLenum *attachments);
+#endif
+typedef void (GL_APIENTRYP PFNGLDISCARDFRAMEBUFFEREXTPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments);
+#endif
+
+#ifndef GL_EXT_multi_draw_arrays
+#define GL_EXT_multi_draw_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei);
+GL_APICALL void GL_APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
+typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+#endif
+
+/* GL_EXT_read_format_bgra */
+#ifndef GL_EXT_read_format_bgra
+#define GL_EXT_read_format_bgra 1
+#endif
+
+/* GL_EXT_texture_filter_anisotropic */
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_EXT_texture_filter_anisotropic 1
+#endif
+
+/* GL_EXT_texture_format_BGRA8888 */
+#ifndef GL_EXT_texture_format_BGRA8888
+#define GL_EXT_texture_format_BGRA8888 1
+#endif
+
+/* GL_EXT_texture_type_2_10_10_10_REV */
+#ifndef GL_EXT_texture_type_2_10_10_10_REV
+#define GL_EXT_texture_type_2_10_10_10_REV 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * IMG extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_IMG_program_binary */
+#ifndef GL_IMG_program_binary
+#define GL_IMG_program_binary 1
+#endif
+
+/* GL_IMG_read_format */
+#ifndef GL_IMG_read_format
+#define GL_IMG_read_format 1
+#endif
+
+/* GL_IMG_shader_binary */
+#ifndef GL_IMG_shader_binary
+#define GL_IMG_shader_binary 1
+#endif
+
+/* GL_IMG_texture_compression_pvrtc */
+#ifndef GL_IMG_texture_compression_pvrtc
+#define GL_IMG_texture_compression_pvrtc 1
+#endif
+
+/*------------------------------------------------------------------------*
+ * NV extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_NV_fence */
+#ifndef GL_NV_fence
+#define GL_NV_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glDeleteFencesNV (GLsizei, const GLuint *);
+GL_APICALL void GL_APIENTRY glGenFencesNV (GLsizei, GLuint *);
+GL_APICALL GLboolean GL_APIENTRY glIsFenceNV (GLuint);
+GL_APICALL GLboolean GL_APIENTRY glTestFenceNV (GLuint);
+GL_APICALL void GL_APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *);
+GL_APICALL void GL_APIENTRY glFinishFenceNV (GLuint);
+GL_APICALL void GL_APIENTRY glSetFenceNV (GLuint, GLenum);
+#endif
+typedef void (GL_APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
+typedef void (GL_APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
+typedef GLboolean (GL_APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
+typedef GLboolean (GL_APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
+typedef void (GL_APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
+typedef void (GL_APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
+#endif
+
+/*------------------------------------------------------------------------*
+ * QCOM extension functions
+ *------------------------------------------------------------------------*/
+
+/* GL_QCOM_driver_control */
+#ifndef GL_QCOM_driver_control
+#define GL_QCOM_driver_control 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glGetDriverControlsQCOM (GLint *num, GLsizei size, GLuint *driverControls);
+GL_APICALL void GL_APIENTRY glGetDriverControlStringQCOM (GLuint driverControl, GLsizei bufSize, GLsizei *length, char *driverControlString);
+GL_APICALL void GL_APIENTRY glEnableDriverControlQCOM (GLuint driverControl);
+GL_APICALL void GL_APIENTRY glDisableDriverControlQCOM (GLuint driverControl);
+#endif
+typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSQCOMPROC) (GLint *num, GLsizei size, GLuint *driverControls);
+typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSTRINGQCOMPROC) (GLuint driverControl, GLsizei bufSize, GLsizei *length, char *driverControlString);
+typedef void (GL_APIENTRYP PFNGLENABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
+typedef void (GL_APIENTRYP PFNGLDISABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl);
+#endif
+
+/* GL_QCOM_extended_get */
+#ifndef GL_QCOM_extended_get
+#define GL_QCOM_extended_get 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glExtGetTexturesQCOM (GLuint *textures, GLint maxTextures, GLint *numTextures);
+GL_APICALL void GL_APIENTRY glExtGetBuffersQCOM (GLuint *buffers, GLint maxBuffers, GLint *numBuffers);
+GL_APICALL void GL_APIENTRY glExtGetRenderbuffersQCOM (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers);
+GL_APICALL void GL_APIENTRY glExtGetFramebuffersQCOM (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers);
+GL_APICALL void GL_APIENTRY glExtGetTexLevelParameterivQCOM (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params);
+GL_APICALL void GL_APIENTRY glExtTexObjectStateOverrideiQCOM (GLenum target, GLenum pname, GLint param);
+GL_APICALL void GL_APIENTRY glExtGetTexSubImageQCOM (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, void *texels);
+GL_APICALL void GL_APIENTRY glExtGetBufferPointervQCOM (GLenum target, void **params);
+#endif
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXTURESQCOMPROC) (GLuint *textures, GLint maxTextures, GLint *numTextures);
+typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERSQCOMPROC) (GLuint *buffers, GLint maxBuffers, GLint *numBuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETRENDERBUFFERSQCOMPROC) (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETFRAMEBUFFERSQCOMPROC) (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers);
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC) (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params);
+typedef void (GL_APIENTRYP PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (GL_APIENTRYP PFNGLEXTGETTEXSUBIMAGEQCOMPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, void *texels);
+typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERPOINTERVQCOMPROC) (GLenum target, void **params);
+#endif
+
+/* GL_QCOM_extended_get2 */
+#ifndef GL_QCOM_extended_get2
+#define GL_QCOM_extended_get2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GL_APICALL void GL_APIENTRY glExtGetShadersQCOM (GLuint *shaders, GLint maxShaders, GLint *numShaders);
+GL_APICALL void GL_APIENTRY glExtGetProgramsQCOM (GLuint *programs, GLint maxPrograms, GLint *numPrograms);
+GL_APICALL GLboolean GL_APIENTRY glExtIsProgramBinaryQCOM (GLuint program);
+GL_APICALL void GL_APIENTRY glExtGetProgramBinarySourceQCOM (GLuint program, GLenum shadertype, char *source, GLint *length);
+#endif
+typedef void (GL_APIENTRYP PFNGLEXTGETSHADERSQCOMPROC) (GLuint *shaders, GLint maxShaders, GLint *numShaders);
+typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMSQCOMPROC) (GLuint *programs, GLint maxPrograms, GLint *numPrograms);
+typedef GLboolean (GL_APIENTRYP PFNGLEXTISPROGRAMBINARYQCOMPROC) (GLuint program);
+typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC) (GLuint program, GLenum shadertype, char *source, GLint *length);
+#endif
+
+/* GL_QCOM_perfmon_global_mode */
+#ifndef GL_QCOM_perfmon_global_mode
+#define GL_QCOM_perfmon_global_mode 1
+#endif
+
+/* GL_QCOM_writeonly_rendering */
+#ifndef GL_QCOM_writeonly_rendering
+#define GL_QCOM_writeonly_rendering 1
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gl2ext_h_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES2/gl2platform.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,32 @@
+#ifndef __gl2platform_h_
+#define __gl2platform_h_
+
+/* $Revision: 9660 $ on $Date:: 2009-11-19 02:28:28 -0800 #$ */
+
+/*
+ * This document is licensed under the SGI Free Software B License Version
+ * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ .
+ */
+
+/* Platform-specific types and definitions for OpenGL ES 2.X  gl2.h
+ * Last modified on 2009/11/19
+ *
+ * Adopters may modify khrplatform.h and this file to suit their platform.
+ * You are encouraged to submit all modifications to the Khronos group so that
+ * they can be included in future versions of this file.  Please submit changes
+ * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla)
+ * by filing a bug against product "OpenGL-ES" component "Registry".
+ */
+
+#include <KHR/khrplatform.h>
+
+#ifndef GL_APICALL
+#define GL_APICALL  KHRONOS_APICALL
+#endif
+
+#ifndef GL_APIENTRY
+#define GL_APIENTRY KHRONOS_APIENTRY
+#endif
+
+#endif /* __gl2platform_h_ */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLES2Interface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,58 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLES2INTERFACE_H_
+#define _GLES2INTERFACE_H_
+
+#include "GLESInterface.h"
+#include "SurfaceDescriptor.h"
+
+enum EImageTarget;
+
+enum EStatus {
+	DGLES2_SUCCESS,
+	DGLES2_BAD_PARAMETER,
+	DGLES2_BAD_MATCH
+};
+
+class CColorDescriptor;
+
+class IEGLtoGLES2Interface : public IEGLtoGLESInterface
+    {
+public:
+    virtual EStatus GetTextureInfo( void* context, EImageTarget target, void* texture, int textureLevel, SurfaceDescriptor& desc ) = 0;
+    virtual EStatus GetTextureData( void* context, EImageTarget target, void* texture, int textureLevel, void* data ) = 0;
+	virtual bool UpdateImageSibling( EImageTarget target, void* name ) = 0;
+    };
+
+typedef IEGLtoGLES2Interface* (*fpGetGLES2Interface)(void);
+IEGLtoGLES2Interface* LoadGLES2Interface( void*& libraryHandle );
+
+#endif // _GLES2INTERFACE_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/GLESInterface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,76 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _GLESINTERFACE_H_
+#define _GLESINTERFACE_H_
+
+#include "ImageTarget.h"
+
+struct SurfaceDescriptor;
+
+typedef void (*fpGLProc)(void);
+
+class IGLEStoEGLInterface
+    {
+public:
+    virtual void* GetGLESContext() = 0;
+    virtual bool IsImageInUse( void* image ) = 0;
+    virtual bool LockGLESSurface( bool read, bool draw ) = 0;
+    virtual bool UnlockGLESSurface() = 0;
+	virtual void* GetHostProcAddress( const char* proc ) = 0;
+	virtual void GetDescForImage( void* image, SurfaceDescriptor& ImageDesc ) = 0;
+    virtual void* GetDataForImage( void* image ) = 0;
+	virtual void RegisterImageTarget( void* image, EImageTarget target, void* buffer ) = 0;
+	virtual void UnregisterImageTarget( void* image, EImageTarget target, void* buffer ) = 0;
+	virtual void UpdateImageSiblings( void* image, EImageTarget target, void* buffer ) = 0;
+	virtual void ReleaseTexImage(void* surface, int name, int level) = 0;
+    };
+
+// GLES services for EGL 
+class IEGLtoGLESInterface
+    {
+public:
+    virtual void SetEGLInterface( IGLEStoEGLInterface* ) = 0;
+	virtual void* CreateContext( void* nativeContext ) = 0;
+	virtual bool ReleaseContext( void* context ) = 0;
+	virtual void* GetNativeContext( void* context ) = 0;
+	virtual fpGLProc GetGLProcAddress( const char *procname ) = 0;
+    virtual int BindTexImage( void* surface, int level, bool generateMipmap, const SurfaceDescriptor* desc, void* buffer ) = 0;
+	virtual bool ReleaseTexImage( int name, int level ) = 0;
+    virtual bool CopyBuffers( void* buf, const SurfaceDescriptor* desc ) = 0;
+    virtual bool UpdateBuffers( void* buf, const SurfaceDescriptor* desc ) = 0;
+    virtual void Flush() = 0;
+    virtual void Finish() = 0;
+    };
+
+typedef IEGLtoGLESInterface* (*fpGetGLES1Interface)(void);
+IEGLtoGLESInterface* LoadGLES1Interface( void*& libraryHandle );
+
+#endif // _GLESINTERFACE_H_
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/ImageTarget.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,45 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _IMAGETARGET_H_
+#define _IMAGETARGET_H_
+
+enum EImageTarget {
+	IMAGE_TARGET_TEXTURE_2D,
+	IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_X,
+    IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_X,
+    IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Y,
+    IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Y,
+    IMAGE_TARGET_TEXTURE_CUBE_MAP_POSITIVE_Z,
+    IMAGE_TARGET_TEXTURE_CUBE_MAP_NEGATIVE_Z,
+	IMAGE_TARGET_RENDERBUFFER
+};
+
+#endif // _IMAGETARGET_H_
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/KHR/khrplatform.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,273 @@
+#ifndef __khrplatform_h_
+#define __khrplatform_h_
+
+/*
+** Copyright (c) 2008-2009 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.
+*/
+
+/* Khronos platform-specific types and definitions.
+ *
+ * $Revision: 9356 $ on $Date: 2009-10-21 02:52:25 -0700 (Wed, 21 Oct 2009) $
+ *
+ * Adopters may modify this file to suit their platform. Adopters are
+ * encouraged to submit platform specific modifications to the Khronos
+ * group so that they can be included in future versions of this file.
+ * Please submit changes by sending them to the public Khronos Bugzilla
+ * (http://khronos.org/bugzilla) by filing a bug against product
+ * "Khronos (general)" component "Registry".
+ *
+ * A predefined template which fills in some of the bug fields can be
+ * reached using http://tinyurl.com/khrplatform-h-bugreport, but you
+ * must create a Bugzilla login first.
+ *
+ *
+ * See the Implementer's Guidelines for information about where this file
+ * should be located on your system and for more details of its use:
+ *    http://www.khronos.org/registry/implementers_guide.pdf
+ *
+ * This file should be included as
+ *        #include <KHR/khrplatform.h>
+ * by Khronos client API header files that use its types and defines.
+ *
+ * The types in khrplatform.h should only be used to define API-specific types.
+ *
+ * Types defined in khrplatform.h:
+ *    khronos_int8_t              signed   8  bit
+ *    khronos_uint8_t             unsigned 8  bit
+ *    khronos_int16_t             signed   16 bit
+ *    khronos_uint16_t            unsigned 16 bit
+ *    khronos_int32_t             signed   32 bit
+ *    khronos_uint32_t            unsigned 32 bit
+ *    khronos_int64_t             signed   64 bit
+ *    khronos_uint64_t            unsigned 64 bit
+ *    khronos_intptr_t            signed   same number of bits as a pointer
+ *    khronos_uintptr_t           unsigned same number of bits as a pointer
+ *    khronos_ssize_t             signed   size
+ *    khronos_usize_t             unsigned size
+ *    khronos_float_t             signed   32 bit floating point
+ *    khronos_time_ns_t           unsigned 64 bit time in nanoseconds
+ *    khronos_utime_nanoseconds_t unsigned time interval or absolute time in
+ *                                         nanoseconds
+ *    khronos_stime_nanoseconds_t signed time interval in nanoseconds
+ *    khronos_boolean_enum_t      enumerated boolean type. This should
+ *      only be used as a base type when a client API's boolean type is
+ *      an enum. Client APIs which use an integer or other type for
+ *      booleans cannot use this as the base type for their boolean.
+ *
+ * Tokens defined in khrplatform.h:
+ *
+ *    KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
+ *
+ *    KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
+ *    KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
+ *
+ * Calling convention macros defined in this file:
+ *    KHRONOS_APICALL
+ *    KHRONOS_APIENTRY
+ *    KHRONOS_APIATTRIBUTES
+ *
+ * These may be used in function prototypes as:
+ *
+ *      KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
+ *                                  int arg1,
+ *                                  int arg2) KHRONOS_APIATTRIBUTES;
+ */
+
+/*-------------------------------------------------------------------------
+ * Definition of KHRONOS_APICALL
+ *-------------------------------------------------------------------------
+ * This precedes the return type of the function in the function prototype.
+ */
+#if defined(_WIN32) && !defined(__SCITECH_SNAP__)
+    #if defined (KHRONOS_APICALL_EXPORT)
+        #   define KHRONOS_APICALL __declspec(dllexport)
+    #else
+        #   define KHRONOS_APICALL __declspec(dllimport)
+    #endif
+#elif defined (__SYMBIAN32__)
+#   define KHRONOS_APICALL IMPORT_C
+#else
+#   define KHRONOS_APICALL
+#endif
+
+/*-------------------------------------------------------------------------
+ * Definition of KHRONOS_APIENTRY
+ *-------------------------------------------------------------------------
+ * This follows the return type of the function  and precedes the function
+ * name in the function prototype.
+ */
+#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
+    /* Win32 but not WinCE */
+#   define KHRONOS_APIENTRY __stdcall
+#else
+#   define KHRONOS_APIENTRY
+#endif
+
+/*-------------------------------------------------------------------------
+ * Definition of KHRONOS_APIATTRIBUTES
+ *-------------------------------------------------------------------------
+ * This follows the closing parenthesis of the function prototype arguments.
+ */
+#if defined (__ARMCC_2__)
+#define KHRONOS_APIATTRIBUTES __softfp
+#else
+#define KHRONOS_APIATTRIBUTES
+#endif
+
+/*-------------------------------------------------------------------------
+ * basic type definitions
+ *-----------------------------------------------------------------------*/
+#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
+
+
+/*
+ * Using <stdint.h>
+ */
+#include <stdint.h>
+typedef int32_t                 khronos_int32_t;
+typedef uint32_t                khronos_uint32_t;
+typedef int64_t                 khronos_int64_t;
+typedef uint64_t                khronos_uint64_t;
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#elif defined(__VMS ) || defined(__sgi)
+
+/*
+ * Using <inttypes.h>
+ */
+#include <inttypes.h>
+typedef int32_t                 khronos_int32_t;
+typedef uint32_t                khronos_uint32_t;
+typedef int64_t                 khronos_int64_t;
+typedef uint64_t                khronos_uint64_t;
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
+
+/*
+ * Win32
+ */
+typedef __int32                 khronos_int32_t;
+typedef unsigned __int32        khronos_uint32_t;
+typedef __int64                 khronos_int64_t;
+typedef unsigned __int64        khronos_uint64_t;
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#elif defined(__sun__) || defined(__digital__)
+
+/*
+ * Sun or Digital
+ */
+typedef int                     khronos_int32_t;
+typedef unsigned int            khronos_uint32_t;
+#if defined(__arch64__) || defined(_LP64)
+typedef long int                khronos_int64_t;
+typedef unsigned long int       khronos_uint64_t;
+#else
+typedef long long int           khronos_int64_t;
+typedef unsigned long long int  khronos_uint64_t;
+#endif /* __arch64__ */
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#elif 0
+
+/*
+ * Hypothetical platform with no float or int64 support
+ */
+typedef int                     khronos_int32_t;
+typedef unsigned int            khronos_uint32_t;
+#define KHRONOS_SUPPORT_INT64   0
+#define KHRONOS_SUPPORT_FLOAT   0
+
+#else
+
+/*
+ * Generic fallback
+ */
+#include <stdint.h>
+typedef int32_t                 khronos_int32_t;
+typedef uint32_t                khronos_uint32_t;
+typedef int64_t                 khronos_int64_t;
+typedef uint64_t                khronos_uint64_t;
+#define KHRONOS_SUPPORT_INT64   1
+#define KHRONOS_SUPPORT_FLOAT   1
+
+#endif
+
+
+/*
+ * Types that are (so far) the same on all platforms
+ */
+typedef signed   char          khronos_int8_t;
+typedef unsigned char          khronos_uint8_t;
+typedef signed   short int     khronos_int16_t;
+typedef unsigned short int     khronos_uint16_t;
+typedef signed   long  int     khronos_intptr_t;
+typedef unsigned long  int     khronos_uintptr_t;
+typedef signed   long  int     khronos_ssize_t;
+typedef unsigned long  int     khronos_usize_t;
+
+#if KHRONOS_SUPPORT_FLOAT
+/*
+ * Float type
+ */
+typedef          float         khronos_float_t;
+#endif
+
+#if KHRONOS_SUPPORT_INT64
+/* Time types
+ *
+ * These types can be used to represent a time interval in nanoseconds or
+ * an absolute Unadjusted System Time.  Unadjusted System Time is the number
+ * of nanoseconds since some arbitrary system event (e.g. since the last
+ * time the system booted).  The Unadjusted System Time is an unsigned
+ * 64 bit value that wraps back to 0 every 584 years.  Time intervals
+ * may be either signed or unsigned.
+ */
+typedef khronos_uint64_t       khronos_utime_nanoseconds_t;
+typedef khronos_int64_t        khronos_stime_nanoseconds_t;
+#endif
+
+/*
+ * Dummy value used to pad enum types to 32 bits.
+ */
+#ifndef KHRONOS_MAX_ENUM
+#define KHRONOS_MAX_ENUM 0x7FFFFFFF
+#endif
+
+/*
+ * Enumerated boolean type
+ *
+ * Values other than zero should be considered to be true.  Therefore
+ * comparisons should not be made against KHRONOS_TRUE.
+ */
+typedef enum {
+    KHRONOS_FALSE = 0,
+    KHRONOS_TRUE  = 1,
+    KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
+} khronos_boolean_enum_t;
+
+#endif /* __khrplatform_h_ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/SurfaceDescriptor.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,57 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _SURFACEDESCRIPTOR_H_
+#define _SURFACEDESCRIPTOR_H_
+
+#include "ColorDescriptor.h"
+
+struct SurfaceDescriptor
+{
+    int                 m_width;
+    int                 m_height;
+
+    int                 m_stride;
+
+    CColorDescriptor    m_colorDescriptor;
+    int                 m_redShift;     
+    int                 m_greenShift;
+    int                 m_blueShift;
+    int                 m_luminanceShift;
+
+    int                 m_alphaShift;
+
+    int                 m_maskSize;
+    int                 m_stencilSize;
+    int                 m_depthSize;
+};
+
+#endif // _SURFACEDESCRIPTOR_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/VG/openvg.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,748 @@
+/* $Revision: 9203 $ on $Date:: 2009-10-07 02:21:52 -0700 #$ */
+
+/*------------------------------------------------------------------------
+ *
+ * OpenVG 1.1 Reference Implementation
+ * -------------------------------------
+ *
+ * Copyright (c) 2008 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.
+ *
+ *//**
+ * \file
+ * \brief	OpenVG 1.1 API.
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _OPENVG_H
+#define _OPENVG_H
+
+#include <VG/vgplatform.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define OPENVG_VERSION_1_0		1
+#define OPENVG_VERSION_1_0_1	1
+#define OPENVG_VERSION_1_1		2
+
+#ifndef VG_MAXSHORT
+#define VG_MAXSHORT 0x7FFF
+#endif
+
+#ifndef VG_MAXINT
+#define VG_MAXINT 0x7FFFFFFF
+#endif
+
+#ifndef VG_MAX_ENUM
+#define VG_MAX_ENUM 0x7FFFFFFF
+#endif
+
+typedef VGuint VGHandle;
+
+typedef VGHandle VGPath;
+typedef VGHandle VGImage;
+typedef VGHandle VGMaskLayer;
+typedef VGHandle VGFont;
+typedef VGHandle VGPaint;
+
+#define VG_INVALID_HANDLE ((VGHandle)0)
+
+typedef enum {
+  VG_FALSE               = 0,
+  VG_TRUE                = 1,
+
+  VG_BOOLEAN_FORCE_SIZE  = VG_MAX_ENUM
+} VGboolean;
+
+typedef enum {
+  VG_NO_ERROR                                 = 0,
+  VG_BAD_HANDLE_ERROR                         = 0x1000,
+  VG_ILLEGAL_ARGUMENT_ERROR                   = 0x1001,
+  VG_OUT_OF_MEMORY_ERROR                      = 0x1002,
+  VG_PATH_CAPABILITY_ERROR                    = 0x1003,
+  VG_UNSUPPORTED_IMAGE_FORMAT_ERROR           = 0x1004,
+  VG_UNSUPPORTED_PATH_FORMAT_ERROR            = 0x1005,
+  VG_IMAGE_IN_USE_ERROR                       = 0x1006,
+  VG_NO_CONTEXT_ERROR                         = 0x1007,
+
+  VG_ERROR_CODE_FORCE_SIZE                    = VG_MAX_ENUM
+} VGErrorCode;
+
+typedef enum {
+  /* Mode settings */
+  VG_MATRIX_MODE                              = 0x1100,
+  VG_FILL_RULE                                = 0x1101,
+  VG_IMAGE_QUALITY                            = 0x1102,
+  VG_RENDERING_QUALITY                        = 0x1103,
+  VG_BLEND_MODE                               = 0x1104,
+  VG_IMAGE_MODE                               = 0x1105,
+
+  /* Scissoring rectangles */
+  VG_SCISSOR_RECTS                            = 0x1106,
+
+  /* Color Transformation */
+  VG_COLOR_TRANSFORM                          = 0x1170,
+  VG_COLOR_TRANSFORM_VALUES                   = 0x1171,
+
+  /* Stroke parameters */
+  VG_STROKE_LINE_WIDTH                        = 0x1110,
+  VG_STROKE_CAP_STYLE                         = 0x1111,
+  VG_STROKE_JOIN_STYLE                        = 0x1112,
+  VG_STROKE_MITER_LIMIT                       = 0x1113,
+  VG_STROKE_DASH_PATTERN                      = 0x1114,
+  VG_STROKE_DASH_PHASE                        = 0x1115,
+  VG_STROKE_DASH_PHASE_RESET                  = 0x1116,
+
+  /* Edge fill color for VG_TILE_FILL tiling mode */
+  VG_TILE_FILL_COLOR                          = 0x1120,
+
+  /* Color for vgClear */
+  VG_CLEAR_COLOR                              = 0x1121,
+
+  /* Glyph origin */
+  VG_GLYPH_ORIGIN                             = 0x1122,
+
+  /* Enable/disable alpha masking and scissoring */
+  VG_MASKING                                  = 0x1130,
+  VG_SCISSORING                               = 0x1131,
+
+  /* Pixel layout information */
+  VG_PIXEL_LAYOUT                             = 0x1140,
+  VG_SCREEN_LAYOUT                            = 0x1141,
+
+  /* Source format selection for image filters */
+  VG_FILTER_FORMAT_LINEAR                     = 0x1150,
+  VG_FILTER_FORMAT_PREMULTIPLIED              = 0x1151,
+
+  /* Destination write enable mask for image filters */
+  VG_FILTER_CHANNEL_MASK                      = 0x1152,
+
+  /* Implementation limits (read-only) */
+  VG_MAX_SCISSOR_RECTS                        = 0x1160,
+  VG_MAX_DASH_COUNT                           = 0x1161,
+  VG_MAX_KERNEL_SIZE                          = 0x1162,
+  VG_MAX_SEPARABLE_KERNEL_SIZE                = 0x1163,
+  VG_MAX_COLOR_RAMP_STOPS                     = 0x1164,
+  VG_MAX_IMAGE_WIDTH                          = 0x1165,
+  VG_MAX_IMAGE_HEIGHT                         = 0x1166,
+  VG_MAX_IMAGE_PIXELS                         = 0x1167,
+  VG_MAX_IMAGE_BYTES                          = 0x1168,
+  VG_MAX_FLOAT                                = 0x1169,
+  VG_MAX_GAUSSIAN_STD_DEVIATION               = 0x116A,
+
+  VG_PARAM_TYPE_FORCE_SIZE                    = VG_MAX_ENUM
+} VGParamType;
+
+typedef enum {
+  VG_RENDERING_QUALITY_NONANTIALIASED         = 0x1200,
+  VG_RENDERING_QUALITY_FASTER                 = 0x1201,
+  VG_RENDERING_QUALITY_BETTER                 = 0x1202, /* Default */
+
+  VG_RENDERING_QUALITY_FORCE_SIZE             = VG_MAX_ENUM
+} VGRenderingQuality;
+
+typedef enum {
+  VG_PIXEL_LAYOUT_UNKNOWN                     = 0x1300,
+  VG_PIXEL_LAYOUT_RGB_VERTICAL                = 0x1301,
+  VG_PIXEL_LAYOUT_BGR_VERTICAL                = 0x1302,
+  VG_PIXEL_LAYOUT_RGB_HORIZONTAL              = 0x1303,
+  VG_PIXEL_LAYOUT_BGR_HORIZONTAL              = 0x1304,
+
+  VG_PIXEL_LAYOUT_FORCE_SIZE                  = VG_MAX_ENUM
+} VGPixelLayout;
+
+typedef enum {
+  VG_MATRIX_PATH_USER_TO_SURFACE              = 0x1400,
+  VG_MATRIX_IMAGE_USER_TO_SURFACE             = 0x1401,
+  VG_MATRIX_FILL_PAINT_TO_USER                = 0x1402,
+  VG_MATRIX_STROKE_PAINT_TO_USER              = 0x1403,
+  VG_MATRIX_GLYPH_USER_TO_SURFACE             = 0x1404,
+
+  VG_MATRIX_MODE_FORCE_SIZE                   = VG_MAX_ENUM
+} VGMatrixMode;
+
+typedef enum {
+  VG_CLEAR_MASK                               = 0x1500,
+  VG_FILL_MASK                                = 0x1501,
+  VG_SET_MASK                                 = 0x1502,
+  VG_UNION_MASK                               = 0x1503,
+  VG_INTERSECT_MASK                           = 0x1504,
+  VG_SUBTRACT_MASK                            = 0x1505,
+
+  VG_MASK_OPERATION_FORCE_SIZE                = VG_MAX_ENUM
+} VGMaskOperation;
+
+#define VG_PATH_FORMAT_STANDARD 0
+
+typedef enum {
+  VG_PATH_DATATYPE_S_8                        =  0,
+  VG_PATH_DATATYPE_S_16                       =  1,
+  VG_PATH_DATATYPE_S_32                       =  2,
+  VG_PATH_DATATYPE_F                          =  3,
+
+  VG_PATH_DATATYPE_FORCE_SIZE                 = VG_MAX_ENUM
+} VGPathDatatype;
+
+typedef enum {
+  VG_ABSOLUTE                                 = 0,
+  VG_RELATIVE                                 = 1,
+
+  VG_PATH_ABS_REL_FORCE_SIZE                  = VG_MAX_ENUM
+} VGPathAbsRel;
+
+typedef enum {
+  VG_CLOSE_PATH                               = ( 0 << 1),
+  VG_MOVE_TO                                  = ( 1 << 1),
+  VG_LINE_TO                                  = ( 2 << 1),
+  VG_HLINE_TO                                 = ( 3 << 1),
+  VG_VLINE_TO                                 = ( 4 << 1),
+  VG_QUAD_TO                                  = ( 5 << 1),
+  VG_CUBIC_TO                                 = ( 6 << 1),
+  VG_SQUAD_TO                                 = ( 7 << 1),
+  VG_SCUBIC_TO                                = ( 8 << 1),
+  VG_SCCWARC_TO                               = ( 9 << 1),
+  VG_SCWARC_TO                                = (10 << 1),
+  VG_LCCWARC_TO                               = (11 << 1),
+  VG_LCWARC_TO                                = (12 << 1),
+
+  VG_PATH_SEGMENT_FORCE_SIZE                  = VG_MAX_ENUM
+} VGPathSegment;
+
+typedef enum {
+  VG_MOVE_TO_ABS                              = VG_MOVE_TO    | VG_ABSOLUTE,
+  VG_MOVE_TO_REL                              = VG_MOVE_TO    | VG_RELATIVE,
+  VG_LINE_TO_ABS                              = VG_LINE_TO    | VG_ABSOLUTE,
+  VG_LINE_TO_REL                              = VG_LINE_TO    | VG_RELATIVE,
+  VG_HLINE_TO_ABS                             = VG_HLINE_TO   | VG_ABSOLUTE,
+  VG_HLINE_TO_REL                             = VG_HLINE_TO   | VG_RELATIVE,
+  VG_VLINE_TO_ABS                             = VG_VLINE_TO   | VG_ABSOLUTE,
+  VG_VLINE_TO_REL                             = VG_VLINE_TO   | VG_RELATIVE,
+  VG_QUAD_TO_ABS                              = VG_QUAD_TO    | VG_ABSOLUTE,
+  VG_QUAD_TO_REL                              = VG_QUAD_TO    | VG_RELATIVE,
+  VG_CUBIC_TO_ABS                             = VG_CUBIC_TO   | VG_ABSOLUTE,
+  VG_CUBIC_TO_REL                             = VG_CUBIC_TO   | VG_RELATIVE,
+  VG_SQUAD_TO_ABS                             = VG_SQUAD_TO   | VG_ABSOLUTE,
+  VG_SQUAD_TO_REL                             = VG_SQUAD_TO   | VG_RELATIVE,
+  VG_SCUBIC_TO_ABS                            = VG_SCUBIC_TO  | VG_ABSOLUTE,
+  VG_SCUBIC_TO_REL                            = VG_SCUBIC_TO  | VG_RELATIVE,
+  VG_SCCWARC_TO_ABS                           = VG_SCCWARC_TO | VG_ABSOLUTE,
+  VG_SCCWARC_TO_REL                           = VG_SCCWARC_TO | VG_RELATIVE,
+  VG_SCWARC_TO_ABS                            = VG_SCWARC_TO  | VG_ABSOLUTE,
+  VG_SCWARC_TO_REL                            = VG_SCWARC_TO  | VG_RELATIVE,
+  VG_LCCWARC_TO_ABS                           = VG_LCCWARC_TO | VG_ABSOLUTE,
+  VG_LCCWARC_TO_REL                           = VG_LCCWARC_TO | VG_RELATIVE,
+  VG_LCWARC_TO_ABS                            = VG_LCWARC_TO  | VG_ABSOLUTE,
+  VG_LCWARC_TO_REL                            = VG_LCWARC_TO  | VG_RELATIVE,
+
+  VG_PATH_COMMAND_FORCE_SIZE                  = VG_MAX_ENUM
+} VGPathCommand;
+
+typedef enum {
+  VG_PATH_CAPABILITY_APPEND_FROM              = (1 <<  0),
+  VG_PATH_CAPABILITY_APPEND_TO                = (1 <<  1),
+  VG_PATH_CAPABILITY_MODIFY                   = (1 <<  2),
+  VG_PATH_CAPABILITY_TRANSFORM_FROM           = (1 <<  3),
+  VG_PATH_CAPABILITY_TRANSFORM_TO             = (1 <<  4),
+  VG_PATH_CAPABILITY_INTERPOLATE_FROM         = (1 <<  5),
+  VG_PATH_CAPABILITY_INTERPOLATE_TO           = (1 <<  6),
+  VG_PATH_CAPABILITY_PATH_LENGTH              = (1 <<  7),
+  VG_PATH_CAPABILITY_POINT_ALONG_PATH         = (1 <<  8),
+  VG_PATH_CAPABILITY_TANGENT_ALONG_PATH       = (1 <<  9),
+  VG_PATH_CAPABILITY_PATH_BOUNDS              = (1 << 10),
+  VG_PATH_CAPABILITY_PATH_TRANSFORMED_BOUNDS  = (1 << 11),
+  VG_PATH_CAPABILITY_ALL                      = (1 << 12) - 1,
+
+  VG_PATH_CAPABILITIES_FORCE_SIZE             = VG_MAX_ENUM
+} VGPathCapabilities;
+
+typedef enum {
+  VG_PATH_FORMAT                              = 0x1600,
+  VG_PATH_DATATYPE                            = 0x1601,
+  VG_PATH_SCALE                               = 0x1602,
+  VG_PATH_BIAS                                = 0x1603,
+  VG_PATH_NUM_SEGMENTS                        = 0x1604,
+  VG_PATH_NUM_COORDS                          = 0x1605,
+
+  VG_PATH_PARAM_TYPE_FORCE_SIZE               = VG_MAX_ENUM
+} VGPathParamType;
+
+typedef enum {
+  VG_CAP_BUTT                                 = 0x1700,
+  VG_CAP_ROUND                                = 0x1701,
+  VG_CAP_SQUARE                               = 0x1702,
+
+  VG_CAP_STYLE_FORCE_SIZE                     = VG_MAX_ENUM
+} VGCapStyle;
+
+typedef enum {
+  VG_JOIN_MITER                               = 0x1800,
+  VG_JOIN_ROUND                               = 0x1801,
+  VG_JOIN_BEVEL                               = 0x1802,
+
+  VG_JOIN_STYLE_FORCE_SIZE                    = VG_MAX_ENUM
+} VGJoinStyle;
+
+typedef enum {
+  VG_EVEN_ODD                                 = 0x1900,
+  VG_NON_ZERO                                 = 0x1901,
+
+  VG_FILL_RULE_FORCE_SIZE                     = VG_MAX_ENUM
+} VGFillRule;
+
+typedef enum {
+  VG_STROKE_PATH                              = (1 << 0),
+  VG_FILL_PATH                                = (1 << 1),
+
+  VG_PAINT_MODE_FORCE_SIZE                    = VG_MAX_ENUM
+} VGPaintMode;
+
+typedef enum {
+  /* Color paint parameters */
+  VG_PAINT_TYPE                               = 0x1A00,
+  VG_PAINT_COLOR                              = 0x1A01,
+  VG_PAINT_COLOR_RAMP_SPREAD_MODE             = 0x1A02,
+  VG_PAINT_COLOR_RAMP_PREMULTIPLIED           = 0x1A07,
+  VG_PAINT_COLOR_RAMP_STOPS                   = 0x1A03,
+
+  /* Linear gradient paint parameters */
+  VG_PAINT_LINEAR_GRADIENT                    = 0x1A04,
+
+  /* Radial gradient paint parameters */
+  VG_PAINT_RADIAL_GRADIENT                    = 0x1A05,
+
+  /* Pattern paint parameters */
+  VG_PAINT_PATTERN_TILING_MODE                = 0x1A06,
+
+  VG_PAINT_PARAM_TYPE_FORCE_SIZE              = VG_MAX_ENUM
+} VGPaintParamType;
+
+typedef enum {
+  VG_PAINT_TYPE_COLOR                         = 0x1B00,
+  VG_PAINT_TYPE_LINEAR_GRADIENT               = 0x1B01,
+  VG_PAINT_TYPE_RADIAL_GRADIENT               = 0x1B02,
+  VG_PAINT_TYPE_PATTERN                       = 0x1B03,
+
+  VG_PAINT_TYPE_FORCE_SIZE                    = VG_MAX_ENUM
+} VGPaintType;
+
+typedef enum {
+  VG_COLOR_RAMP_SPREAD_PAD                    = 0x1C00,
+  VG_COLOR_RAMP_SPREAD_REPEAT                 = 0x1C01,
+  VG_COLOR_RAMP_SPREAD_REFLECT                = 0x1C02,
+
+  VG_COLOR_RAMP_SPREAD_MODE_FORCE_SIZE        = VG_MAX_ENUM
+} VGColorRampSpreadMode;
+
+typedef enum {
+  VG_TILE_FILL                                = 0x1D00,
+  VG_TILE_PAD                                 = 0x1D01,
+  VG_TILE_REPEAT                              = 0x1D02,
+  VG_TILE_REFLECT                             = 0x1D03,
+
+  VG_TILING_MODE_FORCE_SIZE                   = VG_MAX_ENUM
+} VGTilingMode;
+
+typedef enum {
+  /* RGB{A,X} channel ordering */
+  VG_sRGBX_8888                               =  0,
+  VG_sRGBA_8888                               =  1,
+  VG_sRGBA_8888_PRE                           =  2,
+  VG_sRGB_565                                 =  3,
+  VG_sRGBA_5551                               =  4,
+  VG_sRGBA_4444                               =  5,
+  VG_sL_8                                     =  6,
+  VG_lRGBX_8888                               =  7,
+  VG_lRGBA_8888                               =  8,
+  VG_lRGBA_8888_PRE                           =  9,
+  VG_lL_8                                     = 10,
+  VG_A_8                                      = 11,
+  VG_BW_1                                     = 12,
+  VG_A_1                                      = 13,
+  VG_A_4                                      = 14,
+
+  /* {A,X}RGB channel ordering */
+  VG_sXRGB_8888                               =  0 | (1 << 6),
+  VG_sARGB_8888                               =  1 | (1 << 6),
+  VG_sARGB_8888_PRE                           =  2 | (1 << 6),
+  VG_sARGB_1555                               =  4 | (1 << 6),
+  VG_sARGB_4444                               =  5 | (1 << 6),
+  VG_lXRGB_8888                               =  7 | (1 << 6),
+  VG_lARGB_8888                               =  8 | (1 << 6),
+  VG_lARGB_8888_PRE                           =  9 | (1 << 6),
+
+  /* BGR{A,X} channel ordering */
+  VG_sBGRX_8888                               =  0 | (1 << 7),
+  VG_sBGRA_8888                               =  1 | (1 << 7),
+  VG_sBGRA_8888_PRE                           =  2 | (1 << 7),
+  VG_sBGR_565                                 =  3 | (1 << 7),
+  VG_sBGRA_5551                               =  4 | (1 << 7),
+  VG_sBGRA_4444                               =  5 | (1 << 7),
+  VG_lBGRX_8888                               =  7 | (1 << 7),
+  VG_lBGRA_8888                               =  8 | (1 << 7),
+  VG_lBGRA_8888_PRE                           =  9 | (1 << 7),
+
+  /* {A,X}BGR channel ordering */
+  VG_sXBGR_8888                               =  0 | (1 << 6) | (1 << 7),
+  VG_sABGR_8888                               =  1 | (1 << 6) | (1 << 7),
+  VG_sABGR_8888_PRE                           =  2 | (1 << 6) | (1 << 7),
+  VG_sABGR_1555                               =  4 | (1 << 6) | (1 << 7),
+  VG_sABGR_4444                               =  5 | (1 << 6) | (1 << 7),
+  VG_lXBGR_8888                               =  7 | (1 << 6) | (1 << 7),
+  VG_lABGR_8888                               =  8 | (1 << 6) | (1 << 7),
+  VG_lABGR_8888_PRE                           =  9 | (1 << 6) | (1 << 7),
+
+  VG_IMAGE_FORMAT_FORCE_SIZE                  = VG_MAX_ENUM
+} VGImageFormat;
+
+typedef enum {
+  VG_IMAGE_QUALITY_NONANTIALIASED             = (1 << 0),
+  VG_IMAGE_QUALITY_FASTER                     = (1 << 1),
+  VG_IMAGE_QUALITY_BETTER                     = (1 << 2),
+
+  VG_IMAGE_QUALITY_FORCE_SIZE                 = VG_MAX_ENUM
+} VGImageQuality;
+
+typedef enum {
+  VG_IMAGE_FORMAT                             = 0x1E00,
+  VG_IMAGE_WIDTH                              = 0x1E01,
+  VG_IMAGE_HEIGHT                             = 0x1E02,
+
+  VG_IMAGE_PARAM_TYPE_FORCE_SIZE              = VG_MAX_ENUM
+} VGImageParamType;
+
+typedef enum {
+  VG_DRAW_IMAGE_NORMAL                        = 0x1F00,
+  VG_DRAW_IMAGE_MULTIPLY                      = 0x1F01,
+  VG_DRAW_IMAGE_STENCIL                       = 0x1F02,
+
+  VG_IMAGE_MODE_FORCE_SIZE                    = VG_MAX_ENUM
+} VGImageMode;
+
+typedef enum {
+  VG_RED                                      = (1 << 3),
+  VG_GREEN                                    = (1 << 2),
+  VG_BLUE                                     = (1 << 1),
+  VG_ALPHA                                    = (1 << 0),
+
+  VG_IMAGE_CHANNEL_FORCE_SIZE                 = VG_MAX_ENUM
+} VGImageChannel;
+
+typedef enum {
+  VG_BLEND_SRC                                = 0x2000,
+  VG_BLEND_SRC_OVER                           = 0x2001,
+  VG_BLEND_DST_OVER                           = 0x2002,
+  VG_BLEND_SRC_IN                             = 0x2003,
+  VG_BLEND_DST_IN                             = 0x2004,
+  VG_BLEND_MULTIPLY                           = 0x2005,
+  VG_BLEND_SCREEN                             = 0x2006,
+  VG_BLEND_DARKEN                             = 0x2007,
+  VG_BLEND_LIGHTEN                            = 0x2008,
+  VG_BLEND_ADDITIVE                           = 0x2009,
+
+  VG_BLEND_MODE_FORCE_SIZE                    = VG_MAX_ENUM
+} VGBlendMode;
+
+typedef enum {
+  VG_FONT_NUM_GLYPHS                          = 0x2F00,
+
+  VG_FONT_PARAM_TYPE_FORCE_SIZE               = VG_MAX_ENUM
+} VGFontParamType;
+
+typedef enum {
+  VG_IMAGE_FORMAT_QUERY                       = 0x2100,
+  VG_PATH_DATATYPE_QUERY                      = 0x2101,
+
+  VG_HARDWARE_QUERY_TYPE_FORCE_SIZE           = VG_MAX_ENUM
+} VGHardwareQueryType;
+
+typedef enum {
+  VG_HARDWARE_ACCELERATED                     = 0x2200,
+  VG_HARDWARE_UNACCELERATED                   = 0x2201,
+
+  VG_HARDWARE_QUERY_RESULT_FORCE_SIZE         = VG_MAX_ENUM
+} VGHardwareQueryResult;
+
+typedef enum {
+  VG_VENDOR                                   = 0x2300,
+  VG_RENDERER                                 = 0x2301,
+  VG_VERSION                                  = 0x2302,
+  VG_EXTENSIONS                               = 0x2303,
+
+  VG_STRING_ID_FORCE_SIZE                     = VG_MAX_ENUM
+} VGStringID;
+
+/* Function Prototypes */
+
+#ifndef VG_API_CALL
+#	error VG_API_CALL must be defined
+#endif
+
+#ifndef VG_API_ENTRY
+#   error VG_API_ENTRY must be defined 
+#endif
+
+#ifndef VG_API_EXIT
+#   error VG_API_EXIT must be defined 
+#endif
+
+VG_API_CALL VGErrorCode VG_API_ENTRY vgGetError(void) VG_API_EXIT;
+
+VG_API_CALL void VG_API_ENTRY vgFlush(void) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgFinish(void) VG_API_EXIT;
+
+/* Getters and Setters */
+VG_API_CALL void VG_API_ENTRY vgSetf (VGParamType type, VGfloat value) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSeti (VGParamType type, VGint value) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetfv(VGParamType type, VGint count,
+                         const VGfloat * values) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetiv(VGParamType type, VGint count,
+                         const VGint * values) VG_API_EXIT;
+
+VG_API_CALL VGfloat VG_API_ENTRY vgGetf(VGParamType type) VG_API_EXIT;
+VG_API_CALL VGint VG_API_ENTRY vgGeti(VGParamType type) VG_API_EXIT;
+VG_API_CALL VGint VG_API_ENTRY vgGetVectorSize(VGParamType type) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgGetfv(VGParamType type, VGint count, VGfloat * values) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgGetiv(VGParamType type, VGint count, VGint * values) VG_API_EXIT;
+
+VG_API_CALL void VG_API_ENTRY vgSetParameterf(VGHandle object,
+                                 VGint paramType,
+                                 VGfloat value) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetParameteri(VGHandle object,
+                                 VGint paramType,
+                                 VGint value) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetParameterfv(VGHandle object,
+                                  VGint paramType,
+                                  VGint count, const VGfloat * values) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetParameteriv(VGHandle object,
+                                  VGint paramType,
+                                  VGint count, const VGint * values) VG_API_EXIT;
+
+VG_API_CALL VGfloat VG_API_ENTRY vgGetParameterf(VGHandle object,
+                                    VGint paramType) VG_API_EXIT;
+VG_API_CALL VGint VG_API_ENTRY vgGetParameteri(VGHandle object,
+                                  VGint paramType);
+VG_API_CALL VGint VG_API_ENTRY vgGetParameterVectorSize(VGHandle object,
+                                           VGint paramType) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgGetParameterfv(VGHandle object,
+                                  VGint paramType,
+                                  VGint count, VGfloat * values) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgGetParameteriv(VGHandle object,
+                                  VGint paramType,
+                                  VGint count, VGint * values) VG_API_EXIT;
+
+/* Matrix Manipulation */
+VG_API_CALL void VG_API_ENTRY vgLoadIdentity(void) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgLoadMatrix(const VGfloat * m) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgGetMatrix(VGfloat * m) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgMultMatrix(const VGfloat * m) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgTranslate(VGfloat tx, VGfloat ty) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgScale(VGfloat sx, VGfloat sy) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgShear(VGfloat shx, VGfloat shy) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgRotate(VGfloat angle) VG_API_EXIT;
+
+/* Masking and Clearing */
+VG_API_CALL void VG_API_ENTRY vgMask(VGHandle mask, VGMaskOperation operation,
+                                     VGint x, VGint y,
+                                     VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgRenderToMask(VGPath path,
+                                            VGbitfield paintModes,
+                                            VGMaskOperation operation) VG_API_EXIT;
+VG_API_CALL VGMaskLayer VG_API_ENTRY vgCreateMaskLayer(VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDestroyMaskLayer(VGMaskLayer maskLayer) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgFillMaskLayer(VGMaskLayer maskLayer,
+                                             VGint x, VGint y,
+                                             VGint width, VGint height,
+                                             VGfloat value) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgCopyMask(VGMaskLayer maskLayer,
+                                        VGint dx, VGint dy,
+                                        VGint sx, VGint sy,
+                                        VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgClear(VGint x, VGint y, VGint width, VGint height) VG_API_EXIT;
+
+/* Paths */
+VG_API_CALL VGPath VG_API_ENTRY vgCreatePath(VGint pathFormat,
+                                VGPathDatatype datatype,
+                                VGfloat scale, VGfloat bias,
+                                VGint segmentCapacityHint,
+                                VGint coordCapacityHint,
+                                VGbitfield capabilities) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgClearPath(VGPath path, VGbitfield capabilities) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDestroyPath(VGPath path) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgRemovePathCapabilities(VGPath path,
+                                          VGbitfield capabilities) VG_API_EXIT;
+VG_API_CALL VGbitfield VG_API_ENTRY vgGetPathCapabilities(VGPath path) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgAppendPath(VGPath dstPath, VGPath srcPath) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgAppendPathData(VGPath dstPath,
+                                  VGint numSegments,
+                                  const VGubyte * pathSegments,
+                                  const void * pathData) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgModifyPathCoords(VGPath dstPath, VGint startIndex,
+                                    VGint numSegments,
+                                    const void * pathData) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgTransformPath(VGPath dstPath, VGPath srcPath) VG_API_EXIT;
+VG_API_CALL VGboolean VG_API_ENTRY vgInterpolatePath(VGPath dstPath,
+                                        VGPath startPath,
+                                        VGPath endPath,
+                                        VGfloat amount) VG_API_EXIT;
+VG_API_CALL VGfloat VG_API_ENTRY vgPathLength(VGPath path,
+                                 VGint startSegment, VGint numSegments) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgPointAlongPath(VGPath path,
+                                  VGint startSegment, VGint numSegments,
+                                  VGfloat distance,
+                                  VGfloat * x, VGfloat * y,
+                                  VGfloat * tangentX, VGfloat * tangentY) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgPathBounds(VGPath path,
+                              VGfloat * minX, VGfloat * minY,
+                              VGfloat * width, VGfloat * height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgPathTransformedBounds(VGPath path,
+                                         VGfloat * minX, VGfloat * minY,
+                                         VGfloat * width, VGfloat * height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDrawPath(VGPath path, VGbitfield paintModes) VG_API_EXIT;
+
+/* Paint */
+VG_API_CALL VGPaint VG_API_ENTRY vgCreatePaint(void) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDestroyPaint(VGPaint paint) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetPaint(VGPaint paint, VGbitfield paintModes) VG_API_EXIT;
+VG_API_CALL VGPaint VG_API_ENTRY vgGetPaint(VGPaintMode paintMode) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetColor(VGPaint paint, VGuint rgba) VG_API_EXIT;
+VG_API_CALL VGuint VG_API_ENTRY vgGetColor(VGPaint paint) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgPaintPattern(VGPaint paint, VGImage pattern) VG_API_EXIT;
+
+/* Images */
+VG_API_CALL VGImage VG_API_ENTRY vgCreateImage(VGImageFormat format,
+                                  VGint width, VGint height,
+                                  VGbitfield allowedQuality) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDestroyImage(VGImage image) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgClearImage(VGImage image,
+                              VGint x, VGint y, VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgImageSubData(VGImage image,
+                                const void * data, VGint dataStride,
+                                VGImageFormat dataFormat,
+                                VGint x, VGint y, VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgGetImageSubData(VGImage image,
+                                   void * data, VGint dataStride,
+                                   VGImageFormat dataFormat,
+                                   VGint x, VGint y,
+                                   VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL VGImage VG_API_ENTRY vgChildImage(VGImage parent,
+                                 VGint x, VGint y, VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL VGImage VG_API_ENTRY vgGetParent(VGImage image) VG_API_EXIT; 
+VG_API_CALL void VG_API_ENTRY vgCopyImage(VGImage dst, VGint dx, VGint dy,
+                             VGImage src, VGint sx, VGint sy,
+                             VGint width, VGint height,
+                             VGboolean dither) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDrawImage(VGImage image) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetPixels(VGint dx, VGint dy,
+                             VGImage src, VGint sx, VGint sy,
+                             VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgWritePixels(const void * data, VGint dataStride,
+                               VGImageFormat dataFormat,
+                               VGint dx, VGint dy,
+                               VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgGetPixels(VGImage dst, VGint dx, VGint dy,
+                             VGint sx, VGint sy,
+                             VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgReadPixels(void * data, VGint dataStride,
+                              VGImageFormat dataFormat,
+                              VGint sx, VGint sy,
+                              VGint width, VGint height) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgCopyPixels(VGint dx, VGint dy,
+                              VGint sx, VGint sy,
+                              VGint width, VGint height) VG_API_EXIT;
+
+/* Text */
+VG_API_CALL VGFont VG_API_ENTRY vgCreateFont(VGint glyphCapacityHint) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDestroyFont(VGFont font) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetGlyphToPath(VGFont font,
+                                              VGuint glyphIndex,
+                                              VGPath path,
+                                              VGboolean isHinted,
+                                              const VGfloat glyphOrigin [2],
+                                              const VGfloat escapement[2]) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetGlyphToImage(VGFont font,
+                                               VGuint glyphIndex,
+                                               VGImage image,
+                                               const VGfloat glyphOrigin [2],
+                                               const VGfloat escapement[2]) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgClearGlyph(VGFont font,VGuint glyphIndex) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDrawGlyph(VGFont font, 
+                                         VGuint glyphIndex,
+                                         VGbitfield paintModes,
+                                         VGboolean allowAutoHinting) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgDrawGlyphs(VGFont font,
+                                          VGint glyphCount,
+                                          const VGuint *glyphIndices,
+                                          const VGfloat *adjustments_x,
+                                          const VGfloat *adjustments_y,
+                                          VGbitfield paintModes,
+                                          VGboolean allowAutoHinting) VG_API_EXIT;
+
+/* Image Filters */
+VG_API_CALL void VG_API_ENTRY vgColorMatrix(VGImage dst, VGImage src,
+                               const VGfloat * matrix) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgConvolve(VGImage dst, VGImage src,
+                            VGint kernelWidth, VGint kernelHeight,
+                            VGint shiftX, VGint shiftY,
+                            const VGshort * kernel,
+                            VGfloat scale,
+                            VGfloat bias,
+                            VGTilingMode tilingMode) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSeparableConvolve(VGImage dst, VGImage src,
+                                     VGint kernelWidth,
+                                     VGint kernelHeight,
+                                     VGint shiftX, VGint shiftY,
+                                     const VGshort * kernelX,
+                                     const VGshort * kernelY,
+                                     VGfloat scale,
+                                     VGfloat bias,
+                                     VGTilingMode tilingMode) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgGaussianBlur(VGImage dst, VGImage src,
+                                VGfloat stdDeviationX,
+                                VGfloat stdDeviationY,
+                                VGTilingMode tilingMode) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgLookup(VGImage dst, VGImage src,
+                          const VGubyte * redLUT,
+                          const VGubyte * greenLUT,
+                          const VGubyte * blueLUT,
+                          const VGubyte * alphaLUT,
+                          VGboolean outputLinear,
+                          VGboolean outputPremultiplied) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgLookupSingle(VGImage dst, VGImage src,
+                                const VGuint * lookupTable,
+                                VGImageChannel sourceChannel,
+                                VGboolean outputLinear,
+                                VGboolean outputPremultiplied) VG_API_EXIT;
+
+/* Hardware Queries */
+VG_API_CALL VGHardwareQueryResult VG_API_ENTRY vgHardwareQuery(VGHardwareQueryType key,
+                                                  VGint setting) VG_API_EXIT;
+
+/* Renderer and Extension Information */
+VG_API_CALL const VGubyte * VG_API_ENTRY vgGetString(VGStringID name) VG_API_EXIT;
+
+VG_API_CALL VGErrorCode VG_API_ENTRY vgPlatsimGetError(void) VG_API_EXIT;
+
+#ifdef __cplusplus 
+} /* extern "C" */
+#endif
+
+#endif /* _OPENVG_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/VG/vgext.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,235 @@
+/* $Revision: 6810 $ on $Date:: 2008-10-29 07:31:37 -0700 #$ */
+
+/*------------------------------------------------------------------------
+ * 
+ * VG extensions Reference Implementation
+ * -------------------------------------
+ *
+ * Copyright (c) 2008 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.
+ *
+ *//**
+ * \file
+ * \brief	VG extensions
+ *//*-------------------------------------------------------------------*/
+
+
+
+#ifndef _VGEXT_H
+#define _VGEXT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <VG/openvg.h>
+#include <VG/vgu.h>
+
+#ifndef VG_API_ENTRYP
+#   define VG_API_ENTRYP VG_API_ENTRY*
+#endif
+
+#ifndef VGU_API_ENTRYP
+#   define VGU_API_ENTRYP VGU_API_ENTRY*
+#endif
+
+/*-------------------------------------------------------------------------------
+ * KHR extensions
+ *------------------------------------------------------------------------------*/
+
+typedef enum  {
+
+#ifndef VG_KHR_iterative_average_blur
+  VG_MAX_AVERAGE_BLUR_DIMENSION_KHR        = 0x116B,
+  VG_AVERAGE_BLUR_DIMENSION_RESOLUTION_KHR = 0x116C,
+  VG_MAX_AVERAGE_BLUR_ITERATIONS_KHR       = 0x116D,
+#endif
+
+  VG_PARAM_TYPE_KHR_FORCE_SIZE             = VG_MAX_ENUM
+} VGParamTypeKHR;
+
+#ifndef VG_KHR_EGL_image
+#define VG_KHR_EGL_image 1
+/* VGEGLImageKHR is an opaque handle to an EGLImage */
+typedef void* VGeglImageKHR; 
+
+#ifdef VG_VGEXT_PROTOTYPES
+VG_API_CALL VGImage VG_API_ENTRY vgCreateEGLImageTargetKHR(VGeglImageKHR image);
+#endif
+typedef VGImage (VG_API_ENTRYP PFNVGCREATEEGLIMAGETARGETKHRPROC) (VGeglImageKHR image);
+
+#endif
+
+
+#ifndef VG_KHR_iterative_average_blur
+#define VG_KHR_iterative_average_blur 1
+
+#ifdef VG_VGEXT_PROTOTYPES
+VG_API_CALL void vgIterativeAverageBlurKHR(VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGTilingMode tilingMode);
+#endif 
+typedef void (VG_API_ENTRYP PFNVGITERATIVEAVERAGEBLURKHRPROC) (VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGTilingMode tilingMode);
+
+#endif
+
+
+#ifndef VG_KHR_advanced_blending
+#define VG_KHR_advanced_blending 1
+
+typedef enum {
+  VG_BLEND_OVERLAY_KHR        = 0x2010,
+  VG_BLEND_HARDLIGHT_KHR      = 0x2011,
+  VG_BLEND_SOFTLIGHT_SVG_KHR  = 0x2012,
+  VG_BLEND_SOFTLIGHT_KHR      = 0x2013,
+  VG_BLEND_COLORDODGE_KHR     = 0x2014,
+  VG_BLEND_COLORBURN_KHR      = 0x2015,
+  VG_BLEND_DIFFERENCE_KHR     = 0x2016,
+  VG_BLEND_SUBTRACT_KHR       = 0x2017,
+  VG_BLEND_INVERT_KHR         = 0x2018,
+  VG_BLEND_EXCLUSION_KHR      = 0x2019,
+  VG_BLEND_LINEARDODGE_KHR    = 0x201a,
+  VG_BLEND_LINEARBURN_KHR     = 0x201b,
+  VG_BLEND_VIVIDLIGHT_KHR     = 0x201c,
+  VG_BLEND_LINEARLIGHT_KHR    = 0x201d,
+  VG_BLEND_PINLIGHT_KHR       = 0x201e,
+  VG_BLEND_HARDMIX_KHR        = 0x201f,
+  VG_BLEND_CLEAR_KHR          = 0x2020,
+  VG_BLEND_DST_KHR            = 0x2021,
+  VG_BLEND_SRC_OUT_KHR        = 0x2022,
+  VG_BLEND_DST_OUT_KHR        = 0x2023,
+  VG_BLEND_SRC_ATOP_KHR       = 0x2024,
+  VG_BLEND_DST_ATOP_KHR       = 0x2025,
+  VG_BLEND_XOR_KHR            = 0x2026,
+
+  VG_BLEND_MODE_KHR_FORCE_SIZE= VG_MAX_ENUM
+} VGBlendModeKHR;
+#endif
+
+#ifndef VG_KHR_parametric_filter
+#define VG_KHR_parametric_filter 1 
+
+typedef enum {
+  VG_PF_OBJECT_VISIBLE_FLAG_KHR = (1 << 0),
+  VG_PF_KNOCKOUT_FLAG_KHR       = (1 << 1),
+  VG_PF_OUTER_FLAG_KHR          = (1 << 2),
+  VG_PF_INNER_FLAG_KHR          = (1 << 3),
+
+  VG_PF_TYPE_KHR_FORCE_SIZE     = VG_MAX_ENUM
+} VGPfTypeKHR;
+
+typedef enum {
+  VGU_IMAGE_IN_USE_ERROR           = 0xF010,
+
+  VGU_ERROR_CODE_KHR_FORCE_SIZE    = VG_MAX_ENUM
+} VGUErrorCodeKHR;
+
+#ifdef VG_VGEXT_PROTOTYPES
+VG_API_CALL void VG_API_ENTRY vgParametricFilterKHR(VGImage dst,VGImage src,VGImage blur,VGfloat strength,VGfloat offsetX,VGfloat offsetY,VGbitfield filterFlags,VGPaint highlightPaint,VGPaint shadowPaint);
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguDropShadowKHR(VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGfloat distance,VGfloat angle,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint shadowColorRGBA);
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguGlowKHR(VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint glowColorRGBA) ;
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguBevelKHR(VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGfloat distance,VGfloat angle,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint highlightColorRGBA,VGuint shadowColorRGBA);
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguGradientGlowKHR(VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGfloat distance,VGfloat angle,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint stopsCount,const VGfloat* glowColorRampStops);
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguGradientBevelKHR(VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGfloat distance,VGfloat angle,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint stopsCount,const VGfloat* bevelColorRampStops);
+#endif
+typedef void (VG_API_ENTRYP PFNVGPARAMETRICFILTERKHRPROC) (VGImage dst,VGImage src,VGImage blur,VGfloat strength,VGfloat offsetX,VGfloat offsetY,VGbitfield filterFlags,VGPaint highlightPaint,VGPaint shadowPaint);
+typedef VGUErrorCode (VGU_API_ENTRYP PFNVGUDROPSHADOWKHRPROC) (VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGfloat distance,VGfloat angle,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint shadowColorRGBA);
+typedef VGUErrorCode (VGU_API_ENTRYP PFNVGUGLOWKHRPROC) (VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint glowColorRGBA);
+typedef VGUErrorCode (VGU_API_ENTRYP PFNVGUBEVELKHRPROC) (VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGfloat distance,VGfloat angle,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint highlightColorRGBA,VGuint shadowColorRGBA);
+typedef VGUErrorCode (VGU_API_ENTRYP PFNVGUGRADIENTGLOWKHRPROC) (VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGfloat distance,VGfloat angle,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint stopsCount,const VGfloat* glowColorRampStops);
+typedef VGUErrorCode (VGU_API_ENTRYP PFNVGUGRADIENTBEVELKHRPROC) (VGImage dst,VGImage src,VGfloat dimX,VGfloat dimY,VGuint iterative,VGfloat strength,VGfloat distance,VGfloat angle,VGbitfield filterFlags,VGbitfield allowedQuality,VGuint stopsCount,const VGfloat* bevelColorRampStops);
+
+#endif
+
+
+/*-------------------------------------------------------------------------------
+ * NDS extensions
+ *------------------------------------------------------------------------------*/
+
+#ifndef VG_NDS_paint_generation
+#define VG_NDS_paint_generation 1
+
+typedef enum { 
+  VG_PAINT_COLOR_RAMP_LINEAR_NDS            = 0x1A10,
+  VG_COLOR_MATRIX_NDS                       = 0x1A11,
+  VG_PAINT_COLOR_TRANSFORM_LINEAR_NDS       = 0x1A12,
+
+  VG_PAINT_PARAM_TYPE_NDS_FORCE_SIZE        = VG_MAX_ENUM
+} VGPaintParamTypeNds;
+
+typedef enum {
+  VG_DRAW_IMAGE_COLOR_MATRIX_NDS            = 0x1F10,
+
+  VG_IMAGE_MODE_NDS_FORCE_SIZE              = VG_MAX_ENUM
+} VGImageModeNds;
+#endif 
+
+
+#ifndef VG_NDS_projective_geometry
+#define VG_NDS_projective_geometry 1
+
+typedef enum {
+  VG_CLIP_MODE_NDS                          = 0x1180,
+  VG_CLIP_LINES_NDS                         = 0x1181,
+  VG_MAX_CLIP_LINES_NDS                     = 0x1182,
+
+  VG_PARAM_TYPE_NDS_FORCE_SIZE        = VG_MAX_ENUM
+} VGParamTypeNds;
+
+typedef enum {
+  VG_CLIPMODE_NONE_NDS                      = 0x3000,
+  VG_CLIPMODE_CLIP_CLOSED_NDS               = 0x3001,
+  VG_CLIPMODE_CLIP_OPEN_NDS                 = 0x3002,
+  VG_CLIPMODE_CULL_NDS                      = 0x3003,
+
+  VG_CLIPMODE_NDS_FORCE_SIZE = VG_MAX_ENUM
+} VGClipModeNds;
+
+typedef enum {
+  VG_RQUAD_TO_NDS              = ( 13 << 1 ),
+  VG_RCUBIC_TO_NDS             = ( 14 << 1 ),
+  
+  VG_PATH_SEGMENT_NDS_FORCE_SIZE = VG_MAX_ENUM
+} VGPathSegmentNds;
+
+typedef enum {
+  VG_RQUAD_TO_ABS_NDS            = (VG_RQUAD_TO_NDS  | VG_ABSOLUTE),
+  VG_RQUAD_TO_REL_NDS            = (VG_RQUAD_TO_NDS  | VG_RELATIVE),
+  VG_RCUBIC_TO_ABS_NDS           = (VG_RCUBIC_TO_NDS | VG_ABSOLUTE),
+  VG_RCUBIC_TO_REL_NDS           = (VG_RCUBIC_TO_NDS | VG_RELATIVE),
+
+  VG_PATH_COMMAND_NDS_FORCE_SIZE = VG_MAX_ENUM
+} VGPathCommandNds;
+
+#ifdef VG_VGEXT_PROTOTYPES
+VG_API_CALL void VG_API_ENTRY vgProjectiveMatrixNDS(VGboolean enable) ;
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguTransformClipLineNDS(const VGfloat Ain,const VGfloat Bin,const VGfloat Cin,const VGfloat* matrix,const VGboolean inverse,VGfloat* Aout,VGfloat* Bout,VGfloat* Cout);
+#endif 
+typedef void (VG_API_ENTRYP PFNVGPROJECTIVEMATRIXNDSPROC) (VGboolean enable) ;
+typedef VGUErrorCode (VGU_API_ENTRYP PFNVGUTRANSFORMCLIPLINENDSPROC) (const VGfloat Ain,const VGfloat Bin,const VGfloat Cin,const VGfloat* matrix,const VGboolean inverse,VGfloat* Aout,VGfloat* Bout,VGfloat* Cout);
+
+#endif
+
+VGint vgePathCoordsSizeInBytes( VGPath path,  VGint startIndex, VGint numSegments );
+
+#ifdef __cplusplus 
+} /* extern "C" */
+#endif
+
+#endif /* _VGEXT_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/VG/vgplatform.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,106 @@
+/* $Revision: 6810 $ on $Date:: 2008-10-29 07:31:37 -0700 #$ */
+
+/*------------------------------------------------------------------------
+ *
+ * VG platform specific header Reference Implementation
+ * ----------------------------------------------------
+ *
+ * Copyright (c) 2008 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.
+ *
+ *//**
+ * \file
+ * \brief VG platform specific header
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _VGPLATFORM_H
+#define _VGPLATFORM_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef VG_API_CALL 
+#if defined(OPENVG_STATIC_LIBRARY)
+#	define VG_API_CALL
+#else
+#	if defined(_WIN32) || defined(__VC32__)				/* Win32 */
+#		if defined (OPENVG_DLL_EXPORTS)
+#			define VG_API_CALL __declspec(dllexport)
+#		else
+#			define VG_API_CALL __declspec(dllimport)
+#		endif
+#	else 
+#		define VG_API_CALL extern
+#	endif /* defined(_WIN32) ||... */
+#endif /* defined OPENVG_STATIC_LIBRARY */
+#endif /* ifndef VG_API_CALL */
+
+#ifndef VGU_API_CALL 
+#if defined(OPENVG_STATIC_LIBRARY)
+#	define VGU_API_CALL
+#else
+#	if defined(_WIN32) || defined(__VC32__)				/* Win32 */
+#		if defined (OPENVG_DLL_EXPORTS)
+#			define VGU_API_CALL __declspec(dllexport)
+#		else
+#			define VGU_API_CALL __declspec(dllimport)
+#		endif
+#	else 
+#		define VGU_API_CALL extern
+#	endif /* defined(_WIN32) ||... */
+#endif /* defined OPENVG_STATIC_LIBRARY */
+#endif /* ifndef VGU_API_CALL */
+
+
+#ifndef VG_API_ENTRY
+#define VG_API_ENTRY
+#endif
+
+#ifndef VG_API_EXIT
+#define VG_API_EXIT
+#endif
+
+#ifndef VGU_API_ENTRY
+#define VGU_API_ENTRY
+#endif
+
+#ifndef VGU_API_EXIT
+#define VGU_API_EXIT
+#endif
+
+typedef float          VGfloat;
+typedef signed char    VGbyte;
+typedef unsigned char  VGubyte;
+typedef signed short   VGshort;
+typedef signed int     VGint;
+typedef unsigned int   VGuint;
+typedef unsigned int   VGbitfield;
+
+#ifndef VG_VGEXT_PROTOTYPES
+#define VG_VGEXT_PROTOTYPES
+#endif 
+
+#ifdef __cplusplus 
+} /* extern "C" */
+#endif
+
+#endif /* _VGPLATFORM_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/VG/vgu.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,131 @@
+/* $Revision: 6810 $ on $Date:: 2008-10-29 07:31:37 -0700 #$ */
+
+/*------------------------------------------------------------------------
+ * 
+ * VGU 1.1 Reference Implementation
+ * -------------------------------------
+ *
+ * Copyright (c) 2008 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.
+ *
+ *//**
+ * \file
+ * \brief	VGU 1.1 API.
+ *//*-------------------------------------------------------------------*/
+
+#ifndef _VGU_H
+#define _VGU_H
+
+#ifdef __cplusplus 
+extern "C" { 
+#endif
+
+#include <VG/openvg.h>
+
+#define VGU_VERSION_1_0 1
+#define VGU_VERSION_1_1 2
+
+#ifndef VGU_API_CALL
+#	error VGU_API_CALL must be defined
+#endif
+
+#ifndef VGU_API_ENTRY
+#   error VGU_API_ENTRY must be defined 
+#endif
+
+#ifndef VGU_API_EXIT
+#   error VGU_API_EXIT must be defined 
+#endif
+
+
+typedef enum {
+  VGU_NO_ERROR                                 = 0,
+  VGU_BAD_HANDLE_ERROR                         = 0xF000,
+  VGU_ILLEGAL_ARGUMENT_ERROR                   = 0xF001,
+  VGU_OUT_OF_MEMORY_ERROR                      = 0xF002,
+  VGU_PATH_CAPABILITY_ERROR                    = 0xF003,
+  VGU_BAD_WARP_ERROR                           = 0xF004,
+
+  VGU_ERROR_CODE_FORCE_SIZE                    = VG_MAX_ENUM
+} VGUErrorCode;
+
+typedef enum {
+  VGU_ARC_OPEN                                 = 0xF100,
+  VGU_ARC_CHORD                                = 0xF101,
+  VGU_ARC_PIE                                  = 0xF102,
+
+  VGU_ARC_TYPE_FORCE_SIZE                      = VG_MAX_ENUM
+} VGUArcType;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguLine(VGPath path,
+                                  VGfloat x0, VGfloat y0,
+                                  VGfloat x1, VGfloat y1) VGU_API_EXIT;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguPolygon(VGPath path,
+                                     const VGfloat * points, VGint count,
+                                     VGboolean closed) VGU_API_EXIT;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguRect(VGPath path,
+                                  VGfloat x, VGfloat y,
+                                  VGfloat width, VGfloat height) VGU_API_EXIT;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguRoundRect(VGPath path,
+                                       VGfloat x, VGfloat y,
+                                       VGfloat width, VGfloat height,
+                                       VGfloat arcWidth, VGfloat arcHeight) VGU_API_EXIT;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguEllipse(VGPath path,
+                                     VGfloat cx, VGfloat cy,
+                                     VGfloat width, VGfloat height) VGU_API_EXIT;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguArc(VGPath path,
+                                 VGfloat x, VGfloat y,
+                                 VGfloat width, VGfloat height,
+                                 VGfloat startAngle, VGfloat angleExtent,
+                                 VGUArcType arcType) VGU_API_EXIT;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguComputeWarpQuadToSquare(VGfloat sx0, VGfloat sy0,
+                                                     VGfloat sx1, VGfloat sy1,
+                                                     VGfloat sx2, VGfloat sy2,
+                                                     VGfloat sx3, VGfloat sy3,
+                                                     VGfloat * matrix) VGU_API_EXIT;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguComputeWarpSquareToQuad(VGfloat dx0, VGfloat dy0,
+                                                     VGfloat dx1, VGfloat dy1,
+                                                     VGfloat dx2, VGfloat dy2,
+                                                     VGfloat dx3, VGfloat dy3,
+                                                     VGfloat * matrix) VGU_API_EXIT;
+
+VGU_API_CALL VGUErrorCode VGU_API_ENTRY vguComputeWarpQuadToQuad(VGfloat dx0, VGfloat dy0,
+                                                   VGfloat dx1, VGfloat dy1,
+                                                   VGfloat dx2, VGfloat dy2,
+                                                   VGfloat dx3, VGfloat dy3,
+                                                   VGfloat sx0, VGfloat sy0,
+                                                   VGfloat sx1, VGfloat sy1,
+                                                   VGfloat sx2, VGfloat sy2,
+                                                   VGfloat sx3, VGfloat sy3,
+                                                   VGfloat * matrix) VGU_API_EXIT;
+
+#ifdef __cplusplus 
+} /* extern "C" */
+#endif
+
+#endif /* #ifndef _VGU_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hostsupport/inc/VGInterface.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,216 @@
+/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * 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.
+ *
+ * Initial Contributors:
+ * Nokia Corporation - initial contribution.
+ *
+ * Contributors:
+ *
+ * Description:
+ *
+ */
+
+#ifndef _VGINTERFACE_H_
+#define _VGINTERFACE_H_
+
+#include "ImageTarget.h"
+
+struct SurfaceDescriptor;
+struct BufferContainer;
+class CColorDescriptor;
+
+typedef void (*fpVGProc)(void);
+
+// EGL services for VG
+class IVGtoEGLInterface
+    {
+public:
+    // \todo Descriptions
+    virtual void* GetVGContext() = 0;
+    virtual bool IsImageInUse( void* image ) = 0;
+    virtual bool LockVGSurface( bool read, bool write ) = 0;
+    virtual bool UnlockVGSurface() = 0;
+    virtual void GetDescForImage( void* image, SurfaceDescriptor& ImageDesc ) = 0;
+    virtual void* GetDataForImage( void* image ) = 0;
+	virtual void RegisterImageTarget( void* image, EImageTarget target, void* buffer ) = 0;
+	virtual void UnregisterImageTarget( void* image, EImageTarget target, void* buffer ) = 0;
+    };
+
+// VG services for EGL
+class IEGLtoVGInterface
+    {
+public:
+    /* \brief Sets interface for EGL services to VG
+     *
+     * \param egl Pointer to IVGtoEGLInterface implementation.
+     */
+    virtual void SetEGLInterface( IVGtoEGLInterface* egl ) = 0;
+
+    /* \brief Used to create internal VG context
+     * 
+     * \param shareContext  Context to be shared with created context
+     *
+     * \return  Handle to created context
+     */
+    virtual void* CreateContext( void* shareContext ) = 0;
+
+    /* \brief Releases internal VG context
+     * 
+     * \param context   Context to be released
+     *
+     * \return  true if release succeeded false otherwise
+     */
+    virtual bool ReleaseContext( void* context ) = 0;
+
+    /* \brief Creates internal VG surface
+     * 
+     * \param desc      Descriptor describing surface pixel format, size, stride etc.
+     * \param buffers   Container for buffers. VG should fill in handle for surface, color buffer and mask buffer.
+     * \param image     VG image handle used in surface creation (eglCreatePbufferFromClientBuffer()).
+     *
+     * \return true if surface creation succeeded false otherwise
+     */
+    virtual bool CreateSurface( const SurfaceDescriptor* desc, BufferContainer* buffers, void* image ) = 0;
+
+    /* \brief Releases internal VG surface
+     * 
+     * \param surface   Surface to be released
+     *
+     * \return  true if surface release succeeded false otherwise
+     */
+    virtual bool ReleaseSurface( void* surface ) = 0; 
+
+    /* \brief Sets current surface for internal VG context
+     * 
+     * \param context   Handle to internal VG context
+     * \param surface   Handle to internal VG surface to be set current to context.
+     *
+     * \return  true if succeeded false otherwise
+     */
+    virtual bool SetCurrentSurface( void* context, void* surface ) = 0;
+
+     /* \brief Resizes internal VG surface
+     * 
+     * \param context   Handle to internal VG context
+     * \param surface   Handle to internal VG surface
+     * \param width     New width
+     * \param height    New height
+     * \param buffers   Container for buffers. VG should fill in handle for surface, color buffer and mask buffer.
+     *
+     * \return  true if resize succeeded false otherwise
+     */
+    virtual bool ResizeSurface( void* context, void* surface, int width, int height, BufferContainer* buffers ) =0;
+
+    /* \brief Checks if image handle is valid VGImage
+     * 
+     * \param image     Handle to VG image
+     * \param colorDesc Color descriptor. VG should fill in descriptor describing image.
+     * \param width     On return should contain widht of the VG image
+     * \param height    On return should contain height of the VG image
+     *
+     * \return  true if image is valid false otherwise
+     */
+    virtual bool IsValidImage( void* image, CColorDescriptor* colorDesc, int* width, int* height ) = 0;
+
+    /* \brief Checks if image handle is in use by VG
+     *
+     * param image      Handle to VG image
+
+     * return true if image is in use false otherwise
+     */
+    virtual bool IsImageInUse( void* image ) = 0;
+
+    /* \brief Flushes current vg context. Same operation as vgFlush().
+     */
+    virtual void Flush() = 0;
+
+    /* \brief Finishes VG drawing. Same operation as vgFinish().
+     */
+    virtual void Finish() = 0;
+
+    /* \brief Used to get address of vg extension function. Called by eglGetProcAddress().
+     *
+     * \param procname Name of the vg extension function
+     *
+     * \return  Address of the vg extension function or NULL if extension is not found.
+     */
+    virtual fpVGProc GetVGProcAddress( const char *procname ) = 0;
+
+    /* \brief Copy VG color buffer into buffer.
+     * 
+     * \param buffer Buffer to copy data from VG color buffer
+     * \param stride Buffer stride
+     * \param surface Handle to VG internal surface to copy color buffer from.
+     * 
+     * \return void
+     */
+    virtual void CopyBuffers( void* buffer, int stride, void* surface ) = 0;
+
+    /* \brief Updates VG color buffer
+     *
+     * \param buffer Buffer to copy data from
+     * \param stride Stride of buffer
+     * \param desc   Surface descriptor describing buffer.
+     *
+     * \return void
+     */
+    virtual void UpdateBuffers( void* buffer, int stride, const SurfaceDescriptor* desc ) = 0;
+
+    /* \brief Checks if VG image is root image
+     *
+     * \param image Handle to VG image
+     *
+     * \return True if image is root, false otherwise
+     */
+    virtual bool IsRootImage( void* image ) = 0;
+
+    /* \brief Copies data from VG image
+     * 
+     * \param image Handle to VG image
+     * \param desc  Descriptor describing VG image. Function should fill descriptor.
+     * \param data  Pointer to copy data to.
+     * 
+     * \return void
+     */
+    virtual void GetImageData( void* image, SurfaceDescriptor& desc, void* data ) = 0;
+
+    /* \brief Add(+1) VG image reference count when EGLimage is created from VGImage
+     * 
+     * \param image Handle to VG image
+     * 
+     * \return void
+     */
+    virtual void AddRef( void* image ) = 0;
+
+    /* \brief Remove(-1) VG image reference count when EGLimage deleted
+     * 
+     * \param image Handle to VG image
+     * 
+     * \return void
+     */
+    virtual void RemoveRef( void* image ) = 0;
+    };
+
+typedef IEGLtoVGInterface* (*fpGetVGInterface)(void);
+IEGLtoVGInterface* LoadVGInterface( void*& libraryHandle );
+
+#endif // _VGINTERFACE_H_
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/inc/guestvideodriverinterfaceconstants.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,71 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Header file for the guest video driver
+
+#ifndef VirtualVideoInterfaceConstants_h_
+#define VirtualVideoInterfaceConstants_h_
+
+//      virtualhw.irq => ic.input[391];
+//        pvbus.pvbus_m_range[0x60000000..0x62ffffff] => graphicsvirtualhw.mbus; //=>Reserve own memory area later
+//        pvbus.pvbus_m_range[0x63000000..0x63000fff] => graphicsvirtualhw.pbus; //=>Reserve own memory area later                
+
+#ifdef PLATSIM_CONFIG
+#define VVI_BASE 0x60000000
+#else
+#define VVI_BASE 0x00000000
+#endif // PLATSIM_CONFIG
+
+// base address
+#define VVI_REGISTERS_BASE_ADDRESS VVI_BASE + 0x03000000 
+#define VVI_REGISTERS_MEMORY_SIZE 0x1000
+#define VVI_REGISTERS_MASK 0x0FFF
+
+#define VVI_PARAMETERS_INPUT_BASE_ADDRESS VVI_BASE + 0x00000000
+#define VVI_PARAMETERS_INPUT_MEMORY_SIZE  0x01000000
+
+#define VVI_PARAMETERS_OUTPUT_BASE_ADDRESS VVI_BASE + 0x01000000
+#define VVI_PARAMETERS_OUTPUT_MEMORY_SIZE  0x01000000
+
+#define VVI_SURFACEBUFFER_BASE_ADDRESS VVI_BASE + 0x02000000
+#define VVI_SURFACEBUFFER_MEMORY_SIZE  0x01000000
+
+// register indices, TODO: cleanup needed, some are not used
+#define VVI_R_ID                                0x0000
+#define VVI_R_IRQ_ENABLE                        0x0004
+#define VVI_R_IRQ_STATUS                        0x0008
+#define VVI_R_COMMAND                           0x000c
+#define VVI_R_PARAMETER_LOAD                    0x0010
+#define VVI_R_ERROR                             0x0014
+#define VVI_R_INPUT_BUFFER_TAIL                 0x0018
+#define VVI_R_INPUT_BUFFER_HEAD                 0x001c
+#define VVI_R_INPUT_BUFFER_READ_COUNT           0x0020
+#define VVI_R_INPUT_BUFFER_WRITE_COUNT          0x0024
+#define VVI_R_INPUT_BUFFER_MAX_TAIL             0x0028
+#define VVI_R_REQUEST_ID                        0x002c
+#define VVI_R_SHARED_CMD_MEMORY_BASE            0x0030
+#define VVI_R_SHARED_SURFACEBUFFER_MEMORY_BASE  0x0034
+#define VVI_R_LASTREG                           0x0038  // not a register, address of last register
+
+// COMMAND register values
+#define VVI_EXECUTE 0
+
+//IRQ number
+#ifdef PLATSIM_CONFIG
+#define VVI_IRQ 391
+#else
+// Jani - This is defined in syborg.h "EIntGraphics" - should we get it from there?
+#define VVI_IRQ 13
+#endif // PLATSIM_CONFIG
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/CMakeLists.txt	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,88 @@
+# Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+# All rights reserved.
+# This component and the accompanying materials are made available
+# under the terms of "Eclipse Public License v1.0"
+# which accompanies this distribution, and is available
+# at the URL "http://www.eclipse.org/legal/epl-v10.html".
+#
+# Initial Contributors:
+# Nokia Corporation - initial contribution.
+#
+# Contributors:
+#
+# Description:
+# CMake meta build file for the simulator host-side API wrapper
+
+set(WRAPPER_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)
+set(WRAPPER_INC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/inc)
+set(SERIALIZER_INC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../vghwserialiser/inc)
+set(SERIALIZER_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../vghwserialiser/src)
+# For guestvideodriverinterfaceconstants.h file
+set(VIDEODRIVER_INC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../inc)
+
+set(WRAPPER_LIBS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../lib)
+
+if(WIN32)
+	message("*** KhronosAPIWrapper Win32")
+	set(WRAPPER_SSE_FLAGS "/arch:SSE2")
+	set(WRAPPER_PLATFORM_LINK_LIBRARIES libEGL libOpenVG libGLESv1 libGLESv2)
+else(WIN32)
+	set(WRAPPER_SSE_FLAGS "-msse2 -mfpmath=sse -march=pentium4")
+	set(WRAPPER_PLATFORM_LINK_LIBRARIES m stdc++)
+endif(WIN32)
+
+set(WRAPPER_SRC_FILES
+    ${WRAPPER_INC_DIR}/apiwrapper.h
+    ${WRAPPER_INC_DIR}/eglapiwrapper.h
+    ${WRAPPER_INC_DIR}/graphicsvhwcallback.h
+    ${WRAPPER_INC_DIR}/KhronosAPIWrapper.h
+    ${WRAPPER_INC_DIR}/khronosapiwrapperdefs.h
+    ${WRAPPER_INC_DIR}/openvgapiwrapper.h
+    ${WRAPPER_INC_DIR}/driverapiwrapper.h
+    ${WRAPPER_INC_DIR}/opengles11apiwrapper.h
+    ${WRAPPER_INC_DIR}/syborg-graphicswrapper.h
+    ${WRAPPER_INC_DIR}/hostthreadadapter.h
+    ${WRAPPER_INC_DIR}/platformthreading.h
+    ${WRAPPER_INC_DIR}/platformtypes.h
+
+    ${SERIALIZER_INC_DIR}/remotefunctioncall.h
+    ${SERIALIZER_INC_DIR}/requestbuffer.h
+    ${SERIALIZER_INC_DIR}/serializedfunctioncall.h
+    ${SERIALIZER_INC_DIR}/serializerplatform.h
+    ${SERIALIZER_INC_DIR}/driverrfc.h
+    ${SERIALIZER_INC_DIR}/opengles11rfc.h
+
+    ${WRAPPER_SRC_DIR}/apiwrapper.cpp
+    ${WRAPPER_SRC_DIR}/eglapiwrapper.cpp
+    ${WRAPPER_SRC_DIR}/KhronosAPIWrapper.cpp
+    ${WRAPPER_SRC_DIR}/openvgapiwrapper.cpp
+    ${WRAPPER_SRC_DIR}/driverapiwrapper.cpp
+    ${WRAPPER_SRC_DIR}/opengles11apiwrapper.cpp    
+    ${WRAPPER_SRC_DIR}/syborg-graphicswrapper.cpp
+    ${WRAPPER_SRC_DIR}/platformthreading.cpp
+
+    ${SERIALIZER_SRC_DIR}/eglrfc.cpp
+    ${SERIALIZER_SRC_DIR}/openvgrfc.cpp
+    ${SERIALIZER_SRC_DIR}/remotefunctioncall.cpp
+    ${SERIALIZER_SRC_DIR}/serializedfunctioncall.cpp
+    ${SERIALIZER_SRC_DIR}/driverrfc.cpp
+    ${SERIALIZER_SRC_DIR}/opengles11rfc.cpp
+  )
+
+include_directories(
+  ${WRAPPER_INC_DIR}
+  ${SERIALIZER_INC_DIR}
+  ${KHRONOS_API_INC}
+  ${VIDEODRIVER_INC_DIR}
+  ${COMMON_INC_DIR}
+  )
+
+link_directories(${WRAPPER_LIBS_DIR} ${GLOBAL_LIB_DIR})
+
+add_definitions(-DKHRONOSAPIWRAPPER_EXPORTS -DSYBORG_GRAPHICSWRAPPER_EXPORTS)
+
+add_library(KhronosAPIWrapper SHARED ${WRAPPER_SRC_FILES})
+add_library(syborg-graphicswrapper SHARED ${WRAPPER_SRC_FILES})
+
+target_link_libraries(KhronosAPIWrapper ${WRAPPER_PLATFORM_LINK_LIBRARIES})
+target_link_libraries(syborg-graphicswrapper ${WRAPPER_PLATFORM_LINK_LIBRARIES})
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/KhronosAPIWrapper.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,125 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifndef KHRONOSAPIWRAPPER_H
+#define KHRONOSAPIWRAPPER_H
+
+#ifndef PSU_PLATFORMTHREADING_H
+#include "platformthreading.h"
+#endif
+
+#ifndef PSU_PLATFORMTYPES_H
+#include "platformtypes.h"
+#endif
+
+#include "requestbuffer.h"
+
+class APIWrapperStack;
+class RemoteFunctionCall;
+class RemoteFunctionCallData;
+class DriverAPIWrapper;
+class OpenVGAPIWrapper;
+class EGLAPIWrapper;
+class OGLES11Wrapper;
+
+#define KHRONOS_API_W_MULTITHREAD
+
+#ifdef WIN32
+#ifdef KHRONOSAPIWRAPPER_EXPORTS
+#define KHRONOSAPIWRAPPER_API __declspec(dllexport)
+#else
+#define KHRONOSAPIWRAPPER_API __declspec(dllimport)
+#endif
+#else
+#define KHRONOSAPIWRAPPER_API
+#endif
+
+class MGraphicsVHWCallback;
+
+class KHRONOSAPIWRAPPER_API KhronosAPIWrapper: private MRequestBufferBookKeepingReader
+{
+    public:
+
+        KhronosAPIWrapper( MGraphicsVHWCallback* aServiceIf, void* surfacebuffer,
+            void* inputdata, void* outputdata );
+        ~KhronosAPIWrapper();
+
+        void WorkerThread();
+
+        unsigned long Execute();
+        unsigned long InputParameterOffset();
+
+        void SetInputBufferTail(uint32_t p_val);
+        uint32_t InputBufferTail();
+        void SetInputBufferHead(uint32_t p_val);
+        uint32_t InputBufferHead();
+        void SetInputBufferReadCount(uint32_t p_val);
+        uint32_t InputBufferReadCount();
+        void SetInputBufferWriteCount(uint32_t p_val);
+        uint32_t InputBufferWriteCount();
+        void IncrementInputBufferReadCount( TUint32 aReadCount );
+        TUint32 InputMaxTailIndex();
+        void SetInputMaxTailIndex( TUint32 aIndex );
+
+		//For the purpose of wrappers that need each other's services
+		DriverAPIWrapper* GetDriverWrapper() { return m_DriverAPIWrapper; }
+		EGLAPIWrapper* GetEGLWrapper() { return m_EGLWrapper; }
+
+    private:
+//From MRequestBufferBookKeeping
+        TUint32 GetWriteCount();
+        void IncrementReadCount( TUint32 aReadCount );
+        TUint32 GetReadCount();
+
+        TUint32 BufferTail();
+        void SetBufferTail( TUint32 aIndex );
+        TUint32 BufferHead();
+
+        TUint32 MaxTailIndex();
+        void SetMaxTailIndex( TUint32 aIndex );
+
+    protected:
+        int HandleNextRequest();
+        bool m_initDone;
+        void* m_currentResult;
+        void* m_currentInput;
+        MGraphicsVHWCallback* iServiceIf;
+        Psu::PLATFORM_THREAD_T m_threadHandle;
+        Psu::PLATFORM_SEMAPHORE_T m_SemapHandle;
+        bool m_exit;
+        void* m_surfaceBuffer;
+
+//Input buffer
+        Psu::PLATFORM_MUTEX_T m_InputBufferMutex;
+        uint32_t m_InputBufferTail;
+        uint32_t m_InputBufferHead;
+        uint32_t m_InputBufferReadCount;
+        uint32_t m_InputbufferWriteCount;
+        uint32_t m_InputBufferMaxTailIndex;
+    private:
+        RequestBufferReader* m_InputRequestBuffer;
+        APIWrapperStack* iStack;
+		TUint32 m_lastProcessId;
+		TUint32 m_lastThreadId;
+		int m_lastVgError;
+		int m_lastEglError;
+		DriverAPIWrapper* m_DriverAPIWrapper;
+		OpenVGAPIWrapper* m_OpenVGWrapper;
+		OGLES11Wrapper* m_OGLESWrapper;
+		EGLAPIWrapper* m_EGLWrapper;
+
+		RemoteFunctionCallData* iRFCData;
+};
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/apiwrapper.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,110 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifndef APIWRAPPER_H
+#define APIWRAPPER_H
+
+#ifndef PSU_PLATFORMTHREADING_H
+#include "platformthreading.h"
+#endif
+
+#ifndef PSU_PLATFORMTYPES_H
+#include "platformtypes.h"
+#endif
+#include "remotefunctioncall.h"
+
+class RemoteFunctionCall;
+class MGraphicsVHWCallback;
+
+class APIWrapperStack
+{
+    public:
+        APIWrapperStack(): iStack( NULL ), iStackIndex(0), iStackSize(0)
+        {
+        }
+
+        bool InitStack( int stackSize )
+        {
+            if ( iStack )
+            {
+                delete [] iStack;
+            }
+
+            iStack = (char*)new unsigned long[(stackSize+3)/4];
+            iStackIndex = 0;
+            iStackSize = stackSize;
+            return iStack != NULL;
+        }
+
+        void* AllocFromStack( int size, int alignment )
+        {
+            unsigned int adjustedIndex = RemoteFunctionCallData::AlignIndex( iStackIndex, alignment );
+            if ( adjustedIndex + size < iStackSize )
+            {
+                iStackIndex = adjustedIndex + size;
+                return (void*)(iStack + adjustedIndex);
+            }
+            else
+            {
+                return NULL;
+            }
+        }
+
+        void ClearStack()
+        {
+            iStackIndex = 0;
+        }
+
+        ~APIWrapperStack()
+        {
+            delete [] iStack;
+            iStack = NULL;
+        }
+
+    private:
+
+        char* iStack;
+        unsigned int iStackIndex;
+        unsigned int iStackSize;
+};
+
+
+class APIWrapper
+{
+public:
+	virtual ~APIWrapper();
+
+	//void SetCurrentRFC(  );
+
+	virtual void SetProcessInformation( TUint32 aProcess, TUint32 aThread ) = 0;
+	virtual void Cleanup( TUint32 aProcess, TUint32 aThread ) = 0;
+    virtual int DispatchRequest( unsigned long aCode ) = 0;
+
+protected:
+    APIWrapper( RemoteFunctionCallData& currentFunctionCall, 
+		APIWrapperStack* stack,
+        void* result,
+		MGraphicsVHWCallback* serviceIf);
+
+	virtual int WriteReply();
+
+protected:
+	RemoteFunctionCallData& m_currentFunctionCallData;
+    void* m_currentResult;
+    APIWrapperStack* iStack;
+    MGraphicsVHWCallback* iServiceIf;
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/driverapiwrapper.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,194 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifndef DRIVERAPIWRAPPER_H
+#define DRIVERAPIWRAPPER_H
+
+#include <list>
+
+#include "apiwrapper.h"
+#include "graphicsvhwcallback.h"        //callback interface Wrapper=>Virtual HW
+#include "khronosapiwrapperdefs.h"
+#include "driverrfc.h"
+
+#include "eglapiwrapper.h"//needed to request thread switch for egl during some big operations
+class KhronosAPIWrapper;
+
+#ifndef __PIXELFORMATS_H__
+#define __PIXELFORMATS_H__
+/*
+typedef enum
+	{
+    VG_sXRGB_8888                               =  0 | (1 << 6),
+	VG_sARGB_8888                               =  1 | (1 << 6),
+	VG_sARGB_8888_PRE                           =  2 | (1 << 6),
+	VG_sRGB_565                                 =  3,
+	VG_A_8                                      = 11,
+	} VGImageFormat;*///TODO: get these from somewhere (copy sgconst.h and pixelformats.h maybe)
+
+typedef enum
+	{
+	/**
+	 32-bit RGB pixel format without alpha, with 8 bits are reserved for each color
+	 */
+	EUidPixelFormatXRGB_8888 = 0x10275496,
+	/**
+	 32-bit ARGB pixel format with alpha, using 8 bits per channel
+	 */
+	EUidPixelFormatARGB_8888 = 0x10275498,
+	/**
+	 32-bit ARGB pixel format with alpha (pre-multiplied), using 8 bits per channel
+	 */
+	EUidPixelFormatARGB_8888_PRE = 0x1027549A,
+	/**
+	 16-bit RGB pixel format with 5 bits for red, 6 bits for green, and 5 bits for
+	 blue
+	 */
+	EUidPixelFormatRGB_565 = 0x1027549E,
+	/**
+	 8-bit alpha only
+	 */
+	EUidPixelFormatA_8 = 0x102754A3,
+
+
+	} TUidPixelFormat;//TODO: get these from somewhere (copy sgconst.h and pixelformats.h maybe)
+
+#endif
+
+
+
+
+class DriverAPIWrapper: public APIWrapper
+{
+public:
+	DriverAPIWrapper( RemoteFunctionCallData& currentFunctionCallData, APIWrapperStack* stack,
+        void* result,
+		MGraphicsVHWCallback* serviceIf,
+		KhronosAPIWrapper* aAPIWrapper ):
+	APIWrapper( currentFunctionCallData, stack, result, serviceIf ),
+	m_currentFunctionCall( m_currentFunctionCallData ),
+	m_APIWrapper( aAPIWrapper ),
+	m_Dpy( EGL_NO_DISPLAY ),
+	m_PoolConfig( 0 ),
+	m_PoolContext( EGL_NO_CONTEXT ),
+    m_ContextWithFormatARGB_8888_PRE( EGL_NO_CONTEXT ),
+    m_ContextWithFormatARGB_8888( EGL_NO_CONTEXT ),
+    m_ContextWithFormatXRGB_8888( EGL_NO_CONTEXT ),
+    m_ContextWithFormatRGB_565( EGL_NO_CONTEXT ),
+    m_ContextWithFormatA_8( EGL_NO_CONTEXT ),
+    m_DudSurface( EGL_NO_SURFACE )
+	{
+		m_initialized = false;
+	}
+
+	bool IsSgBackingVGImage( VGImage aImage );
+
+	bool IsSgBackingPBuffer( EGLSurface aSurface );
+
+	void SetProcessInformation( TUint32 aProcess, TUint32 aThread )
+	{
+	}
+
+	void Cleanup( TUint32 aProcess, TUint32 aThread )
+	{
+	}
+
+    int DispatchRequest( unsigned long aCode )
+	{
+		TRACE("DriverAPIWrapper DispatchRequest() in proc/thread %u / %u \n", m_currentFunctionCall.Data().Header().iProcessId, m_currentFunctionCall.Data().Header().iProcessId );
+		int ret(0);
+		switch ( aCode )
+		{
+            case DriverRFC::EDrvCreatePoolContext:
+			{
+			ret = CreatePoolContext();
+			break;
+			}
+		case DriverRFC::EDrvCreatePbufferSg:
+			{
+			ret = CreatePbufferSg();
+			break;
+			}
+		case DriverRFC::EDrvCreateVGImageSg:
+			{
+			ret = CreateVGImageSg();
+			break;
+			}
+		case DriverRFC::EDrvDeleteSgImage:
+			{
+			ret = DeleteSgImage();
+			break;
+			}
+		case DriverRFC::EDrvSyncVGImageFromPBuffer:
+			{
+			//ret = SyncVGImageFromPBuffer();
+			break;
+			}
+		default:
+			{
+			ASSERT( FALSE );
+			break;
+			}
+		}
+		return ret;
+	}
+	EGLContext GetPoolContext(){ return m_PoolContext; }
+
+	//API for external users, such as the egl wrapper
+	void SyncVGImageFromPBuffer( EGLSurface aPbuffer, VGImage aVGImage );
+	int SyncPBufferFromVGImage( VGImage aSrc, VGint aWidth, VGint aHeight );
+
+	EGLint* getColorAttributes( int aPixelFormat, int& aRed, int& aGreen, int& aBlue, int& aAlpha );
+	EGLDisplay getDisplay(){ if( !m_initialized ){ CreatePoolContext(); }return m_Dpy; }
+
+protected:
+//Request handlers
+	int ClientShutdown()
+	{
+	TRACE("KhronosAPIWrapper ClientShutdown()\n");
+    return WriteReply();
+	}
+
+	int CreatePoolContext();
+
+	int CreatePbufferSg();
+
+	int CreateVGImageSg();
+
+	int DeleteSgImage();
+
+
+	VGImageFormat getVGColorFormat( int aPixelFormat );
+
+private:
+	DriverRFC m_currentFunctionCall;
+	KhronosAPIWrapper* m_APIWrapper;//not owned here
+
+	std::list<VGImage> m_SgImageVGImages;
+	std::list<EGLSurface> m_SgImagePbuffers;
+
+	bool m_initialized;
+
+	EGLDisplay m_Dpy;
+	EGLConfig  m_PoolConfig;
+	EGLContext m_PoolContext;
+    EGLContext m_ContextWithFormatARGB_8888_PRE;
+    EGLContext m_ContextWithFormatARGB_8888;
+    EGLContext m_ContextWithFormatXRGB_8888;
+    EGLContext m_ContextWithFormatRGB_565;
+    EGLContext m_ContextWithFormatA_8;
+    EGLSurface m_DudSurface;
+};
+#endif//DRIVERAPIWRAPPER
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/eglapiwrapper.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,138 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifndef EGLAPIWRAPPER_H
+#define EGLAPIWRAPPER_H
+
+#ifndef PSU_PLATFORMTYPES_H
+#include "platformtypes.h"
+#endif
+
+#include <map>
+
+#include "eglrfc.h"
+#include "apiwrapper.h"
+#include "egltypes.h"
+
+class KhronosAPIWrapper;
+
+
+struct TSurfaceKey
+{
+public:
+	int iDpy;
+	int iSurfaceId;
+	TUint64 iProcId;
+public:
+	TSurfaceKey( int aDpy, int aSurfaceId, TUint32 aProcId ) : iDpy( aDpy ), iSurfaceId( aSurfaceId ), iProcId( aProcId )
+	{
+	}
+
+	void set( int aDpy, int aSurfaceId, TUint32 aProcId )
+	{
+		iDpy = aDpy; iSurfaceId = aSurfaceId; iProcId = aProcId;
+	}
+
+	bool operator<(const TSurfaceKey& aOtherKey) const
+	{ 
+		if( iDpy != aOtherKey.iDpy )					{ return iDpy < aOtherKey.iDpy; }
+		else if( iSurfaceId != aOtherKey.iSurfaceId )	{ return iSurfaceId < aOtherKey.iSurfaceId; }
+		else if( iProcId!= aOtherKey.iProcId )			{ return iProcId < aOtherKey.iProcId; }
+		else {return false; }
+	}
+};
+
+struct TSurfaceData
+{
+public:
+	SymbianWindow* iWindow;
+	//sgImage-related data here later on
+public:
+	TSurfaceData( SymbianWindow* aWindow ) : iWindow( aWindow )
+	{
+	}
+};
+/**
+* This maps surfaces to their native symbian windows, and other metadata
+*
+*/
+typedef std::map< TSurfaceKey, TSurfaceData > TSurfaceMap;
+
+class MGraphicsVHWCallback;
+
+class EGLAPIWrapper: public APIWrapper
+{
+public:
+
+    EGLAPIWrapper( RemoteFunctionCallData& currentFunctionCallData, APIWrapperStack* stack,
+	        void* result,
+			MGraphicsVHWCallback* serviceIf,
+			void* surfacebuffer, KhronosAPIWrapper* aAPIWrapper );
+
+    int WriteReply();
+    int DispatchRequest( unsigned long aCode );
+	void SetProcessInformation( TUint32 aProcess, TUint32 aThread );
+	void Cleanup( TUint32 aProcess, TUint32 aThread );
+
+private:
+
+	int eglGetError();
+    int eglGetDisplay();
+    int eglInitialize();
+    int eglTerminate();
+    int eglQueryString();
+    int eglGetConfigs();
+    int eglChooseConfig();
+    int eglGetConfigAttrib();
+    int eglCreateWindowSurface();
+    int eglCreatePbufferSurface();
+    int eglCreatePixmapSurface();
+    int eglDestroySurface();
+    int eglQuerySurface();
+    int eglBindAPI();
+    int eglQueryAPI();
+    int eglWaitClient();
+    int eglReleaseThread();
+    int eglCreatePbufferFromClientBuffer();
+    int eglSurfaceAttrib();
+    int eglBindTexImage();
+    int eglReleaseTexImage();
+    int eglSwapInterval();
+    int eglCreateContext();
+    int eglDestroyContext();
+    int eglMakeCurrent();
+    int eglGetCurrentContext();
+    int eglGetCurrentSurface();
+    int eglGetCurrentDisplay();
+    int eglQueryContext();
+    int eglWaitGL();
+    int eglWaitNative();
+    int eglSwapBuffers();
+    int eglCopyBuffers();
+    int eglPlatsimSetSurfaceParams();
+	int eglPlatsimCopyImageData();
+	int eglPixmapSurfaceSizeChanged();
+
+private://Meta calls
+	int eglMetaGetConfigs();
+
+private:
+	int m_lastEglError;
+	EglRFC m_currentFunctionCall;
+	void* m_surfaceBuffer;
+	TSurfaceMap m_windowMap;
+	KhronosAPIWrapper* m_APIWrapper;
+};
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/egltypes.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,113 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// EGL/EGLTYPES.H
+// 
+//
+
+/* NOTE: If you change the signature of the library and it causes a build
+         break, please see readme.txt on EGL root folder
+*/
+
+#ifndef __EGL_EGLTYPES_H__
+#define __EGL_EGLTYPES_H__
+
+
+
+
+/**
+@publishedAll
+@released
+*/
+
+/*
+** egltypes.h is platform dependent. It defines:
+**
+**     - EGL types and resources
+**     - Native types
+**     - EGL and native handle values
+**
+** EGL types and resources are to be typedef'ed with appropriate platform
+** dependent resource handle types. EGLint must be an integer of at least
+** 32-bit.
+**
+** NativeDisplayType, NativeWindowType and NativePixmapType are to be
+** replaced with corresponding types of the native window system in egl.h.
+**
+** EGL and native handle values must match their types.
+**
+*/
+
+typedef struct
+{
+	void* buffer0;
+	void* buffer1;
+} PlatformSpecificSurface;
+
+enum TDisplayMode
+	{
+	/** No display mode */
+	ENone,
+	/** Monochrome display mode (1 bpp) */
+	EGray2,
+	/** Four grayscales display mode (2 bpp) */
+	EGray4,
+	/** 16 grayscales display mode (4 bpp) */
+	EGray16,
+	/** 256 grayscales display mode (8 bpp) */
+	EGray256,
+	/** Low colour EGA 16 colour display mode (4 bpp) */
+	EColor16,
+	/** 256 colour display mode (8 bpp) */
+	EColor256,
+	/** 64,000 colour display mode (16 bpp) */
+	EColor64K,
+	/** True colour display mode (24 bpp) */
+	EColor16M,
+	/** (Not an actual display mode used for moving buffers containing bitmaps) */
+	ERgb,
+	/** 4096 colour display (12 bpp). */
+	EColor4K,
+	/** True colour display mode (32 bpp, but top byte is unused and unspecified) */
+	EColor16MU,
+	/** Display mode with alpha (24bpp colour plus 8bpp alpha) */
+	EColor16MA,
+	/** Pre-multiplied Alpha display mode (24bpp color multiplied with the alpha channel value, plus 8bpp alpha) */
+	EColor16MAP,
+	//Any new display mode should be insterted here!
+	//There might be up to 255 display modes, so value of the last
+	//inserted EColorXXX enum item should be less than 256 -
+	//BC reasons!
+	EColorLast
+	};
+
+struct SymbianWindow
+{
+	int id;
+	int width;
+	int height;
+	int horizontalPitch;
+    int verticalPitch;
+};
+
+struct SymbianPixmap
+{
+	enum TDisplayMode format;
+	unsigned long* data;
+	int width;
+	int height;
+	int stride;
+	int type;
+};
+
+#endif // __EGL_EGLTYPES_H__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/graphicsvhwcallback.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,29 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Graphics virtual hardware callback interface
+
+#ifndef GRAPHICSVHWCALLBACK_H
+#define GRAPHICSVHWCALLBACK_H
+
+class MGraphicsVHWCallback
+{
+public:
+    virtual ~MGraphicsVHWCallback() {}
+    virtual void LockOutputBuffer() = 0;
+    virtual void ReleaseOutputBuffer() = 0;
+    virtual void ProcessingDone(int aTransactionId) = 0;
+};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/hostthreadadapter.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,27 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Host thread adapter header file
+
+#ifndef HOSTTHREADADAPTER_H
+#define HOSTTHREADADAPTER_H
+
+#pragma once
+
+#define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers
+#define _WIN32_WINNT 0x0400
+
+#include "platformthreading.h"
+
+#endif // HOSTTHREADADAPTER
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/khronosapiwrapperdefs.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,34 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifndef KHRONOSAPIWRAPPERDEFS_H
+#define KHRONOSAPIWRAPPERDEFS_H
+
+#include "guestvideodriverinterfaceconstants.h"
+
+const int KMaxStackSize( VVI_PARAMETERS_INPUT_MEMORY_SIZE );//16Mb
+
+//Checks for error after every request and logs it
+#define LOG_ERROR
+
+// tracing
+//#define PRINT_TRACES
+#ifdef PRINT_TRACES
+    #define TRACE(format, ...) printf(format, ##__VA_ARGS__)
+#else
+    #define TRACE(format, ...)
+#endif
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/opengles11apiwrapper.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,225 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifndef OPENGLES11APIWRAPPER_H
+#define OPENGLES11APIWRAPPER_H
+
+#ifndef PSU_PLATFORMTYPES_H
+#include "platformtypes.h"
+#endif
+
+#include "opengles11rfc.h"
+#include "apiwrapper.h"
+
+class MGraphicsVHWCallback;
+
+/* vertex array pointers */
+enum
+{
+    COLOR_ARRAY,
+    NORMAL_ARRAY,
+    POINT_SIZE_ARRAY,
+    TEX_COORD_ARRAY,
+    VERTEX_ARRAY,
+    MATRIX_INDEX_ARRAY,
+    WEIGHT_ARRAY,
+    NUM_ARRAYS
+};
+typedef struct
+{
+    GLint size;
+    GLenum type;
+    GLsizei stride;
+    GLvoid *pointer;
+} vertexArrayInfo;
+
+class OGLES11Wrapper: public APIWrapper
+{
+public:
+    OGLES11Wrapper(RemoteFunctionCallData& currentFunctionCallData,
+            APIWrapperStack* stack,
+            void* result,
+            MGraphicsVHWCallback* serviceIf);
+
+    void SetProcessInformation(TUint32 aProcess, TUint32 aThread) {}
+    void Cleanup(TUint32 aProcess, TUint32 aThread) {}
+    int DispatchRequest(unsigned long aCode);
+
+    int WriteReply();
+private:
+    int m_lastGlError;
+    OpenGlES11RFC m_currentFunctionCall;
+
+    // Here follows the functions that map to the GL calls
+
+    int glActiveTexture();
+    int glAlphaFunc();
+    int glAlphaFuncx();
+    int glBindBuffer();
+    int glBindTexture();
+    int glBlendFunc();
+    int glBufferData();
+    int glBufferSubData();
+    int glClear();
+    int glClearColor();
+    int glClearColorx();
+    int glClearDepthf();
+    int glClearDepthx();
+    int glClearStencil();
+    int glClientActiveTexture();
+    int glClipPlanef();
+    int glClipPlanex();
+    int glColor4f();
+    int glColor4ub();
+    int glColor4x();
+    int glColorMask();
+    int glColorPointer();
+    int glCompressedTexImage2D();
+    int glCompressedTexSubImage2D();
+    int glCopyTexImage2D();
+    int glCopyTexSubImage2D();
+    int glCullFace();
+    int glDeleteBuffers();
+    int glDeleteTextures();
+    int glDepthFunc();
+    int glDepthMask();
+    int glDepthRangef();
+    int glDepthRangex();
+    int glDisable();
+    int glDisableClientState();
+    int glDrawArrays();
+    int glDrawElements();
+    int glEnable();
+    int glEnableClientState();
+    int glFinish();
+    int glFlush();
+    int glFogf();
+    int glFogfv();
+    int glFogx();
+    int glFogxv();
+    int glFrontFace();
+    int glFrustumf();
+    int glFrustumx();
+    int glGenBuffers();
+    int glGenTextures();
+    int glGetBooleanv();
+    int glGetBufferParameteriv();
+    int glGetClipPlanef();
+    int glGetClipPlanex();
+    int glGetError();
+    int glGetFixedv();
+    int glGetFloatv();
+    int glGetIntegerv();
+    int glGetLightfv();
+    int glGetLightxv();
+    int glGetMaterialfv();
+    int glGetMaterialxv();
+    int glGetPointerv();
+    int glGetString();
+    int glGetTexEnvfv();
+    int glGetTexEnviv();
+    int glGetTexEnvxv();
+    int glGetTexParameterfv();
+    int glGetTexParameteriv();
+    int glGetTexParameterxv();
+    int glHint();
+    int glIsBuffer();
+    int glIsEnabled();
+    int glIsTexture();
+    int glLightModelf();
+    int glLightModelfv();
+    int glLightModelx();
+    int glLightModelxv();
+    int glLightf();
+    int glLightfv();
+    int glLightx();
+    int glLightxv();
+    int glLineWidth();
+    int glLineWidthx();
+    int glLoadIdentity();
+    int glLoadMatrixf();
+    int glLoadMatrixx();
+    int glLogicOp();
+    int glMaterialf();
+    int glMaterialfv();
+    int glMaterialx();
+    int glMaterialxv();
+    int glMatrixMode();
+    int glMultMatrixf();
+    int glMultMatrixx();
+    int glMultiTexCoord4f();
+    int glMultiTexCoord4x();
+    int glNormal3f();
+    int glNormal3x();
+    int glNormalPointer();
+    int glOrthof();
+    int glOrthox();
+    int glPixelStorei();
+    int glPointParameterf();
+    int glPointParameterfv();
+    int glPointParameterx();
+    int glPointParameterxv();
+    int glPointSize();
+    int glPointSizex();
+    int glPolygonOffset();
+    int glPolygonOffsetx();
+    int glPopMatrix();
+    int glPushMatrix();
+    int glReadPixels();
+    int glRotatef();
+    int glRotatex();
+    int glSampleCoverage();
+    int glSampleCoveragex();
+    int glScalef();
+    int glScalex();
+    int glScissor();
+    int glShadeModel();
+    int glStencilFunc();
+    int glStencilMask();
+    int glStencilOp();
+    int glTexCoordPointer();
+    int glTexEnvf();
+    int glTexEnvfv();
+    int glTexEnvi();
+    int glTexEnviv();
+    int glTexEnvx();
+    int glTexEnvxv();
+    int glTexImage2D();
+    int glTexParameterf();
+    int glTexParameterfv();
+    int glTexParameteri();
+    int glTexParameteriv();
+    int glTexParameterx();
+    int glTexParameterxv();
+    int glTexSubImage2D();
+    int glTranslatef();
+    int glTranslatex();
+    int glVertexPointer();
+    int glViewport();
+    int glCurrentPaletteMatrixOES();
+    int glDrawTexfOES();
+    int glDrawTexfvOES();
+    int glDrawTexiOES();
+    int glDrawTexivOES();
+    int glDrawTexsOES();
+    int glDrawTexsvOES();
+    int glDrawTexxOES();
+    int glDrawTexxvOES();
+    int glLoadPaletteFromModelViewMatrixOES();
+    int glQueryMatrixxOES();
+
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/openvgapiwrapper.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,155 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifndef OPENVGAPIWRAPPER_H
+#define OPENVGAPIWRAPPER_H
+
+#ifndef PSU_PLATFORMTYPES_H
+#include "platformtypes.h"
+#endif
+
+#include "requestbuffer.h"
+#include "apiwrapper.h"
+
+class MGraphicsVHWCallback;
+class APIWrapperStack;
+
+class OpenVGAPIWrapper: public APIWrapper
+{
+public:
+    OpenVGAPIWrapper( RemoteFunctionCallData& currentFunctionCallData, APIWrapperStack* stack,
+	        void* result,
+			MGraphicsVHWCallback* serviceIf, KhronosAPIWrapper* aAPIWrapper );
+
+	int WriteReply();
+	
+	void SetProcessInformation( TUint32 aProcess, TUint32 aThread )
+	{
+	}
+
+	void Cleanup( TUint32 aProcess, TUint32 aThread )
+	{
+	}
+
+    int DispatchRequest( unsigned long aCode );
+    int vgCreatePaint();
+    int vgDestroyPaint();
+    int vgSetPaint();
+    int vgSetParameteri();
+    int vgSetParameterf();
+    int vgSetParameterfv();
+    int vgCreatePath();
+    int vgDrawPath();
+    int vgDestroyPath();
+    int vgAppendPathData();
+    int vgGetError();
+    int vgSeti();
+    int vgSetf();
+    int vgSetfv();
+    int vgClear();
+    int vgLoadIdentity();
+    int vgRotate();
+    int vgScale();
+    int vgTranslate();
+    int vgReadPixels();
+    int vgFlush();
+    int vgFinish();
+    int vgSetiv();
+
+    int vgGetf();
+    int vgGeti();
+    int vgGetVectorSize();
+    int vgGetParameterf();
+    int vgGetParameteri();
+    int vgGetParameterVectorSize();
+    int vgShear();
+    int vgMask();
+    int vgRenderToMask();
+    int vgCreateMaskLayer();
+    int vgDestroyMaskLayer();
+    int vgFillMaskLayer();
+    int vgCopyMask();
+    int vgClearPath();
+    int vgRemovePathCapabilities();
+    int vgGetPathCapabilities();
+    int vgAppendPath();
+    int vgTransformPath();
+    int vgInterpolatePath();
+    int vgPathLength();
+    int vgGetPaint();
+    int vgSetColor();
+    int vgGetColor();
+    int vgPaintPattern();
+    int vgCreateImage();
+    int vgDestroyImage();
+    int vgClearImage();
+    int vgChildImage();
+    int vgGetParent();
+    int vgCopyImage();
+    int vgDrawImage();
+    int vgSetPixels();
+    int vgGetPixels();
+    int vgCopyPixels();
+    int vgCreateFont();
+    int vgDestroyFont();
+    int vgClearGlyph();
+    int vgDrawGlyph();
+    int vgGaussianBlur();
+    int vgHardwareQuery();
+    int vgConvolve();
+    int vgColorMatrix();
+    int vgWritePixels();
+    int vgImageSubData();
+    int vgSetParameteriv();
+    int vgLoadMatrix();
+    int vgMultMatrix();
+    int vgModifyPathCoords();
+    int vgSetGlyphToPath();
+    int vgSetGlyphToImage();
+    int vgDrawGlyphs();
+    int vgSeparableConvolve();
+    int vgLookup();
+    int vgLookupSingle();
+    int vgGetMatrix();
+    int vgGetfv();
+    int vgGetiv();
+    int vgGetParameterfv();
+    int vgGetParameteriv();
+    int vgGetImageSubData();
+    int vgPointAlongPath();
+    int vgPathBounds();
+    int vgPathTransformedBounds();
+    int vgePathCoordsSizeInBytes();
+
+    int vguLine();
+    int vguPolygon();
+    int vguRect();
+    int vguRoundRect();
+    int vguEllipse();
+    int vguArc();
+    int vguComputeWarpQuadToSquare();
+    int vguComputeWarpSquareToQuad();
+    int vguComputeWarpQuadToQuad();
+private:
+	void doSync( int aParamIndex, VGImage aDst, VGImage aSrc = 0 );
+private:
+	int m_lastVgError;
+	OpenVgRFC m_currentFunctionCall;
+	typedef VGint (*vgePathCoordsSizeInBytesPtrType)(VGPath, VGint, VGint);
+	//VGint (*vgePathCoordsSizeInBytesPtr)(VGPath, VGint, VGint);
+	vgePathCoordsSizeInBytesPtrType vgePathCoordsSizeInBytesPtr;
+	KhronosAPIWrapper* m_APIWrapper;
+};
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/platformthreading.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,164 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// This header is to create platform independent
+// threading / synchronization API types and values.
+
+#ifndef PSU_PLATFORMTHREADING_H
+#define PSU_PLATFORMTHREADING_H
+
+#ifdef WIN32
+#include <windows.h>
+#else
+#include <pthread.h>
+#include <semaphore.h>
+#include <signal.h>
+#endif
+
+#include "platformtypes.h"
+
+namespace Psu
+{
+
+#ifdef WIN32
+
+    typedef HANDLE PLATFORM_THREAD_T;
+    typedef DWORD PLATFORM_THREADFUNC_RETTYPE;
+    typedef LPTHREAD_START_ROUTINE PLATFORM_THREADFUNC;
+    typedef CRITICAL_SECTION PLATFORM_MUTEX_T;
+    typedef HANDLE PLATFORM_SEMAPHORE_T;
+    typedef DWORD STATUS_T;
+
+#ifdef __GNUG__
+    typedef void (*PLATFORM_INTERRUPT_HANDLER)(ULONG_PTR);
+#else
+    typedef VOID CALLBACK PLATFORM_INTERRUPT_HANDLER (__in  ULONG_PTR);
+#endif
+
+#else // LINUX
+
+    typedef pthread_t PLATFORM_THREAD_T;
+    typedef void * PLATFORM_THREADFUNC_RETTYPE;
+    typedef void * (*PLATFORM_THREADFUNC)(void *);
+    typedef pthread_mutex_t PLATFORM_MUTEX_T;
+    typedef sem_t PLATFORM_SEMAPHORE_T;
+    typedef int STATUS_T;
+
+    typedef void (*PLATFORM_INTERRUPT_HANDLER)(int);
+
+#define WINAPI
+
+#endif
+
+#ifndef WIN32
+    extern const int MicrosecsInMillisec;
+#endif
+
+
+    /**
+     * Creates a thread with the default attributes.
+     */
+    int platform_create_simple_thread(PLATFORM_THREAD_T * pThreadHandle,
+                                      PLATFORM_THREADFUNC pFunc,
+                                      void * param);
+
+    /**
+     * Releases a thread (does not kill it).
+     */
+    void platform_release_thread(PLATFORM_THREAD_T threadHandle);
+
+    /**
+     * Waits for a thread to terminate.
+     */
+    STATUS_T platform_join_thread(PLATFORM_THREAD_T threadHandle);
+
+    /**
+     * Initializes a mutex (CRITICAL_SECTION on windows).
+     */
+    void platform_mutex_init(PLATFORM_MUTEX_T * pMutex);
+
+    /**
+     * Destroys a mutex (CRITICAL_SECTION on windows).
+     */
+    void platform_mutex_destroy(PLATFORM_MUTEX_T * pMutex);
+
+    /**
+     *Locks a mutex  ("enters" a CRITICAL_SECTION on windows).
+     */
+    void platform_mutex_lock(PLATFORM_MUTEX_T * pMutex);
+
+    /**
+     * Unlocks a mutex ("exits" a CRITICAL_SECTION on windows).
+     */
+    void platform_mutex_unlock(PLATFORM_MUTEX_T * pMutex);
+
+
+    /**
+     * Sleeps for a certain duration for given milliseconds.
+     */
+    void platform_sleep(int millisecs);
+
+	 /**
+     * Creates a semaphore with the default attributes.
+     */
+	STATUS_T platform_create_semaphore(PLATFORM_SEMAPHORE_T& semHandle,
+    					int initialCount,int maximumCount);
+
+
+    /**
+     * wait for the semaphore signal
+     */
+    STATUS_T platform_wait_for_signal(PLATFORM_SEMAPHORE_T& semHandle);
+
+    /**
+     *  Posts a semaphore signal so that the pending thread can continue
+     */
+    void platform_signal_semaphore(PLATFORM_SEMAPHORE_T& semHandle);
+
+    /**
+     * releases a semaphore object/handle.
+     */
+    void platform_release_semaphore(PLATFORM_SEMAPHORE_T& semHandle);
+
+    /**
+    * do an interruptable sleep
+    * @param length the length thread should sleep, in milliseconds
+    * @return 0 if the sleep expires normally, non-zero if the sleep has
+    * been interrupted
+    */
+    int32_t platform_interruptable_sleep(int64_t length);
+
+    /**
+    * signals a thread to interrupt a sleep
+    * @param handle PLATFORM_THREAD_T handle to the thread
+    * @return whether the interrupt succeeded or not
+    */
+    bool platform_interrupt_sleep(PLATFORM_THREAD_T handle);
+
+#ifndef WIN32
+    class SignalUSR1Handler
+    {
+    private:
+        SignalUSR1Handler();
+        ~SignalUSR1Handler();
+
+        struct sigaction sa;
+        struct sigaction old;
+
+    public:
+        static SignalUSR1Handler instance;
+    };
+#endif
+}
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/platformtypes.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,90 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Cross platform types
+
+#ifndef PSU_PLATFORMTYPES_H
+#define PSU_PLATFORMTYPES_H
+
+#include <limits.h>
+
+
+#ifdef WIN32
+#define DllExport   __declspec( dllexport )
+#else  // LINUX
+#define DllExport
+#endif
+
+
+#ifdef WIN32
+
+#if !defined(__STDC_CONSTANT_MACROS) && !defined(HAVE_STDINT_H)
+#define __STDC_CONSTANT_MACROS
+    /*  MSVC++ does not have the standard header <stdint.h>, so we need to
+        write here all the declarations that <stdint.h> shall contain */
+#ifndef HAVE_INT8_T
+#define HAVE_INT8_T 1
+    typedef signed __int8         int8_t;
+#endif
+#ifndef HAVE_INT16_T
+#define HAVE_INT16_T 1
+    typedef signed __int16        int16_t;
+#endif
+#ifndef HAVE_INT32_T
+#define HAVE_INT32_T 1
+    typedef signed __int32        int32_t;
+#endif
+#ifndef HAVE_INT64_T
+#define HAVE_INT64_T 1
+    typedef signed __int64        int64_t;
+#endif
+#ifndef HAVE_U_INT8_T
+#define HAVE_U_INT8_T 1
+    typedef unsigned __int8     uint8_t;
+    typedef unsigned __int8     u_int8_t;
+#endif
+#ifndef HAVE_U_INT16_T
+#define HAVE_U_INT16_T 1
+    typedef unsigned __int16    uint16_t;
+    typedef unsigned __int16    u_int16_t;
+#endif
+#ifndef HAVE_U_INT32_T
+#define HAVE_U_INT32_T 1
+    typedef unsigned __int32    uint32_t;
+    typedef unsigned __int32    u_int32_t;
+#endif
+#ifndef HAVE_U_INT64_T
+#define HAVE_U_INT64_T 1
+    typedef unsigned __int64    uint64_t;
+    typedef unsigned __int64    u_int64_t;
+#endif
+
+
+
+// on both Linux and Windows platforms, size_t is a 4-bytes unsigned integer
+// on Linux, ssize_t is a 4 bytes signed integer
+// Windows does not seem to have a ssize_t
+typedef int32_t ssize_t;
+
+#endif  // __STDC_CONSTANT_MACROS
+#else
+#include <stdint.h>
+#include <sys/types.h>
+#endif
+
+
+// a byte will be an unsigned char, i.e. an unsigned int8_t
+// this typedef works fine on both Linux and Windows
+typedef unsigned char byte_t;
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/inc/syborg-graphicswrapper.h	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,47 @@
+#ifndef _SYBORG_GRAPHICSWRAPPER_H
+#define _SYBORG_GRAPHICSWRAPPER_H
+
+#pragma once
+					  
+#ifdef WIN32
+#ifdef SYBORG_GRAPHICSWRAPPER_EXPORTS
+#define SYBORG_GRAPHICSWRAPPER_API __declspec(dllexport)
+#else
+#define SYBORG_GRAPHICSWRAPPER_API __declspec(dllimport)
+#endif
+#else
+#define SYBORG_GRAPHICSWRAPPER_API
+#endif
+
+Psu::PLATFORM_SEMAPHORE_T m_outputBufferSemaphore;
+int (*m_pythonCallBack)(int); 
+KhronosAPIWrapper* m_wrapper;
+														   
+
+// Derived from GraphicsVirtualHW.lisa
+static const int VVHW_BUFFER (0x3000000);
+static const int VVHW_INPUT_BUFFER (0x1000000);
+static const int VVHW_INPUT_BASE(0x0);
+static const int VVHW_OUTPUT_BUFFER (0x1000000);
+static const int VVHW_OUTPUT_BASE(0x1000000);
+static const int VVHW_FRAME_BUFFER (0x1000000);
+static const int VVHW_FRAME_BASE(0x2000000);
+
+class SyborgGraphicsWrapper : public MGraphicsVHWCallback
+    {
+    public:
+
+        SyborgGraphicsWrapper();
+        ~SyborgGraphicsWrapper();
+
+        int Reset( uint32_t *aGraphicsMemBase,  uint32_t *aCommandMemBase );
+
+        virtual void LockOutputBuffer();
+	    virtual void ReleaseOutputBuffer();
+	    virtual void ProcessingDone(int i);
+
+    private:
+    };
+
+
+#endif // _SYBORG_GRAPHICSWRAPPER_H
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/src/KhronosAPIWrapper.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,410 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN                       // Exclude rarely-used stuff from Windows headers
+#include <windows.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <EGL/egl.h>
+#include <vg/openvg.h>
+#include "GLES/gl.h"
+
+#include "KhronosAPIWrapper.h"
+#include "serializedfunctioncall.h"
+#include "remotefunctioncall.h"
+#include "openvgrfc.h"
+#include "eglrfc.h"
+#include "driverrfc.h"
+#include "apiwrapper.h"
+#include "driverapiwrapper.h"
+#include "eglapiwrapper.h"
+#include "openvgapiwrapper.h"
+#include "opengles11apiwrapper.h"
+
+#include "graphicsvhwcallback.h"        //callback interface Wrapper=>Virtual HW
+
+#include "platformthreading.h"
+#include "serialisedapiuids.h"
+#include "khronosapiwrapperdefs.h"
+
+
+
+
+Psu::PLATFORM_THREADFUNC_RETTYPE WINAPI WorkerThreadFunction(void* aParam)
+{
+    TRACE("KhronosAPIWrapper WorkerThreadFunction ->\n");
+    KhronosAPIWrapper* impl=(KhronosAPIWrapper*) aParam;
+    impl->WorkerThread();
+    TRACE("KhronosAPIWrapper WorkerThreadFunction <-\n");
+    return 0;
+}
+
+int KhronosAPIWrapper::HandleNextRequest()
+{
+    TRACE("KhronosAPIWrapper::HandleNextRequest() ->\n");
+    int ret(0);
+    uint32_t inputBufferTail = m_InputRequestBuffer->GetReadIndex();
+	RemoteFunctionCallData& rfc( *iRFCData );
+    SerializedFunctionCall remotefcall(rfc);
+    TRACE("KhronosAPIWrapper::HandleNextRequest ParseBuffer from %u\n",  inputBufferTail);
+    TInt len = remotefcall.ParseBuffer( ((TUint8*)(m_currentInput))+inputBufferTail,
+        VVI_PARAMETERS_INPUT_MEMORY_SIZE - inputBufferTail );
+    ASSERT( len != -1 );
+    m_InputRequestBuffer->FreeBytes( len );
+
+    //TRACE("KhronosAPIWrapper::WorkerThread DispatchRequest -> %u\n",  m_currentFunctionCall.Data().Header().iTransactionId);
+	TRACE("KhronosAPIWrapper::HandleNextRequest DispatchRequest opCode -> %u / retval initially:%d\n",  rfc.Header().iOpCode, rfc.Header().iReturnValue );
+
+    const TUint32 processId(rfc.Header().iProcessId);
+    const TUint32 threadId(rfc.Header().iThreadId);
+
+	if ( processId != m_lastProcessId || threadId != m_lastThreadId )
+		{
+		m_lastProcessId = processId;
+		m_lastThreadId = threadId;
+		TRACE("KhronosAPIWrapper::HandleNextRequest Set process info for %u / %u \n", processId, threadId );
+		m_EGLWrapper->SetProcessInformation( processId, threadId );
+		}
+
+	switch ( rfc.Header().iApiUid )
+		{
+		case SERIALISED_DRIVER_API_UID:
+			{
+			TRACE("KhronosAPIWrapper::HandleNextRequest SERIALISED_DRIVER_API_UID \n" );
+			if ( DriverRFC::EDrvClientShutdown == rfc.Header().iOpCode )
+				{
+				m_OpenVGWrapper->Cleanup( processId, threadId );
+				m_EGLWrapper->Cleanup( processId, threadId );
+				m_OGLESWrapper->Cleanup( processId, threadId );
+				}
+			else
+				{
+				m_DriverAPIWrapper->DispatchRequest( rfc.Header().iOpCode );
+				}
+			break;
+			}
+		case SERIALISED_OPENVG_API_UID:
+			{
+			ret = m_OpenVGWrapper->DispatchRequest( rfc.Header().iOpCode );
+			break;
+			}
+		case SERIALISED_EGL_API_UID:
+			{
+			ret = m_EGLWrapper->DispatchRequest( rfc.Header().iOpCode );
+			break;
+			}
+		case SERIALISED_OPENGLES_1_1_API_UID:
+			{
+			m_OGLESWrapper->SetProcessInformation( processId, threadId );
+			ret = m_OGLESWrapper->DispatchRequest( rfc.Header().iOpCode );
+			break;
+			}
+		default:
+			break;
+		}
+
+    TRACE("KhronosAPIWrapper::HandleNextRequest DispatchRequest <-\n");
+
+	if ( RemoteFunctionCallData::EOpReply ==  rfc.Header().iOpType )
+    {
+        TRACE("KhronosAPIWrapper::HandleNextRequest ProsessingDone ->\n");
+        iServiceIf->ProcessingDone( rfc.Header().iTransactionId );
+        TRACE("KhronosAPIWrapper::HandleNextRequest ProsessingDone <-\n");
+    }
+    else if ( !m_InputRequestBuffer->IsDataAvailable() )
+    {
+        iServiceIf->LockOutputBuffer(); //We need to use the lock buffer so that the request id register is protected
+        iServiceIf->ProcessingDone( 0 ); //Signal driver that buffer is empty
+    }
+    TRACE("ret = %d\n", ret);
+    TRACE("KhronosAPIWrapper::HandleNextRequest() <-\n");
+    return ret;
+}
+
+
+void KhronosAPIWrapper::WorkerThread()
+{
+    TRACE("KhronosAPIWrapper::WorkerThread ->\n");
+    while(1)
+    {
+        int ret;
+
+        while ( !m_exit && !m_InputRequestBuffer->IsDataAvailable() )
+        {
+            TRACE("KhronosAPIWrapper::WorkerThread Waiting\n");
+			//No more data, wait for some more
+            Psu::platform_wait_for_signal(m_SemapHandle);
+            TRACE("KhronosAPIWrapper::WorkerThread Signaled\n");
+        }
+
+        TRACE("KhronosAPIWrapper::WorkerThread Process request\n");
+
+        if ( m_exit )
+        {
+            TRACE("KhronosAPIWrapper::WorkerThread m_exit\n");
+            return;
+        }
+        ret = HandleNextRequest();
+        TRACE("KhronosAPIWrapper::WorkerThread <-\n");
+    }
+}
+
+
+TUint32 KhronosAPIWrapper::GetWriteCount()
+{
+    TRACE("KhronosAPIWrapper::GetWriteCount()\n");
+    return InputBufferWriteCount();
+}
+
+
+void KhronosAPIWrapper::IncrementReadCount( TUint32 aReadCount )
+{
+    TRACE("KhronosAPIWrapper::IncrementReadCount()\n");
+    IncrementInputBufferReadCount( aReadCount );
+}
+
+
+TUint32 KhronosAPIWrapper::GetReadCount()
+{
+    TRACE("KhronosAPIWrapper::GetReadCount()\n");
+    return InputBufferReadCount();
+}
+
+
+TUint32 KhronosAPIWrapper::BufferTail()
+{
+    TRACE("KhronosAPIWrapper::BufferTail()\n");
+    return InputBufferTail();
+}
+
+
+void KhronosAPIWrapper::SetBufferTail( TUint32 aIndex )
+{
+    TRACE("KhronosAPIWrapper::SetBufferTail()\n");
+    SetInputBufferTail( aIndex );
+}
+
+
+TUint32 KhronosAPIWrapper::BufferHead()
+{
+    TRACE("KhronosAPIWrapper::BufferHead()\n");
+    return InputBufferHead();
+}
+
+
+TUint32 KhronosAPIWrapper::MaxTailIndex()
+{
+    TRACE("KhronosAPIWrapper::MaxTailIndex()\n");
+    return InputMaxTailIndex();
+}
+
+
+void KhronosAPIWrapper::SetMaxTailIndex( TUint32 aIndex )
+{
+    TRACE("KhronosAPIWrapper::SetMaxTailIndex()\n");
+    SetInputMaxTailIndex( aIndex );
+}
+
+
+TUint32 KhronosAPIWrapper::InputMaxTailIndex()
+{
+    TRACE("KhronosAPIWrapper::InputMaxTailIndex()\n");
+    TUint32 ret = m_InputBufferMaxTailIndex;
+    return ret;
+}
+
+
+void KhronosAPIWrapper::SetInputMaxTailIndex( TUint32 aIndex )
+{
+    TRACE("KhronosAPIWrapper::SetInputMaxTailIndex aIndex %u\n", aIndex );
+    m_InputBufferMaxTailIndex = aIndex;
+}
+
+
+void KhronosAPIWrapper::SetInputBufferTail(uint32_t p_val)
+{
+    TRACE("KhronosAPIWrapper::SetInputBufferTail aIndex %u\n", p_val );
+    m_InputBufferTail = p_val;
+}
+
+
+uint32_t KhronosAPIWrapper::InputBufferTail()
+{
+    uint32_t val = m_InputBufferTail;
+    TRACE("KhronosAPIWrapper::InputBufferTail %u\n", val );
+    return val;
+}
+
+
+void KhronosAPIWrapper::SetInputBufferHead(uint32_t p_val)
+{
+    TRACE("KhronosAPIWrapper::SetInputBufferHead aIndex %u\n", p_val );
+    m_InputBufferHead = p_val;
+}
+
+
+uint32_t KhronosAPIWrapper::InputBufferHead()
+{
+    uint32_t val = m_InputBufferHead;
+    TRACE("KhronosAPIWrapper::InputBufferHead %u\n", val );
+    return val;
+}
+
+
+void KhronosAPIWrapper::SetInputBufferReadCount(uint32_t p_val)
+{
+    TRACE("KhronosAPIWrapper::SetInputBufferReadCount aIndex %u\n", p_val );
+    m_InputBufferReadCount = p_val;
+}
+
+
+void KhronosAPIWrapper::IncrementInputBufferReadCount( TUint32 aReadCount )
+{
+    TRACE("KhronosAPIWrapper::IncrementInputBufferReadCount m_InputBufferReadCount++ %u\n", m_InputBufferReadCount );
+    m_InputBufferReadCount += aReadCount;
+}
+
+
+uint32_t KhronosAPIWrapper::InputBufferReadCount()
+{
+    uint32_t val = m_InputBufferReadCount;
+    TRACE("KhronosAPIWrapper::InputBufferReadCount %u\n", val );
+    return val;
+}
+
+
+void KhronosAPIWrapper::SetInputBufferWriteCount(uint32_t p_val)
+{
+    TRACE("KhronosAPIWrapper::SetInputBufferWriteCount	%u\n", p_val );
+    m_InputbufferWriteCount = p_val;
+}
+
+
+uint32_t KhronosAPIWrapper::InputBufferWriteCount()
+{
+    uint32_t val = m_InputbufferWriteCount;
+    TRACE("KhronosAPIWrapper::InputBufferWriteCount %u\n", val );
+    return val;
+}
+
+
+KhronosAPIWrapper::KhronosAPIWrapper( MGraphicsVHWCallback* aServiceIf, void* surfacebuffer, void* inputdata, void* outputdata )
+{
+    TRACE("KhronosAPIWrapper::KhronosAPIWrapper()\n");
+	m_lastVgError = VG_NO_ERROR;
+	m_lastEglError = EGL_SUCCESS;
+
+	m_lastProcessId = 0;
+	m_lastThreadId = 0;
+    m_currentInput = inputdata;
+    m_currentResult = outputdata;
+    m_surfaceBuffer = surfacebuffer;
+    m_exit = false;
+    iServiceIf = aServiceIf;
+    m_initDone = false;
+	iRFCData = new RemoteFunctionCallData;
+    m_InputRequestBuffer = new RequestBufferReader( *this, VVI_PARAMETERS_INPUT_MEMORY_SIZE );
+
+	Psu::platform_create_semaphore(m_SemapHandle, 0, 1000000);
+
+    Psu::platform_mutex_init( &m_InputBufferMutex );
+    m_InputBufferTail = 0;
+    m_InputBufferHead = 0;
+    m_InputBufferReadCount = 0;
+    m_InputbufferWriteCount = 0;
+
+    iStack = new APIWrapperStack();
+    iStack->InitStack( KMaxStackSize );
+
+	m_OpenVGWrapper = new OpenVGAPIWrapper( *iRFCData, iStack, m_currentResult, iServiceIf, this );
+	m_OGLESWrapper = new OGLES11Wrapper(*iRFCData, iStack, m_currentResult, iServiceIf);
+	m_EGLWrapper = new EGLAPIWrapper( *iRFCData, iStack, m_currentResult, iServiceIf, m_surfaceBuffer, this );
+	m_DriverAPIWrapper = new DriverAPIWrapper( *iRFCData, iStack, m_currentResult, iServiceIf, this );
+
+#ifdef KHRONOS_API_W_MULTITHREAD
+    int result = Psu::platform_create_simple_thread(&m_threadHandle,
+        &WorkerThreadFunction, this);
+    if (result)
+    {
+//Error
+    }
+#endif
+}
+
+KhronosAPIWrapper::~KhronosAPIWrapper()
+{
+    TRACE("KhronosAPIWrapper::~KhronosAPIWrapper\n");
+    m_exit = true;
+    Psu::platform_signal_semaphore(m_SemapHandle);
+    Psu::platform_join_thread(m_threadHandle);
+    Psu::platform_release_semaphore(m_SemapHandle);
+    Psu::platform_mutex_destroy( &m_InputBufferMutex );
+    delete iStack; iStack = NULL;
+	delete m_InputRequestBuffer; m_InputRequestBuffer = NULL;
+	delete m_OpenVGWrapper; m_OpenVGWrapper = NULL;
+	delete m_EGLWrapper; m_EGLWrapper = NULL;
+	delete m_DriverAPIWrapper; m_DriverAPIWrapper = NULL;
+	delete m_OGLESWrapper; m_OGLESWrapper = NULL;
+	delete iRFCData; iRFCData = NULL;
+}
+
+
+unsigned long KhronosAPIWrapper::InputParameterOffset()
+{
+    TRACE("KhronosAPIWrapper::InputParameterOffset()\n");
+    return 0;
+}
+
+
+unsigned long KhronosAPIWrapper::Execute()
+{
+    TRACE("KhronosAPIWrapper::Execute\n");
+    TInt ret(0);
+
+#ifdef KHRONOS_API_W_MULTITHREAD
+    Psu::platform_signal_semaphore(m_SemapHandle);
+#else
+    while ( m_InputRequestBuffer->IsDataAvailable() )
+    {
+        HandleNextRequest();
+    }
+#endif
+
+    return ret;
+}
+
+
+#ifdef WIN32
+
+BOOL APIENTRY DllMain( HMODULE hModule,
+DWORD  ul_reason_for_call,
+LPVOID lpReserved
+)
+{
+    switch (ul_reason_for_call)
+    {
+        case DLL_PROCESS_ATTACH:
+        case DLL_THREAD_ATTACH:
+        case DLL_THREAD_DETACH:
+        case DLL_PROCESS_DETACH:
+            break;
+    }
+    return true;
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/src/apiwrapper.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,62 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN                       // Exclude rarely-used stuff from Windows headers
+#include <windows.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <EGL/egl.h>
+#include "serializedfunctioncall.h"
+#include "remotefunctioncall.h"
+#include "apiwrapper.h"
+#include "graphicsvhwcallback.h"        //callback interface Wrapper=>Virtual HW
+#include "khronosapiwrapperdefs.h"
+
+APIWrapper::~APIWrapper()
+{
+}
+/*
+void APIWrapper::SetCurrentRFC( RemoteFunctionCallData* currentFunctionCall )
+{
+	m_currentFunctionCallData = currentFunctionCall;
+}*/
+
+APIWrapper::APIWrapper( RemoteFunctionCallData& currentFunctionCall, 
+	APIWrapperStack* stack,
+    void* result,
+	MGraphicsVHWCallback* serviceIf):
+m_currentFunctionCallData( currentFunctionCall ),
+m_currentResult( result ),
+iStack( stack ),
+iServiceIf( serviceIf )
+{
+}
+
+int APIWrapper::WriteReply()
+{
+	int ret( 0 );
+	if ( RemoteFunctionCallData::EOpRequestWithReply == m_currentFunctionCallData.Header().iOpType )
+	{
+		TRACE("APIWrapper::WriteReply() retval finally:%d\n", m_currentFunctionCallData.Header().iReturnValue );
+		m_currentFunctionCallData.SetOperationType( RemoteFunctionCallData::EOpReply );
+		iServiceIf->LockOutputBuffer();
+		SerializedFunctionCall sfc( m_currentFunctionCallData );
+		ret = sfc.WriteToBuffer( (TUint8*)m_currentResult, VVI_PARAMETERS_OUTPUT_MEMORY_SIZE );
+	}
+	return ret;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/src/driverapiwrapper.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,400 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <EGL/egl.h>//EGL operations will be called a lot from here
+#include <vg/openvg.h>
+
+#include "driverapiwrapper.h"
+#include "KhronosAPIWrapper.h"
+
+
+bool DriverAPIWrapper::IsSgBackingVGImage( VGImage aImage )
+	{
+		for( std::list<VGImage>::iterator cur = m_SgImageVGImages.begin();
+			 cur != m_SgImageVGImages.end();
+			 ++cur )
+		{
+			if( (*cur) == aImage )
+			{
+				return true;
+			}
+		}
+		return false;
+	}
+
+bool DriverAPIWrapper::IsSgBackingPBuffer( EGLSurface aSurface )
+	{
+		for( std::list<EGLSurface>::iterator cur = m_SgImagePbuffers.begin();
+			 cur != m_SgImagePbuffers.end();
+			 ++cur )
+		{
+			if( (*cur) == aSurface )
+			{
+				return true;
+			}
+		}
+		return false;
+	}
+
+int DriverAPIWrapper::CreatePoolContext()
+	{
+	//Initialize EGL on the first run, as per 5.1 in the "Implementing SgImage" design doc
+	if( m_initialized ){ return 0; }
+	TRACE("DriverAPIWrapper::CreatePoolContext() ->\n");
+    EGLDisplay display(0);
+
+    EGLConfig config(0);
+	EGLint num_config;
+
+	EGLContext PoolContext(0);//for sharing
+    EGLContext ContextWithFormatARGB_8888_PRE(0);//for sharing
+    EGLContext ContextWithFormatARGB_8888(0);
+    EGLContext ContextWithFormatXRGB_8888(0);
+    EGLContext ContextWithFormatRGB_565(0);
+    EGLContext ContextWithFormatA_8(0);
+    EGLSurface DudSurface(0);
+
+	int red(0);
+	int green(0);
+	int blue(0);
+	int alpha(0);
+    
+	display = ::eglGetDisplay( EGL_DEFAULT_DISPLAY );//Notice: there is no support for multiple displays here
+
+	if( !::eglInitialize(display, NULL, NULL) )
+	{
+		TRACE("DriverAPIWrapper::CreatePoolContext() <- (eglInitialize failed)\n");
+		return 0;
+	}
+
+	m_Dpy = display;
+	//Pool Context
+    //get a Configuration, then get the context
+	if( ::eglChooseConfig(	display,
+							getColorAttributes( EUidPixelFormatARGB_8888, red, green, blue, alpha ),
+							&config,
+							1,
+							&num_config ) == EGL_TRUE )
+	{
+		/* create an EGL rendering context */
+		PoolContext = ContextWithFormatARGB_8888 = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
+		m_PoolConfig = config;
+	}
+
+
+    /* get an appropriate EGL surface buffer configuration */
+	if( ::eglChooseConfig(	display,
+							getColorAttributes( EUidPixelFormatXRGB_8888, red, green, blue, alpha ),
+							&config,
+							1,
+							&num_config ) == EGL_TRUE )
+	{
+		/* create an EGL rendering context */
+		PoolContext = ContextWithFormatXRGB_8888 = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
+	}
+
+
+    //get a Configuration, then get the context
+	if( ::eglChooseConfig(	display,
+							getColorAttributes( EUidPixelFormatARGB_8888_PRE, red, green, blue, alpha ),
+							&config,
+							1,
+							&num_config ) == EGL_TRUE )
+	{
+		/* create an EGL rendering context */
+		ContextWithFormatARGB_8888_PRE = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
+	}
+	
+
+    //get a Configuration, then get the context
+	if( ::eglChooseConfig(	display,
+							getColorAttributes( EUidPixelFormatRGB_565, red, green, blue, alpha ),
+							&config,
+							1,
+							&num_config ) == EGL_TRUE )
+	{
+		/* create an EGL rendering context */
+		ContextWithFormatRGB_565 = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
+	}
+	
+
+    //get a Configuration, then get the context
+	if( ::eglChooseConfig(	display,
+							getColorAttributes( EUidPixelFormatA_8, red, green, blue, alpha ),
+							&config,
+							1,
+							&num_config ) == EGL_TRUE )
+	{
+		/* create an EGL rendering context */
+		ContextWithFormatA_8 = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
+	}
+
+
+	EGLint attribs[] = { EGL_NONE };
+	DudSurface = ::eglCreatePbufferSurface( display, PoolContext, attribs );
+
+
+	TRACE( "PoolContext = %u\n", PoolContext );
+	TRACE( "ContextWithFormatARGB_8888_PRE = %u\n", ContextWithFormatARGB_8888_PRE );
+	TRACE( "ContextWithFormatARGB_8888 = %u\n", ContextWithFormatARGB_8888 );
+	TRACE( "ContextWithFormatXRGB_8888 = %u\n", ContextWithFormatXRGB_8888 );
+	TRACE( "ContextWithFormatRGB_565 = %u\n", ContextWithFormatRGB_565 );
+	TRACE( "ContextWithFormatA_8 = %u\n", ContextWithFormatA_8 );
+	TRACE( "DummySurface = %u\n", DudSurface );
+
+	m_Dpy								= display;
+	m_PoolContext						= PoolContext;
+    m_ContextWithFormatARGB_8888_PRE	= ContextWithFormatARGB_8888_PRE;
+    m_ContextWithFormatARGB_8888		= ContextWithFormatARGB_8888;
+    m_ContextWithFormatXRGB_8888		= ContextWithFormatXRGB_8888;
+    m_ContextWithFormatRGB_565			= ContextWithFormatRGB_565;
+    m_ContextWithFormatA_8				= ContextWithFormatA_8;
+    m_DudSurface						= DudSurface;
+
+	//m_currentFunctionCall.AppendEGLContext( PoolContext );//for sharing
+    //m_currentFunctionCall.AppendEGLContext( ContextWithFormatARGB_8888_PRE );//for sharing
+    //m_currentFunctionCall.AppendEGLContext( ContextWithFormatARGB_8888 );
+    //m_currentFunctionCall.AppendEGLContext( ContextWithFormatXRGB_8888 );
+    //m_currentFunctionCall.AppendEGLContext( ContextWithFormatRGB_565 );
+    //m_currentFunctionCall.AppendEGLContext( ContextWithFormatA_8 );
+	//m_currentFunctionCall.AppendEGLSurface( DudSurface );
+
+	TRACE("DriverAPIWrapper::CreatePoolContext() <-\n");
+	m_initialized = true;
+	return 1;
+	}
+
+
+
+
+/**
+* This code is supposed to create a pbuffer to back an sgImage
+* TODO: not tested at all
+*/
+int DriverAPIWrapper::CreatePbufferSg(  )
+	{
+	TRACE("DriverAPIWrapper::CreatePbufferSg ->\n");
+	EGLint w;
+	EGLint h;
+
+	if( !m_initialized )
+		{
+		CreatePoolContext();
+		}
+	
+	m_currentFunctionCall.GetEGLint( w, 0 );
+	m_currentFunctionCall.GetEGLint( h, 1 );
+
+	//eglCreatePbufferSurface
+	EGLint pbuffer_surface_attribs[] =
+	{
+      EGL_WIDTH,    w,
+	  EGL_HEIGHT,   h,
+      EGL_NONE
+	};
+	
+    EGLSurface surface = ::eglCreatePbufferSurface( m_Dpy, m_PoolConfig, pbuffer_surface_attribs );
+	if( surface != EGL_NO_SURFACE )
+	{
+		m_SgImagePbuffers.push_back( surface );
+	}
+	TRACE("DriverAPIWrapper::CreatePbufferSg surface=%u \n", surface );
+    m_currentFunctionCall.SetReturnValue( (TUint32)surface );
+    TRACE("DriverAPIWrapper::CreatePbufferSg <-\n");
+    return WriteReply();
+	}
+
+
+/**
+* This code is supposed to create a pbuffer to back an sgImage
+* TODO: not tested at all
+*/
+int DriverAPIWrapper::CreateVGImageSg(  )
+	{
+	TRACE("DriverAPIWrapper::CreateVGImageSg ->\n");
+	EGLint w;
+	EGLint h;
+	EGLint pixelformat;
+	VGImage img;
+
+	if( !m_initialized )
+	{
+		CreatePoolContext();
+	}
+	
+	EGLenum previousApi = ::eglQueryAPI();
+	::eglBindAPI( EGL_OPENVG_API );
+
+	m_currentFunctionCall.GetEGLint( w, 0 );
+	m_currentFunctionCall.GetEGLint( h, 1 );
+	m_currentFunctionCall.GetEGLint( pixelformat, 2 );
+
+	::eglMakeCurrent( m_Dpy, m_DudSurface, m_DudSurface, m_PoolContext );
+
+	//eglCreatePbufferSurface
+	EGLint pbuffer_surface_attribs[] =
+	{
+      EGL_WIDTH,    w,
+	  EGL_HEIGHT,   h,
+      EGL_NONE
+	};
+	VGImageFormat format = getVGColorFormat( pixelformat );
+	img = ::vgCreateImage(format, w, h, VG_IMAGE_QUALITY_NONANTIALIASED);//todo: quality; how to decide (TSgImageInfo only provides w,h, pixelformat)?
+		if( img != VG_INVALID_HANDLE )
+	{
+		m_SgImageVGImages.push_back( img );
+	}
+
+    m_currentFunctionCall.SetReturnValue( (TUint32)img );
+	::eglBindAPI( previousApi );
+    TRACE("DriverAPIWrapper::CreateVGImageSg <-\n");
+    return WriteReply();
+	}
+
+int DriverAPIWrapper::DeleteSgImage()
+{
+	EGLSurface surface;
+	VGImage image;
+	m_currentFunctionCall.GetEGLSurface( surface, 0 );
+	m_currentFunctionCall.GetVGParamValue( image, 1 );
+
+	eglDestroySurface( m_Dpy, surface );
+	vgDestroyImage( image );
+
+	return WriteReply();
+}
+
+void DriverAPIWrapper::SyncVGImageFromPBuffer( EGLSurface aPbuffer, VGImage aVGImage )
+{
+	TRACE("DriverAPIWrapper::SyncVGImageFromPBuffer ->\n");
+	//Store the previous current
+	EGLDisplay disp = ::eglGetCurrentDisplay();
+	EGLSurface draw = ::eglGetCurrentSurface( EGL_DRAW );
+	EGLSurface read = ::eglGetCurrentSurface( EGL_READ );
+	EGLContext ctx  = ::eglGetCurrentContext();
+
+	EGLint width(0);
+	EGLint height(0);
+	eglSurfaceAttrib( disp, aPbuffer, EGL_WIDTH, width );
+	eglSurfaceAttrib( disp, aPbuffer, EGL_HEIGHT, height );
+
+	::eglMakeCurrent( m_Dpy, aPbuffer, aPbuffer, m_PoolContext );
+	::vgGetPixels( aVGImage, 0, 0, 0, 0, width, height );
+	//Set the previous current
+	::eglMakeCurrent( disp, draw, read, ctx );
+	TRACE("DriverAPIWrapper::SyncVGImageFromPBuffer <-\n");
+}
+
+
+int DriverAPIWrapper::SyncPBufferFromVGImage( VGImage aSrc, VGint aWidth, VGint aHeight )
+{
+	TRACE("DriverAPIWrapper::SyncPBufferFromVGImage ->\n");
+	if( ((VGboolean)vgGeti( VG_SCISSORING )) == VG_TRUE )
+	{
+		::vgSeti( VG_SCISSORING, VG_FALSE );
+		//The surface is the same size, as the vgimage
+		::vgSetPixels( 0, 0, aSrc, 0, 0, aWidth, aHeight );
+		::vgSeti( VG_SCISSORING, VG_TRUE );
+	}
+	else
+	{
+		::vgSetPixels( 0, 0, aSrc, 0, 0, aWidth, aHeight );
+	}
+	TRACE("DriverAPIWrapper::SyncPBufferFromVGImage <-\n");
+	return 0;
+}
+
+
+VGImageFormat DriverAPIWrapper::getVGColorFormat( int aPixelFormat )
+{
+	switch( aPixelFormat )
+		{
+		case  EUidPixelFormatXRGB_8888:
+			{
+			return VG_sXRGB_8888;
+			}
+		case EUidPixelFormatARGB_8888:
+			{
+			return VG_sARGB_8888;
+			}
+		case EUidPixelFormatARGB_8888_PRE:
+			{
+			return VG_sARGB_8888_PRE;
+			}
+		case EUidPixelFormatRGB_565:
+			{
+			return VG_sRGB_565;
+			}
+		case EUidPixelFormatA_8:
+			{
+			return VG_A_8;
+			}
+		default:
+			{
+			return VG_sARGB_8888;
+			}
+		}
+}
+
+EGLint* DriverAPIWrapper::getColorAttributes( int aPixelFormat, int& aRed, int& aGreen, int& aBlue, int& aAlpha )
+	{
+	switch( aPixelFormat )
+		{
+		case  EUidPixelFormatXRGB_8888:
+			{
+			aRed = aGreen = aBlue = aAlpha = 8;
+			break;
+			}
+		case EUidPixelFormatARGB_8888:
+			{
+			aRed = aGreen = aBlue = aAlpha = 8;
+			break;
+			}
+		case EUidPixelFormatARGB_8888_PRE:
+			{
+			aRed = aGreen = aBlue = aAlpha = 8;
+			break;
+			}
+		case EUidPixelFormatRGB_565:
+			{
+			aRed = 5; aGreen = 6; aBlue = 5; aAlpha = 0;
+			break;
+			}
+		case EUidPixelFormatA_8:
+			{
+			aRed = aGreen = aBlue = 0; aAlpha = 8;
+			break;
+			}
+		default:
+			{
+			aRed = aGreen = aBlue = aAlpha = 0;
+			break;
+			}
+		}
+		static EGLint attribs[] =
+		{
+		  EGL_RED_SIZE,   aRed,
+		  EGL_GREEN_SIZE, aGreen,
+		  EGL_BLUE_SIZE,  aBlue,
+		  EGL_ALPHA_SIZE, aAlpha,
+	      EGL_RENDERABLE_TYPE, EGL_OPENVG_BIT,
+		  EGL_SURFACE_TYPE,   EGL_PBUFFER_BIT,
+		  EGL_NONE
+		};
+	return attribs;
+	}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/src/eglapiwrapper.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,1281 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN                       // Exclude rarely-used stuff from Windows headers
+#include <windows.h>
+#endif
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <EGL/egl.h>
+#include "eglapiwrapper.h"
+#include "serializedfunctioncall.h"
+#include "remotefunctioncall.h"
+#include "khronosapiwrapperdefs.h"
+#include "KhronosAPIWrapper.h"
+#include "DriverAPIWrapper.h"
+
+
+EGLAPIWrapper::EGLAPIWrapper( RemoteFunctionCallData& currentFunctionCallData, 
+	APIWrapperStack* stack, 
+	void* result, 
+	MGraphicsVHWCallback* serviceIf, 
+	void* surfacebuffer,
+	KhronosAPIWrapper* aAPIWrapper ):
+	APIWrapper( currentFunctionCallData, stack, result, serviceIf ),
+	m_currentFunctionCall( m_currentFunctionCallData ),
+	m_surfaceBuffer( surfacebuffer ),
+	m_APIWrapper( aAPIWrapper )
+{
+    TRACE("EGLAPIWrapper::EGLAPIWrapper()\n");
+}
+
+void EGLAPIWrapper::SetProcessInformation( TUint32 aProcess, TUint32 aThread )
+{
+    TRACE("EGLAPIWrapper::SetProcessInformation()\n");
+	::eglPlatsimSetProcessInformation( aProcess, aThread );
+}
+
+void EGLAPIWrapper::Cleanup( TUint32 aProcess, TUint32 aThread )
+{
+    TRACE("EGLAPIWrapper::Cleanup()\n");
+	::eglPlatsimSetProcessInformation( aProcess, aThread );
+	::eglReleaseThread();
+}
+
+int EGLAPIWrapper::WriteReply()
+{
+    TRACE("EGLAPIWrapper::WriteReply()\n");
+#ifdef LOG_ERROR
+	int operationid = (int)m_currentFunctionCall.Data().Header().iOpCode;
+	int eglerror = ::eglPlatsimGetError();
+	if ( m_lastEglError != eglerror )
+	{
+		if ( EGL_SUCCESS != eglerror )
+			{
+			TRACE("EGL error 0x%X, for request %d\n", eglerror, operationid );
+			}
+		m_lastEglError = eglerror;
+	}
+#endif
+	return APIWrapper::WriteReply();
+}
+
+int EGLAPIWrapper::eglGetError()
+{
+    TRACE("EGLAPIWrapper::eglGetError()\n");
+    EGLint error = ::eglGetError();
+    m_currentFunctionCall.SetReturnValue( error );
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglGetDisplay()
+{
+    TRACE("EGLAPIWrapper::eglGetDisplay() ->\n");
+    EGLNativeDisplayType display_id;
+    m_currentFunctionCall.GetEGLNativeDisplayType( display_id, 0 );
+    /*EGLint display*/EGLDisplay display = ::eglGetDisplay( display_id );
+    m_currentFunctionCall.SetReturnValue( (TUint32)display );
+    TRACE("EGLAPIWrapper::eglGetDisplay() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglInitialize()
+{
+    TRACE("EGLAPIWrapper::eglInitialize() ->\n");
+    EGLDisplay dpy;
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    // The major and minor version numbers are set from the host side
+    EGLBoolean ret = ::eglInitialize( dpy, NULL, NULL);
+    m_currentFunctionCall.SetReturnValue(ret);
+    TRACE("EGLAPIWrapper::eglInitialize() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglTerminate()
+{
+    TRACE("EGLAPIWrapper::eglTerminate ->()\n");
+    EGLDisplay dpy;
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    EGLBoolean result = ::eglTerminate( dpy );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglTerminate <-()\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglQueryString()
+{
+    TRACE("EGLAPIWrapper::eglQueryString() ->\n");
+    EGLDisplay dpy;
+    EGLint name;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLint( name, 1 );
+    const char* result = ::eglQueryString( dpy, name );
+    m_currentFunctionCall.SetReturnValue( result ? 1 : 0 );
+    TRACE("EGLAPIWrapper::eglQueryString() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglGetConfigs()
+{
+    TRACE("EGLAPIWrapper::eglGetConfigs() ->\n");
+    EGLDisplay dpy;
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+
+    EGLint num_config = 0;
+    EGLint config_size = 0;
+    EGLint config_limit = 0;
+    EGLConfig* configs = 0;
+    EGLint* num_config_data = 0;
+    EGLint num_config_size = 0;
+
+    m_currentFunctionCall.GetEGLConfigVectorData( configs, config_size, 1 );
+    if ( config_size )
+    {
+        configs = (EGLConfig*)iStack->AllocFromStack( config_size*m_currentFunctionCall.GetTypeSize( EglRFC::EEGLConfig),
+            m_currentFunctionCall.GetTypeAlignment( EglRFC::EEGLConfig) );
+    }
+    m_currentFunctionCall.GetEGLint( config_limit, 2 );
+    m_currentFunctionCall.GetEGLintVectorData( num_config_data, num_config_size, 3 );
+    EGLBoolean result = ::eglGetConfigs( dpy, configs, config_limit, num_config_size ? &num_config : NULL);
+    
+    if(configs)
+    {
+        m_currentFunctionCall.SetEGLConfigVectorData( configs, config_limit, 1 );
+    }
+    if (num_config_size)
+    {
+        if (config_size && num_config > config_limit)
+            num_config = config_limit;
+        m_currentFunctionCall.SetEGLintVectorData( &num_config, 1, 3 );
+    }
+
+    m_currentFunctionCall.SetReturnValue( result );
+    int reply = WriteReply();
+
+    iStack->ClearStack();
+    configs = NULL;
+    TRACE("EGLAPIWrapper::eglGetConfigs() <-\n");
+    return reply;
+}
+
+
+int EGLAPIWrapper::eglChooseConfig()
+{
+    TRACE("EGLAPIWrapper::eglChooseConfig() ->\n");
+    EGLDisplay dpy;
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+
+    EGLint num_config = 0;
+    EGLint config_size = 0;
+    EGLint config_limit = 0;
+    EGLConfig* configs = 0;
+    EGLint* attribs = 0;
+    EGLint attrib_size = 0;
+    EGLint* num_config_data = 0;
+    EGLint num_config_size = 0;
+
+    m_currentFunctionCall.GetEGLintVectorData( attribs, attrib_size, 1 );
+    m_currentFunctionCall.GetEGLConfigVectorData( configs, config_size, 2 );
+    if ( config_size )
+    {
+        configs = (EGLConfig*)iStack->AllocFromStack( config_size*m_currentFunctionCall.GetTypeSize( EglRFC::EEGLConfig),
+            m_currentFunctionCall.GetTypeAlignment( EglRFC::EEGLConfig) );
+    }
+    m_currentFunctionCall.GetEGLint( config_limit, 3 );
+    m_currentFunctionCall.GetEGLintVectorData( num_config_data, num_config_size, 4 );
+    EGLBoolean result = ::eglChooseConfig( dpy, attribs, configs, config_limit, num_config_size ? &num_config : NULL );
+    if(configs)
+    {
+        m_currentFunctionCall.SetEGLConfigVectorData( configs, config_limit, 2 );
+    }
+    if (num_config_size)
+    {
+        if (config_size && num_config > config_limit)
+            num_config = config_limit;
+        m_currentFunctionCall.SetEGLintVectorData( &num_config, 1, 4 );
+    }
+
+    m_currentFunctionCall.SetReturnValue( result );
+    int reply = WriteReply();
+
+    iStack->ClearStack();
+    configs = NULL;
+    TRACE("EGLAPIWrapper::eglChooseConfig() <-\n");
+    return reply;
+}
+
+
+int EGLAPIWrapper::eglGetConfigAttrib()
+{
+    TRACE("EGLAPIWrapper::eglGetConfigAttrib() ->\n");
+    EGLDisplay dpy;
+    EGLConfig config;
+    EGLint attrib;
+    EGLint value = 0;
+    EGLint* value_data;
+    EGLint value_size;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLConfig( config, 1 );
+    m_currentFunctionCall.GetEGLint( attrib, 2 );
+    m_currentFunctionCall.GetEGLintVectorData( value_data, value_size, 3 );
+    EGLBoolean result = ::eglGetConfigAttrib( dpy, config, attrib, value_size ? &value : NULL);
+    
+	if (value_size)
+	{
+        m_currentFunctionCall.SetEGLintVectorData( &value, 1, 3 );
+	}
+
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglGetConfigAttrib() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglCreateWindowSurface()
+{
+    TRACE("EGLAPIWrapper::eglCreateWindowSurface() ->\n");
+    EGLDisplay dpy;
+    EGLConfig config;
+    EGLNativeWindowType window;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLConfig( config, 1 );
+    m_currentFunctionCall.GetEGLNativeWindowType( window, 2 );
+
+    EGLint* attribs;
+    EGLint attrib_size;
+
+    m_currentFunctionCall.GetEGLintVectorData( attribs, attrib_size, 3 );
+
+	int width;
+	int height;
+	int horizontalPitch;
+    int verticalPitch;
+	m_currentFunctionCall.GetEGLint( width, 4);
+	m_currentFunctionCall.GetEGLint( height, 5);
+	m_currentFunctionCall.GetEGLint( horizontalPitch, 6);
+	m_currentFunctionCall.GetEGLint( verticalPitch, 7);
+
+	SymbianWindow* nativeWindow = new SymbianWindow;
+	nativeWindow->id = (int)window;
+	nativeWindow->width = width;
+	nativeWindow->height = height;
+	nativeWindow->horizontalPitch = horizontalPitch;
+    nativeWindow->verticalPitch = verticalPitch;
+
+    EGLSurface surface = ::eglCreateWindowSurface( dpy, config, (EGLNativeWindowType)nativeWindow, attribs );
+
+	if ( EGL_NO_SURFACE != surface )
+	{
+		//Takes ownership of nativeWindow
+		//m_windowMap.insert( std::pair<std::pair<int,int>,SymbianWindow*>( std::pair<int,int>(dpy, surface), nativeWindow ) );
+		m_windowMap.insert( std::pair<TSurfaceKey,TSurfaceData>( TSurfaceKey((int)dpy, (int)surface, m_currentFunctionCall.Data().Header().iProcessId ), TSurfaceData( nativeWindow ) ) );
+	}
+	else
+	{
+		delete nativeWindow;
+	}
+
+    m_currentFunctionCall.SetReturnValue( (TUint32)surface );
+    TRACE("EGLAPIWrapper::eglCreateWindowSurface() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglCreatePbufferSurface()
+{
+    TRACE("EGLAPIWrapper::eglCreatePbufferSurface() ->\n");
+    EGLDisplay dpy;
+    EGLConfig config;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLConfig( config, 1 );
+
+    EGLint* attribs;
+    EGLint attrib_size;
+
+    m_currentFunctionCall.GetEGLintVectorData( attribs, attrib_size, 2 );
+
+    EGLSurface surface = ::eglCreatePbufferSurface( dpy, config, attribs );
+    m_currentFunctionCall.SetReturnValue( (TUint32)surface );
+    TRACE("EGLAPIWrapper::eglCreatePbufferSurface() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglCreatePixmapSurface()
+{
+    TRACE("EGLAPIWrapper::eglCreatePixmapSurface() ->\n");
+    EGLDisplay display;
+    EGLConfig config;
+    EGLNativePixmapType pixmap;
+    EGLint format;
+    EGLint width;
+    EGLint height;
+    EGLint stride;
+    EGLint pixmapType;
+
+	m_currentFunctionCall.GetEGLDisplay( display, 0 );
+    m_currentFunctionCall.GetEGLConfig( config, 1 );
+    m_currentFunctionCall.GetEGLNativePixmapType( pixmap, 2 );
+    m_currentFunctionCall.GetEGLint( format, 3 );
+    m_currentFunctionCall.GetEGLint( width, 4 );
+    m_currentFunctionCall.GetEGLint( height, 5 );
+    m_currentFunctionCall.GetEGLint( stride, 6 );
+    m_currentFunctionCall.GetEGLint( pixmapType, 7 );
+
+	SymbianPixmap* nativeBitmap = new SymbianPixmap;
+	nativeBitmap->data = new unsigned long[(stride*height+3)/4];
+	nativeBitmap->format = (TDisplayMode)format;
+	nativeBitmap->width = width;
+	nativeBitmap->height = height;
+	nativeBitmap->stride = stride;
+	nativeBitmap->type = pixmapType;
+
+    EGLint* attribs;
+    EGLint attrib_size;
+
+    m_currentFunctionCall.GetEGLintVectorData( attribs, attrib_size, 8 );
+
+	//Takes ownership of nativeBitmap 
+    EGLSurface surface = ::eglCreatePixmapSurface( display, config, (EGLNativePixmapType)nativeBitmap, attribs );
+    m_currentFunctionCall.SetReturnValue( (TUint32)surface );
+    TRACE("EGLAPIWrapper::eglCreatePixmapSurface() <-\n");
+	return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglDestroySurface()
+{
+    TRACE("EGLAPIWrapper::eglDestroySurface() ->\n");
+    EGLDisplay dpy;
+    EGLConfig surface;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLSurface( surface, 1 );
+
+    EGLBoolean result = ::eglDestroySurface( dpy, surface );
+
+	if ( result )
+	{
+		if ( EGL_NO_SURFACE != surface )
+		{
+			TSurfaceMap::iterator cur = m_windowMap.find( TSurfaceKey((int)dpy, (int)surface, m_currentFunctionCall.Data().Header().iProcessId ) );
+			if ( m_windowMap.end() != cur )
+			{
+				SymbianWindow* nativeWindow( cur->second.iWindow );
+				m_windowMap.erase(cur);
+				delete nativeWindow;
+			}
+		}
+	}
+
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglDestroySurface() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglQuerySurface()
+{
+    TRACE("EGLAPIWrapper::eglQuerySurface() ->\n");
+    EGLDisplay dpy;
+    EGLConfig surface;
+    EGLint attrib;
+    EGLint value = 0;
+    EGLint* value_data;
+    EGLint value_size;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLSurface( surface, 1 );
+    m_currentFunctionCall.GetEGLint( attrib, 2 );
+    m_currentFunctionCall.GetEGLintVectorData( value_data, value_size, 3 );
+    EGLBoolean result = ::eglQuerySurface( dpy, surface, attrib, value_size ? &value : NULL);
+    if (value_size)
+        m_currentFunctionCall.SetEGLintVectorData( &value, 1, 3 );
+
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglQuerySurface() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglBindAPI()
+{
+    TRACE("EGLAPIWrapper::eglBindAPI() ->\n");
+    EGLenum api;
+    m_currentFunctionCall.GetEGLenum( api, 0 );
+    EGLBoolean result = ::eglBindAPI( api );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglBindAPI() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglQueryAPI()
+{
+    TRACE("EGLAPIWrapper::eglQueryAPI() ->\n");
+    EGLenum result = ::eglQueryAPI();
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglQueryAPI() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglWaitClient()
+{
+    TRACE("EGLAPIWrapper::eglWaitClient() ->\n");
+    EGLBoolean result = ::eglWaitClient();
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglWaitClient() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglReleaseThread()
+{
+    TRACE("EGLAPIWrapper::eglReleaseThread() ->\n");
+    EGLBoolean result = ::eglReleaseThread();
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglReleaseThread() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglCreatePbufferFromClientBuffer()
+{
+    TRACE("EGLAPIWrapper::eglCreatePbufferFromClientBuffer() ->\n");
+    EGLDisplay dpy;
+    EGLenum buftype;
+    EGLClientBuffer buffer;
+    EGLConfig config;
+	
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLenum( buftype, 1 );
+    m_currentFunctionCall.GetEGLClientBuffer( buffer, 2 );
+    m_currentFunctionCall.GetEGLConfig( config, 3 );
+
+	if( buftype == EGL_OPENVG_IMAGE &&
+		m_APIWrapper->GetDriverWrapper()->IsSgBackingVGImage( (VGImage)buffer ) )
+	{
+		//TODO EGL_BAD_ADDRESS
+	}
+
+    EGLint* attribs;
+    EGLint attrib_size;
+
+    m_currentFunctionCall.GetEGLintVectorData( attribs, attrib_size, 4 );
+
+    EGLSurface surface = ::eglCreatePbufferFromClientBuffer( dpy, buftype, buffer, config, attribs );
+    m_currentFunctionCall.SetReturnValue( (TUint32)surface );
+    TRACE("EGLAPIWrapper::eglCreateBufferFromClientBuffer() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglSurfaceAttrib()
+{
+    TRACE("EGLAPIWrapper::eglSurfaceAttrib() ->\n");
+    EGLDisplay dpy;
+    EGLSurface surface;
+    EGLint attrib;
+    EGLint value;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLSurface( surface, 1 );
+    m_currentFunctionCall.GetEGLint( attrib, 2 );
+    m_currentFunctionCall.GetEGLint( value, 3 );
+
+    EGLBoolean result = ::eglSurfaceAttrib( dpy, surface, attrib, value );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglSurfaceAttrib() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglBindTexImage()
+{
+    TRACE("EGLAPIWrapper::eglBindTexImage() ->\n");
+    EGLDisplay dpy;
+    EGLSurface surface;
+    EGLint buffer;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLSurface( surface, 1 );
+    m_currentFunctionCall.GetEGLint( buffer, 2 );
+
+    EGLBoolean result = ::eglBindTexImage( dpy, surface, buffer );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglBindTexImage() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglReleaseTexImage()
+{
+    TRACE("EGLAPIWrapper::eglReleaseTexImage() ->\n");
+    EGLDisplay dpy;
+    EGLSurface surface;
+    EGLint buffer;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLSurface( surface, 1 );
+    m_currentFunctionCall.GetEGLint( buffer, 2 );
+
+    EGLBoolean result = ::eglReleaseTexImage( dpy, surface, buffer );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglReleaseTexImage() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglSwapInterval()
+{
+    TRACE("EGLAPIWrapper::eglSwapInterval() ->\n");
+    EGLDisplay dpy;
+    EGLint interval;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLint( interval, 1 );
+
+    EGLBoolean result = ::eglSwapInterval( dpy, interval );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglSwapInterval() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglCreateContext()
+{
+    TRACE("EGLAPIWrapper::eglCreateContext() ->\n");
+    EGLDisplay dpy;
+    EGLConfig config;
+    EGLContext share_context;
+	EGLBoolean sgSupporting(EGL_FALSE);
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLConfig( config, 1 );
+    m_currentFunctionCall.GetEGLContext( share_context, 2 );
+
+	if( share_context == EGL_NO_CONTEXT )
+	{
+		share_context = m_APIWrapper->GetDriverWrapper()->GetPoolContext();
+	}
+
+    EGLint* attribs;
+    EGLint attrib_size;
+
+    m_currentFunctionCall.GetEGLintVectorData( attribs, attrib_size, 3 );
+
+    EGLContext context = ::eglCreateContext( dpy, config, share_context, attribs );
+    m_currentFunctionCall.SetReturnValue( (TUint32)context );
+    TRACE("EGLAPIWrapper::eglCreateContext() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglDestroyContext()
+{
+    TRACE("EGLAPIWrapper::eglDestroyContext() ->\n");
+    EGLDisplay dpy;
+    EGLContext context;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLContext( context, 1 );
+
+    EGLBoolean result = ::eglDestroyContext( dpy, context );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglDestroyContext() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglMakeCurrent()
+{
+    TRACE("EGLAPIWrapper::eglMakeCurrent() ->\n");
+    EGLDisplay dpy;
+    EGLSurface draw;
+    EGLSurface read;
+    EGLContext context;
+	EGLint syncNeed(0);
+	EGLint src(0);
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLSurface( draw, 1 );
+    m_currentFunctionCall.GetEGLSurface( read, 2 );
+    m_currentFunctionCall.GetEGLContext( context, 3 );
+	if( m_currentFunctionCall.Data().Header().iParameterCount > 4 )
+	{
+		m_currentFunctionCall.GetEGLint( syncNeed, 4 );
+		m_currentFunctionCall.GetEGLint( src, 5 );
+	}
+
+	//Call eglMakeCurrent first
+	EGLBoolean result = ::eglMakeCurrent( dpy, draw, read, context );
+
+	//If the surface is "dirty", then it needs to be drawn the vgImage onto
+	if( syncNeed & KSyncReadSurface )
+	{
+		int width;
+		int height;
+		::eglQuerySurface(dpy, read, EGL_WIDTH, &width );
+		::eglQuerySurface(dpy, read, EGL_HEIGHT, &height );		
+		m_APIWrapper->GetDriverWrapper()->SyncPBufferFromVGImage( (int)src, width, height );
+	}
+	if( syncNeed & KSyncDrawSurface )
+	{
+		int width;
+		int height;
+		::eglQuerySurface(dpy, draw, EGL_WIDTH, &width );
+		::eglQuerySurface(dpy, draw, EGL_HEIGHT, &height );
+		m_APIWrapper->GetDriverWrapper()->SyncPBufferFromVGImage( (int)src, width, height );
+	}
+    
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglMakeCurrent() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglGetCurrentContext()
+{
+    TRACE("EGLAPIWrapper::eglGetCurrentContext() ->\n");
+    EGLContext context = ::eglGetCurrentContext();
+    m_currentFunctionCall.SetReturnValue( (TUint32)context );
+    TRACE("EGLAPIWrapper::eglGetCurrentContext() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglGetCurrentSurface()
+{
+    TRACE("EGLAPIWrapper::eglGetCurrentSurface() ->\n");
+    EGLint readdraw;
+
+    m_currentFunctionCall.GetEGLint( readdraw, 0 );
+
+    EGLSurface surface = ::eglGetCurrentSurface( readdraw );
+    m_currentFunctionCall.SetReturnValue( (TUint32)surface );
+    TRACE("EGLAPIWrapper::eglGetCurrentSurface() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglGetCurrentDisplay()
+{
+    TRACE("EGLAPIWrapper::eglGetCurrentDisplay() ->\n");
+    EGLDisplay display = ::eglGetCurrentDisplay();
+    m_currentFunctionCall.SetReturnValue( (TUint32)display );
+    TRACE("EGLAPIWrapper::eglGetCurrentDisplay() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglQueryContext()
+{
+    TRACE("EGLAPIWrapper::eglQueryContext() ->\n");
+    EGLDisplay dpy;
+    EGLContext context;
+    EGLint attrib;
+    EGLint value = 0;
+    EGLint* value_data;
+    EGLint value_size;
+
+    m_currentFunctionCall.GetEGLDisplay( dpy, 0 );
+    m_currentFunctionCall.GetEGLContext( context, 1 );
+    m_currentFunctionCall.GetEGLint( attrib, 2 );
+    m_currentFunctionCall.GetEGLintVectorData( value_data, value_size, 3 );
+    EGLBoolean result = ::eglQueryContext( dpy, context, attrib, value_size ? &value : NULL);
+    if (value_size)
+        m_currentFunctionCall.SetEGLintVectorData( &value, 1, 3 );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglQueryContext() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglWaitGL()
+{
+    TRACE("EGLAPIWrapper::eglWaitGL() ->\n");
+    EGLBoolean result = ::eglWaitGL();
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglWaitNative()
+{
+    TRACE("EGLAPIWrapper::eglWaitNative() ->\n");
+    EGLint engine;
+
+    m_currentFunctionCall.GetEGLint( engine, 0 );
+
+    EGLBoolean result = ::eglWaitNative( engine );
+    m_currentFunctionCall.SetReturnValue( result );
+    TRACE("EGLAPIWrapper::eglWaitNative() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglSwapBuffers()
+{
+    TRACE("EGLAPIWrapper::eglSwapBuffers() ->\n");
+    EGLDisplay display;
+    EGLSurface surface;
+	int width;
+	int height;
+    m_currentFunctionCall.GetEGLDisplay( display, 0 );
+    m_currentFunctionCall.GetEGLSurface( surface, 1 );
+    m_currentFunctionCall.GetEGLint( width, 2 );
+    m_currentFunctionCall.GetEGLint( height, 3 );
+	//TWindowMap::const_iterator cur  = m_windowMap.find(std::pair<int,int>( display, surface ));
+	TSurfaceMap::const_iterator cur  = m_windowMap.find(TSurfaceKey( (int)display, (int)surface, m_currentFunctionCall.Data().Header().iProcessId ));
+
+	//Only found for windows surfaces
+	if ( m_windowMap.end() != cur )
+	{
+		cur->second.iWindow->width = width;
+		cur->second.iWindow->height = height;
+	}
+
+    EGLBoolean result = ::eglSwapBuffers( display, surface );
+
+    m_currentFunctionCall.SetReturnValue( (TUint32)result );
+    TRACE("EGLAPIWrapper::eglSwapBuffers() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglCopyBuffers()
+{
+    TRACE("EGLAPIWrapper::eglCopyBuffers() ->\n");
+    EGLDisplay display(0);
+    EGLSurface surface(0);
+
+    m_currentFunctionCall.GetEGLDisplay( display, 0 );
+    m_currentFunctionCall.GetEGLSurface( surface, 1 );
+
+	void* data(NULL);
+    int size(0);
+    m_currentFunctionCall.GetVectorData( data, size, 2 );
+
+	SymbianPixmap* bitmap(NULL);
+	if ( size )
+	{
+		bitmap = (SymbianPixmap*)iStack->AllocFromStack( sizeof(SymbianPixmap),
+            m_currentFunctionCall.GetTypeAlignment( EglRFC::EEGLVoid ) );
+		bitmap->data = (unsigned long*)iStack->AllocFromStack( size,
+            m_currentFunctionCall.GetTypeAlignment( EglRFC::EEGLVoid ) );
+		EGLint format;
+		m_currentFunctionCall.GetEGLint( format, 3 );
+		bitmap->format = (TDisplayMode)format;
+		m_currentFunctionCall.GetEGLint( bitmap->width, 4 );
+		m_currentFunctionCall.GetEGLint( bitmap->height, 5 );
+		m_currentFunctionCall.GetEGLint( bitmap->stride, 6 );
+		m_currentFunctionCall.GetEGLint( bitmap->type, 7 );
+	}
+	else
+	{
+		data = NULL;
+	}
+	
+    EGLBoolean result = ::eglCopyBuffers( display, surface, (EGLNativePixmapType)bitmap );
+    
+	if ( result )
+		{
+		m_currentFunctionCall.SetVectorData( bitmap->data, size, 2 );
+		}
+
+    m_currentFunctionCall.SetReturnValue( result );
+	int ret = WriteReply();
+	iStack->ClearStack();
+	TRACE("EGLAPIWrapper::eglCopyBiffers() <-\n");
+    return ret;
+}
+
+
+int EGLAPIWrapper::eglPlatsimSetSurfaceParams()
+{
+    TRACE("EGLAPIWrapper::eglPlatsimSetSurfaceParams() ->\n");
+    EGLDisplay display;
+    EGLSurface surface;
+    EGLint width;
+    EGLint height;
+    EGLint stride;
+    EGLint buffer0Offset(0);
+    EGLint buffer1Offset(0);
+	NativeWindowType win(0);
+
+    m_currentFunctionCall.GetEGLDisplay( display, 0 );
+    m_currentFunctionCall.GetEGLSurface( surface, 1 );
+    m_currentFunctionCall.GetEGLNativeWindowType( win, 2 );
+    m_currentFunctionCall.GetEGLint( width, 3 );
+    m_currentFunctionCall.GetEGLint( height, 4 );
+    m_currentFunctionCall.GetEGLint( stride, 5 );
+    m_currentFunctionCall.GetEGLint( buffer0Offset, 6 );
+    m_currentFunctionCall.GetEGLint( buffer1Offset, 7 );
+
+    void* buffer0 = (void*)((EGLint)m_surfaceBuffer + buffer0Offset);
+    void* buffer1 = (void*)((EGLint)m_surfaceBuffer + buffer1Offset);
+
+	::eglPlatsimSetSurfaceParams(display, surface, width, height, stride, buffer0, buffer1);
+	m_currentFunctionCall.SetReturnValue( 0 );
+	TRACE("EGLAPIWrapper::eglPlatsimSetSurfaceParams() <-\n");
+    return WriteReply();
+}
+
+
+int EGLAPIWrapper::eglPlatsimCopyImageData()
+{
+    TRACE("EGLAPIWrapper::eglPlatsimCopyImageData() ->\n");
+    void* data(NULL);
+    int size(0);
+    m_currentFunctionCall.GetVectorData( data, size, 0 );
+
+	if ( size )
+		{
+		EGLDisplay display = ::eglGetCurrentDisplay();
+		EGLSurface surface = ::eglGetCurrentSurface(EGL_DRAW);
+		NativePixmapType nativePixmap = eglPlatsimGetPixmapSurfaceBitmap(display,surface);
+		SymbianPixmap* symbianBitmap = (SymbianPixmap*)nativePixmap;
+		if ( symbianBitmap )
+			{
+			m_currentFunctionCall.SetVectorData( symbianBitmap->data, size, 0 );
+			}
+		}	
+    TRACE("EGLAPIWrapper::eglPlatsimCopyImageData() <-\n");
+    return WriteReply();
+}
+
+int EGLAPIWrapper::eglPixmapSurfaceSizeChanged()
+{
+    TRACE("EGLAPIWrapper::eglPixmapSurfaceSizeChanged() ->\n");
+	EGLDisplay display;
+	m_currentFunctionCall.GetEGLDisplay( display, 0 );
+	EGLSurface surface;
+	m_currentFunctionCall.GetEGLSurface( surface, 1 );
+	NativePixmapType dtype;
+    m_currentFunctionCall.GetEGLNativePixmapType( dtype, 2);
+	EGLint format;
+	m_currentFunctionCall.GetEGLint( format, 3 );
+	EGLint width;
+    m_currentFunctionCall.GetEGLint( width, 4 );
+	EGLint height;
+    m_currentFunctionCall.GetEGLint( height, 5 );
+	EGLint stride;
+    m_currentFunctionCall.GetEGLint( stride, 6 );
+
+	NativePixmapType nativePixmap = eglPlatsimGetPixmapSurfaceBitmap(display,surface);
+	SymbianPixmap* symbianBitmap = (SymbianPixmap*)nativePixmap;
+	if ( symbianBitmap )
+	{
+		symbianBitmap->format = (TDisplayMode)format;
+		symbianBitmap->width = width;
+		symbianBitmap->height = height;
+		symbianBitmap->stride = stride;
+		delete [] symbianBitmap->data;
+		symbianBitmap->data = new unsigned long[(stride*height+3)/4];
+	}
+    TRACE("EGLAPIWrapper::eglPixmapSurfaceSizeChanged() <-\n");
+    return WriteReply();
+}
+
+int EGLAPIWrapper::eglMetaGetConfigs()
+{
+    TRACE("EGLAPIWrapper::eglMetaGetConfigs() ->\n");
+	bool abortOper = false;
+	int fetchMode(0);
+	m_currentFunctionCall.GetEGLint( fetchMode, 1 );//2nd parameter
+
+	EGLint* attributes;
+
+	EGLint red, green, blue, alpha;
+
+	//For storing the sg-compatible configs (for a single call to eglChooseConfig)
+	EGLConfig* sgConfigs = 0;
+	EGLint     sgConfigsSize = 0;//size of the array
+	EGLint     sgConfigsCnt = 0;//Number of actually received configurations
+
+	//The sgConfigs for returning them
+	EGLConfig* sgConfigsToReturn;
+	EGLint     sgConfigsToReturnCnt;
+	int        sgConfigsToReturnIndex = 0;
+
+	//For storing all the configs
+	EGLConfig*  allConfigs = 0;
+	EGLint      allConfigsSize = 0;//size of the array
+	EGLint      allConfigsCnt = 0;//Number of actually received configurations
+
+	//Allocate temporary storage for the attributes for each config
+	//This is actually obtained from the remote function call
+	EGLint* attributesForAllConfigs(0);
+	int     sizeAttributesForAllConfigs(0);
+	int     sizeAttributesForAllConfigsMax(0);
+
+
+	static EGLint SgPixelFormats[] =
+		{
+		EUidPixelFormatXRGB_8888,
+		EUidPixelFormatARGB_8888,
+		EUidPixelFormatARGB_8888_PRE,
+		EUidPixelFormatRGB_565,
+		EUidPixelFormatA_8
+		};
+
+	int sgPixelFormatsCnt = sizeof(SgPixelFormats)/sizeof(EGLint);
+
+	//This is for storing all the attributes. This struct's values will be queried from the configs
+	static EGLint configAttributes[] =
+	{
+		EGL_BUFFER_SIZE,
+		EGL_RED_SIZE,
+		EGL_GREEN_SIZE,
+		EGL_BLUE_SIZE,
+		EGL_LUMINANCE_SIZE,
+		EGL_ALPHA_SIZE,
+		EGL_ALPHA_MASK_SIZE,
+		EGL_BIND_TO_TEXTURE_RGB,
+		EGL_BIND_TO_TEXTURE_RGBA,
+		EGL_COLOR_BUFFER_TYPE,
+		EGL_CONFIG_CAVEAT,
+		EGL_CONFIG_ID,
+		EGL_CONFORMANT,
+		EGL_DEPTH_SIZE,
+		EGL_LEVEL,
+		EGL_MATCH_NATIVE_PIXMAP,
+		EGL_MAX_SWAP_INTERVAL,
+		EGL_MIN_SWAP_INTERVAL,
+		EGL_NATIVE_RENDERABLE,
+		EGL_NATIVE_VISUAL_TYPE,
+		EGL_RENDERABLE_TYPE,
+		EGL_SAMPLE_BUFFERS,
+		EGL_SAMPLES,
+		EGL_STENCIL_SIZE,
+		EGL_SURFACE_TYPE,
+		EGL_TRANSPARENT_TYPE,
+		EGL_TRANSPARENT_RED_VALUE,
+		EGL_TRANSPARENT_GREEN_VALUE,
+		EGL_TRANSPARENT_BLUE_VALUE
+	};
+	int cntConfigAttributes = sizeof(configAttributes) / sizeof(EGLint);
+
+	sizeAttributesForAllConfigsMax = cntConfigAttributes * KConfigsMaxCnt;
+	TRACE("\nEGLAPIWrapper::eglMetaGetConfigs get Vector datas\n" );
+	m_currentFunctionCall.GetEGLConfigVectorData( sgConfigsToReturn, sgConfigsToReturnCnt, 0 );
+	//m_currentFunctionCall.GetEGLConfigVectorData( attributesForAllConfigs, sizeAttributesForAllConfigs, 1 );
+    m_currentFunctionCall.GetEGLintVectorData( attributesForAllConfigs, sizeAttributesForAllConfigs, 1 );
+	TRACE("\nEGLAPIWrapper::eglMetaGetConfigs eglGetConfigs\n" );
+	//Get the total number of all the configs
+	::eglGetConfigs( m_APIWrapper->GetDriverWrapper()->getDisplay(), NULL, 0, &allConfigsCnt );
+	TRACE("\nEGLAPIWrapper::eglMetaGetConfigs all configs count=%d\n", allConfigsCnt );
+	ASSERT( allConfigsCnt <= KConfigsMaxCnt );
+
+    if ( sizeAttributesForAllConfigs <= sizeAttributesForAllConfigsMax )
+    {
+		attributesForAllConfigs = (EGLint*)iStack->AllocFromStack( sizeAttributesForAllConfigs*m_currentFunctionCall.GetTypeSize( EglRFC::EEGLint ),
+					m_currentFunctionCall.GetTypeAlignment( EglRFC::EEGLint ) );
+		//Allocate room for holding the configs
+		TRACE("\nEGLAPIWrapper::eglMetaGetConfigs attribs cnt = %d\n", cntConfigAttributes );			
+		switch( fetchMode )
+		{
+		case EMetaGetConfigsSg:
+			{
+			for( int i = 0; i < sgPixelFormatsCnt; ++i )//Go through all the pixel formats, fetching configs matching them
+			{
+				TRACE("\nEGLAPIWrapper::eglMetaGetConfigs sg pixel formats %d\n", i );
+				//This is for temporary storage. We are only interested in picking the attribute values for each configuration
+				sgConfigs = new EGLConfig[KConfigsMaxCnt];//(EGLConfig*)iStack->AllocFromStack( KConfigsMaxCnt*m_currentFunctionCall.GetTypeSize( EglRFC::EEGLConfig),
+							//m_currentFunctionCall.GetTypeAlignment( EglRFC::EEGLConfig) );
+				sgConfigsSize = KConfigsMaxCnt;
+				attributes = m_APIWrapper->GetDriverWrapper()->getColorAttributes( SgPixelFormats[i], red, green, blue, alpha );
+				if( ::eglChooseConfig(	m_APIWrapper->GetDriverWrapper()->getDisplay(), 
+										attributes,
+										sgConfigs,
+										sgConfigsSize,
+										&sgConfigsCnt ) )
+				{
+					//TRACE("\nEGLAPIWrapper::eglMetaGetConfigs sg configs cnt / size = %d / %d\n", sgConfigsCnt, sgConfigsSize );
+					sizeAttributesForAllConfigs = sgConfigsCnt * sizeof(EGLint) * cntConfigAttributes;
+					for( int config_i = 0; config_i < sgConfigsCnt; ++config_i )
+					{
+						*(sgConfigsToReturn + (sgConfigsToReturnIndex++)) = sgConfigs[config_i]; 
+						//Go through all the configs, recording the attributes
+						for( int attr_i = 0; attr_i < cntConfigAttributes; ++attr_i )
+						{
+							EGLint attribValue;
+							if( ::eglGetConfigAttrib( m_APIWrapper->GetDriverWrapper()->getDisplay(), sgConfigs[config_i], configAttributes[attr_i], &attribValue ) )
+							{
+								//                           #config                          #attribute
+								*( attributesForAllConfigs + config_i * cntConfigAttributes + attr_i ) = attribValue;
+								//TRACE("\nEGLAPIWrapper::eglMetaGetConfigs sg pixformat %d, config %d, attr %d = %d\n", i, config_i, attr_i, attribValue );
+							}
+							else
+							{
+								//Could not obtain the config attribute, now we are going to abort everything
+								goto ATTRIBUTESARRAYDELETE;
+							}
+						}//end for all attribs within a config
+					}//end for all configs returned
+ATTRIBUTESARRAYDELETE:
+					//We have not been able to populate the attributes list, just abort now
+					delete[] sgConfigs;
+					abortOper = true;
+				}//end if eglGetConfigs succeeded
+				else
+				{
+					//Problems: can't get the configs. Maybe just abort the whole business
+					abortOper = true;
+					break;
+				}
+			}//end for all pixel formats
+			break;
+			}//end case EMetaGetConfigsSg
+		}//end switch fetchMode
+	
+		if( !abortOper )
+		{
+			//Param 0:
+			TRACE("EGLAPIWrapper::eglMetaGetConfigs sgConfigsToReturnIndex = %d", sgConfigsToReturnIndex );
+			//m_currentFunctionCall.SetEGLintVectorData( sgConfigsToReturn, sgConfigsToReturnIndex+1, 0 );
+            m_currentFunctionCall.SetEGLConfigVectorData( sgConfigsToReturn, sgConfigsToReturnIndex+1, 0 );
+			TRACE("EGLAPIWrapper::eglMetaGetConfigs sizeAttributesForAllConfigs = %d", sizeAttributesForAllConfigs / sizeof( EGLint ) );
+			m_currentFunctionCall.SetEGLintVectorData( attributesForAllConfigs, sizeAttributesForAllConfigs / sizeof( EGLint ), 1 );
+		}
+	}//end if config_size >= KConfigsMaxCnt
+	else
+	{
+		abortOper = true;
+	}
+	m_currentFunctionCall.SetReturnValue( abortOper?EGL_FALSE:EGL_TRUE );
+    int reply = WriteReply();
+    iStack->ClearStack();
+    sgConfigs = NULL;
+	allConfigs = NULL;
+    TRACE("EGLAPIWrapper::eglGetConfigs() <-\n");
+    return reply;
+}
+
+int EGLAPIWrapper::DispatchRequest( unsigned long aCode )
+{
+    int ret(0);
+
+    switch ( aCode )
+    {        
+		case EglRFC::EeglGetError:
+        {
+            ret = eglGetError();
+            break;
+        }
+        case EglRFC::EeglGetDisplay:
+        {
+            ret = eglGetDisplay();
+            break;
+        }
+        case EglRFC::EeglInitialize:
+        {
+            ret = eglInitialize();
+            break;
+        }
+        case EglRFC::EeglTerminate:
+        {
+            ret = eglTerminate();
+            break;
+        }
+        case EglRFC::EeglQueryString:
+        {
+            ret = eglQueryString();
+            break;
+        }
+        case EglRFC::EeglGetConfigs:
+        {
+            ret = eglGetConfigs();
+            break;
+        }
+        case EglRFC::EeglChooseConfig:
+        {
+            ret = eglChooseConfig();
+            break;
+        }
+        case EglRFC::EeglGetConfigAttrib:
+        {
+            ret = eglGetConfigAttrib();
+            break;
+        }
+        case EglRFC::EeglCreateWindowSurface:
+        {
+            ret = eglCreateWindowSurface();
+            break;
+        }
+        case EglRFC::EeglCreatePbufferSurface:
+        {
+            ret = eglCreatePbufferSurface();
+            break;
+        }
+        case EglRFC::EeglCreatePixmapSurface:
+        {
+            ret = eglCreatePixmapSurface();
+            break;
+        }
+        case EglRFC::EeglDestroySurface:
+        {
+            ret = eglDestroySurface();
+            break;
+        }
+        case EglRFC::EeglQuerySurface:
+        {
+            ret = eglQuerySurface();
+            break;
+        }
+        case EglRFC::EeglBindAPI:
+        {
+            ret = eglBindAPI();
+            break;
+        }
+        case EglRFC::EeglQueryAPI:
+        {
+            ret = eglQueryAPI();
+            break;
+        }
+        case EglRFC::EeglWaitClient:
+        {
+            ret = eglWaitClient();
+            break;
+        }
+        case EglRFC::EeglReleaseThread:
+        {
+            ret = eglReleaseThread();
+            break;
+        }
+        case EglRFC::EeglCreatePbufferFromClientBuffer:
+        {
+            ret = eglCreatePbufferFromClientBuffer();
+            break;
+        }
+        case EglRFC::EeglSurfaceAttrib:
+        {
+            ret = eglSurfaceAttrib();
+            break;
+        }
+        case EglRFC::EeglBindTexImage:
+        {
+            ret = eglBindTexImage();
+            break;
+        }
+        case EglRFC::EeglReleaseTexImage:
+        {
+            ret = eglReleaseTexImage();
+            break;
+        }
+        case EglRFC::EeglSwapInterval:
+        {
+            ret = eglSwapInterval();
+            break;
+        }
+        case EglRFC::EeglCreateContext:
+        {
+            ret = eglCreateContext();
+            break;
+        }
+        case EglRFC::EeglDestroyContext:
+        {
+            ret = eglDestroyContext();
+            break;
+        }
+        case EglRFC::EeglMakeCurrent:
+        {
+            ret = eglMakeCurrent();
+            break;
+        }
+		case EglRFC::EeglMakeCurrentSg:
+		{
+			break;
+		}
+        case EglRFC::EeglGetCurrentContext:
+        {
+            ret = eglGetCurrentContext();
+            break;
+        }
+        case EglRFC::EeglGetCurrentSurface:
+        {
+            ret = eglGetCurrentSurface();
+            break;
+        }
+        case EglRFC::EeglGetCurrentDisplay:
+        {
+            ret = eglGetCurrentDisplay();
+            break;
+        }
+        case EglRFC::EeglQueryContext:
+        {
+            ret = eglQueryContext();
+            break;
+        }
+        case EglRFC::EeglWaitGL:
+        {
+            ret = eglWaitGL();
+            break;
+        }
+        case EglRFC::EeglWaitNative:
+        {
+            ret = eglWaitNative();
+            break;
+        }
+        case EglRFC::EeglSwapBuffers:
+        {
+            ret = eglSwapBuffers();
+            break;
+        }
+        case EglRFC::EeglCopyBuffers:
+        {
+            ret = eglCopyBuffers();
+            break;
+        }
+        case EglRFC::EeglSimulatorSetSurfaceParams:
+        {
+            ret = eglPlatsimSetSurfaceParams();
+            break;
+        }
+		case EglRFC::EeglSimulatorCopyImageData:
+        {
+            ret = eglPlatsimCopyImageData();
+            break;
+        }
+		case EglRFC::EeglPixmapSurfaceSizeChanged:
+        {
+            ret = eglPixmapSurfaceSizeChanged();
+            break;
+        }
+		case EglRFC::EeglMetaGetConfigs:
+		{
+			ret = eglMetaGetConfigs();
+			break;
+		}
+        default:
+            TRACE("Unimplemented EGL Op code %u\n",aCode);
+            break;
+    }
+    return ret;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/src/opengles11apiwrapper.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2580 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN                       // Exclude rarely-used stuff from Windows headers
+#include <windows.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <GLES/gl.h>
+#include "opengles11apiwrapper.h"
+#include "serializedfunctioncall.h"
+#include "remotefunctioncall.h"
+#include "khronosapiwrapperdefs.h"
+
+#include "openvgrfc.h"
+
+
+OGLES11Wrapper::OGLES11Wrapper(RemoteFunctionCallData& currentFunctionCallData,
+            APIWrapperStack* stack,
+            void* result,
+            MGraphicsVHWCallback* serviceIf):
+APIWrapper(currentFunctionCallData, stack, result, serviceIf),
+m_currentFunctionCall(m_currentFunctionCallData)
+{
+}
+
+int OGLES11Wrapper::DispatchRequest(unsigned long aCode)
+{
+    int ret(0);
+    TRACE("OpenGLES11APIWrapper: OpenGL ES Op command received: %u\n", aCode);
+
+    switch ( aCode )
+    {
+    case OpenGlES11RFC::EglActiveTexture:
+        ret = glActiveTexture();
+        break;
+    case OpenGlES11RFC::EglAlphaFunc:
+        ret = glAlphaFunc();
+        break;
+    case OpenGlES11RFC::EglAlphaFuncx:
+        ret = glAlphaFuncx();
+        break;
+    case OpenGlES11RFC::EglBindBuffer:
+        ret = glBindBuffer();
+        break;
+    case OpenGlES11RFC::EglBindTexture:
+        ret = glBindTexture();
+        break;
+    case OpenGlES11RFC::EglBlendFunc:
+        ret = glBlendFunc();
+        break;
+    case OpenGlES11RFC::EglBufferData:
+        ret = glBufferData();
+        break;
+    case OpenGlES11RFC::EglBufferSubData:
+        ret = glBufferSubData();
+        break;
+    case OpenGlES11RFC::EglClear:
+        ret = glClear();
+        break;
+    case OpenGlES11RFC::EglClearColor:
+        ret = glClearColor();
+        break;
+    case OpenGlES11RFC::EglClearColorx:
+        ret = glClearColorx();
+        break;
+    case OpenGlES11RFC::EglClearDepthf:
+        ret = glClearDepthf();
+        break;
+    case OpenGlES11RFC::EglClearDepthx:
+        ret = glClearDepthx();
+        break;
+    case OpenGlES11RFC::EglClearStencil:
+        ret = glClearStencil();
+        break;
+    case OpenGlES11RFC::EglClientActiveTexture:
+        ret = glClientActiveTexture();
+        break;
+    case OpenGlES11RFC::EglClipPlanef:
+        ret = glClipPlanef();
+        break;
+    case OpenGlES11RFC::EglClipPlanex:
+        ret = glClipPlanex();
+        break;
+    case OpenGlES11RFC::EglColor4f:
+        ret = glColor4f();
+        break;
+    case OpenGlES11RFC::EglColor4ub:
+        ret = glColor4ub();
+        break;
+    case OpenGlES11RFC::EglColor4x:
+        ret = glColor4x();
+        break;
+    case OpenGlES11RFC::EglColorMask:
+        ret = glColorMask();
+        break;
+    case OpenGlES11RFC::EglCompressedTexImage2D:
+        ret = glCompressedTexImage2D();
+        break;
+    case OpenGlES11RFC::EglCompressedTexSubImage2D:
+        ret = glCompressedTexSubImage2D();
+        break;
+    case OpenGlES11RFC::EglCopyTexImage2D:
+        ret = glCopyTexImage2D();
+        break;
+    case OpenGlES11RFC::EglCopyTexSubImage2D:
+        ret = glCopyTexSubImage2D();
+        break;
+    case OpenGlES11RFC::EglCullFace:
+        ret = glCullFace();
+        break;
+    case OpenGlES11RFC::EglDeleteBuffers:
+        ret = glDeleteBuffers();
+        break;
+    case OpenGlES11RFC::EglDeleteTextures:
+        ret = glDeleteTextures();
+        break;
+    case OpenGlES11RFC::EglDepthFunc:
+        ret = glDepthFunc();
+        break;
+    case OpenGlES11RFC::EglDepthMask:
+        ret = glDepthMask();
+        break;
+    case OpenGlES11RFC::EglDepthRangef:
+        ret = glDepthRangef();
+        break;
+    case OpenGlES11RFC::EglDepthRangex:
+        ret = glDepthRangex();
+        break;
+    case OpenGlES11RFC::EglDisable:
+        ret = glDisable();
+        break;
+    case OpenGlES11RFC::EglDisableClientState:
+        ret = glDisableClientState();
+        break;
+    case OpenGlES11RFC::EglDrawArrays:
+        ret = glDrawArrays();
+        break;
+    case OpenGlES11RFC::EglDrawElements:
+        ret = glDrawElements();
+        break;
+    case OpenGlES11RFC::EglEnable:
+        ret = glEnable();
+        break;
+    case OpenGlES11RFC::EglEnableClientState:
+        ret = glEnableClientState();
+        break;
+    case OpenGlES11RFC::EglFinish:
+        ret = glFinish();
+        break;
+    case OpenGlES11RFC::EglFlush:
+        ret = glFlush();
+        break;
+    case OpenGlES11RFC::EglFogf:
+        ret = glFogf();
+        break;
+    case OpenGlES11RFC::EglFogfv:
+        ret = glFogfv();
+        break;
+    case OpenGlES11RFC::EglFogx:
+        ret = glFogx();
+        break;
+    case OpenGlES11RFC::EglFogxv:
+        ret = glFogxv();
+        break;
+    case OpenGlES11RFC::EglFrontFace:
+        ret = glFrontFace();
+        break;
+    case OpenGlES11RFC::EglFrustumf:
+        ret = glFrustumf();
+        break;
+    case OpenGlES11RFC::EglFrustumx:
+        ret = glFrustumx();
+        break;
+    case OpenGlES11RFC::EglGenBuffers:
+        ret = glGenBuffers();
+        break;
+    case OpenGlES11RFC::EglGenTextures:
+        ret = glGenTextures();
+        break;
+    case OpenGlES11RFC::EglGetBooleanv:
+        ret = glGetBooleanv();
+        break;
+    case OpenGlES11RFC::EglGetBufferParameteriv:
+        ret = glGetBufferParameteriv();
+        break;
+    case OpenGlES11RFC::EglGetClipPlanef:
+        ret = glGetClipPlanef();
+        break;
+    case OpenGlES11RFC::EglGetClipPlanex:
+        ret = glGetClipPlanex();
+        break;
+    case OpenGlES11RFC::EglGetError:
+        ret = glGetError();
+        break;
+    case OpenGlES11RFC::EglGetFixedv:
+        ret = glGetFixedv();
+        break;
+    case OpenGlES11RFC::EglGetFloatv:
+        ret = glGetFloatv();
+        break;
+    case OpenGlES11RFC::EglGetIntegerv:
+        ret = glGetIntegerv();
+        break;
+    case OpenGlES11RFC::EglGetLightfv:
+        ret = glGetLightfv();
+        break;
+    case OpenGlES11RFC::EglGetLightxv:
+        ret = glGetLightxv();
+        break;
+    case OpenGlES11RFC::EglGetMaterialfv:
+        ret = glGetMaterialfv();
+        break;
+    case OpenGlES11RFC::EglGetMaterialxv:
+        ret = glGetMaterialxv();
+        break;
+    case OpenGlES11RFC::EglGetPointerv:
+        ret = glGetPointerv();
+        break;
+//  case OpenGlES11RFC::EglGetString:
+//      ret = glGetString();
+//      break;
+    case OpenGlES11RFC::EglGetTexEnvfv:
+        ret = glGetTexEnvfv();
+        break;
+    case OpenGlES11RFC::EglGetTexEnviv:
+        ret = glGetTexEnviv();
+        break;
+    case OpenGlES11RFC::EglGetTexEnvxv:
+        ret = glGetTexEnvxv();
+        break;
+    case OpenGlES11RFC::EglGetTexParameterfv:
+        ret = glGetTexParameterfv();
+        break;
+    case OpenGlES11RFC::EglGetTexParameteriv:
+        ret = glGetTexParameteriv();
+        break;
+    case OpenGlES11RFC::EglGetTexParameterxv:
+        ret = glGetTexParameterxv();
+        break;
+    case OpenGlES11RFC::EglHint:
+        ret = glHint();
+        break;
+    case OpenGlES11RFC::EglIsBuffer:
+        ret = glIsBuffer();
+        break;
+    case OpenGlES11RFC::EglIsEnabled:
+        ret = glIsEnabled();
+        break;
+    case OpenGlES11RFC::EglIsTexture:
+        ret = glIsTexture();
+        break;
+    case OpenGlES11RFC::EglLightModelf:
+        ret = glLightModelf();
+        break;
+    case OpenGlES11RFC::EglLightModelfv:
+        ret = glLightModelfv();
+        break;
+    case OpenGlES11RFC::EglLightModelx:
+        ret = glLightModelx();
+        break;
+    case OpenGlES11RFC::EglLightModelxv:
+        ret = glLightModelxv();
+        break;
+    case OpenGlES11RFC::EglLightf:
+        ret = glLightf();
+        break;
+    case OpenGlES11RFC::EglLightfv:
+        ret = glLightfv();
+        break;
+    case OpenGlES11RFC::EglLightx:
+        ret = glLightx();
+        break;
+    case OpenGlES11RFC::EglLightxv:
+        ret = glLightxv();
+        break;
+    case OpenGlES11RFC::EglLineWidth:
+        ret = glLineWidth();
+        break;
+    case OpenGlES11RFC::EglLineWidthx:
+        ret = glLineWidthx();
+        break;
+    case OpenGlES11RFC::EglLoadIdentity:
+        ret = glLoadIdentity();
+        break;
+    case OpenGlES11RFC::EglLoadMatrixf:
+        ret = glLoadMatrixf();
+        break;
+    case OpenGlES11RFC::EglLoadMatrixx:
+        ret = glLoadMatrixx();
+        break;
+    case OpenGlES11RFC::EglLogicOp:
+        ret = glLogicOp();
+        break;
+    case OpenGlES11RFC::EglMaterialf:
+        ret = glMaterialf();
+        break;
+    case OpenGlES11RFC::EglMaterialfv:
+        ret = glMaterialfv();
+        break;
+    case OpenGlES11RFC::EglMaterialx:
+        ret = glMaterialx();
+        break;
+    case OpenGlES11RFC::EglMaterialxv:
+        ret = glMaterialxv();
+        break;
+    case OpenGlES11RFC::EglMatrixMode:
+        ret = glMatrixMode();
+        break;
+    case OpenGlES11RFC::EglMultMatrixf:
+        ret = glMultMatrixf();
+        break;
+    case OpenGlES11RFC::EglMultMatrixx:
+        ret = glMultMatrixx();
+        break;
+    case OpenGlES11RFC::EglMultiTexCoord4f:
+        ret = glMultiTexCoord4f();
+        break;
+    case OpenGlES11RFC::EglMultiTexCoord4x:
+        ret = glMultiTexCoord4x();
+        break;
+    case OpenGlES11RFC::EglNormal3f:
+        ret = glNormal3f();
+        break;
+    case OpenGlES11RFC::EglNormal3x:
+        ret = glNormal3x();
+        break;
+    case OpenGlES11RFC::EglOrthof:
+        ret = glOrthof();
+        break;
+    case OpenGlES11RFC::EglOrthox:
+        ret = glOrthox();
+        break;
+    case OpenGlES11RFC::EglPixelStorei:
+        ret = glPixelStorei();
+        break;
+    case OpenGlES11RFC::EglPointParameterf:
+        ret = glPointParameterf();
+        break;
+    case OpenGlES11RFC::EglPointParameterfv:
+        ret = glPointParameterfv();
+        break;
+    case OpenGlES11RFC::EglPointParameterx:
+        ret = glPointParameterx();
+        break;
+    case OpenGlES11RFC::EglPointParameterxv:
+        ret = glPointParameterxv();
+        break;
+    case OpenGlES11RFC::EglPointSize:
+        ret = glPointSize();
+        break;
+    case OpenGlES11RFC::EglPointSizex:
+        ret = glPointSizex();
+        break;
+    case OpenGlES11RFC::EglPolygonOffset:
+        ret = glPolygonOffset();
+        break;
+    case OpenGlES11RFC::EglPolygonOffsetx:
+        ret = glPolygonOffsetx();
+        break;
+    case OpenGlES11RFC::EglPopMatrix:
+        ret = glPopMatrix();
+        break;
+    case OpenGlES11RFC::EglPushMatrix:
+        ret = glPushMatrix();
+        break;
+    case OpenGlES11RFC::EglReadPixels:
+        ret = glReadPixels();
+        break;
+    case OpenGlES11RFC::EglRotatef:
+        ret = glRotatef();
+        break;
+    case OpenGlES11RFC::EglRotatex:
+        ret = glRotatex();
+        break;
+    case OpenGlES11RFC::EglSampleCoverage:
+        ret = glSampleCoverage();
+        break;
+    case OpenGlES11RFC::EglSampleCoveragex:
+        ret = glSampleCoveragex();
+        break;
+    case OpenGlES11RFC::EglScalef:
+        ret = glScalef();
+        break;
+    case OpenGlES11RFC::EglScalex:
+        ret = glScalex();
+        break;
+    case OpenGlES11RFC::EglScissor:
+        ret = glScissor();
+        break;
+    case OpenGlES11RFC::EglShadeModel:
+        ret = glShadeModel();
+        break;
+    case OpenGlES11RFC::EglStencilFunc:
+        ret = glStencilFunc();
+        break;
+    case OpenGlES11RFC::EglStencilMask:
+        ret = glStencilMask();
+        break;
+    case OpenGlES11RFC::EglStencilOp:
+        ret = glStencilOp();
+        break;
+    case OpenGlES11RFC::EglTexEnvf:
+        ret = glTexEnvf();
+        break;
+    case OpenGlES11RFC::EglTexEnvfv:
+        ret = glTexEnvfv();
+        break;
+    case OpenGlES11RFC::EglTexEnvi:
+        ret = glTexEnvi();
+        break;
+    case OpenGlES11RFC::EglTexEnviv:
+        ret = glTexEnviv();
+        break;
+    case OpenGlES11RFC::EglTexEnvx:
+        ret = glTexEnvx();
+        break;
+    case OpenGlES11RFC::EglTexEnvxv:
+        ret = glTexEnvxv();
+        break;
+    case OpenGlES11RFC::EglTexImage2D:
+        ret = glTexImage2D();
+        break;
+    case OpenGlES11RFC::EglTexParameterf:
+        ret = glTexParameterf();
+        break;
+    case OpenGlES11RFC::EglTexParameterfv:
+        ret = glTexParameterfv();
+        break;
+    case OpenGlES11RFC::EglTexParameteri:
+        ret = glTexParameteri();
+        break;
+    case OpenGlES11RFC::EglTexParameteriv:
+        ret = glTexParameteriv();
+        break;
+    case OpenGlES11RFC::EglTexParameterx:
+        ret = glTexParameterx();
+        break;
+    case OpenGlES11RFC::EglTexParameterxv:
+        ret = glTexParameterxv();
+        break;
+    case OpenGlES11RFC::EglTexSubImage2D:
+        ret = glTexSubImage2D();
+        break;
+    case OpenGlES11RFC::EglTranslatef:
+        ret = glTranslatef();
+        break;
+    case OpenGlES11RFC::EglTranslatex:
+        ret = glTranslatex();
+        break;
+    case OpenGlES11RFC::EglViewport:
+        ret = glViewport();
+        break;
+
+    // from Eglextplatform.h
+    case OpenGlES11RFC::EglCurrentPaletteMatrixOES:
+        ret = glCurrentPaletteMatrixOES();
+        break;
+    case OpenGlES11RFC::EglDrawTexfOES:
+        ret = glDrawTexfOES();
+        break;
+    case OpenGlES11RFC::EglDrawTexfvOES:
+        ret = glDrawTexfvOES();
+        break;
+    case OpenGlES11RFC::EglDrawTexiOES:
+        ret = glDrawTexiOES();
+        break;
+    case OpenGlES11RFC::EglDrawTexivOES:
+        ret = glDrawTexivOES();
+        break;
+    case OpenGlES11RFC::EglDrawTexsOES:
+        ret = glDrawTexsOES();
+        break;
+    case OpenGlES11RFC::EglDrawTexsvOES:
+        ret = glDrawTexsvOES();
+        break;
+    case OpenGlES11RFC::EglDrawTexxOES:
+        ret = glDrawTexxOES();
+        break;
+    case OpenGlES11RFC::EglDrawTexxvOES:
+        ret = glDrawTexxvOES();
+        break;
+    case OpenGlES11RFC::EglLoadPaletteFromModelViewMatrixOES:
+        ret = glLoadPaletteFromModelViewMatrixOES();
+        break;
+    case OpenGlES11RFC::EglQueryMatrixxOES:
+        ret = glQueryMatrixxOES();
+        break;
+
+    case OpenGlES11RFC::EglColorPointer:
+    case OpenGlES11RFC::EglNormalPointer:
+    case OpenGlES11RFC::EglTexCoordPointer:
+    case OpenGlES11RFC::EglVertexPointer:
+    case OpenGlES11RFC::EglMatrixIndexPointerOES:
+    case OpenGlES11RFC::EglWeightPointerOES:    
+        TRACE("OpenGLES11APIWrapper: ERROR! Vertex pointer functions are not handled directly, should not be here\n");
+        break;
+        
+    // client shutdown
+    case OpenGlES11RFC::EClientShutdown:
+        TRACE("OpenGLES11APIWrapper: Client shutdown unimplemented\n");
+        break;
+
+    default:
+        TRACE("OpenGLES11APIWrapper: Unimplemented OpenGL ES Op code %u\n",aCode);
+        break;
+    }
+    TRACE("OpenGLES11APIWrapper: OpenGL ES 1.1 command processed\n");
+    return ret;
+}
+
+int OGLES11Wrapper::WriteReply()
+{
+#ifdef LOG_ERROR
+    int operationid = (int)m_currentFunctionCall.Data().Header().iOpCode;
+    
+    int glerror = ::glGetError();
+    if ( m_lastGlError != glerror )
+    {
+        if ( GL_NO_ERROR != glerror )
+        {
+            TRACE("OpenGLES11APIWrapper: OpenGL error 0x%X, for request %d\n", glerror, operationid );
+        }
+        m_lastGlError = glerror;
+    }
+#endif
+    return APIWrapper::WriteReply();
+}
+
+// ///////////////////////////////////////////////////
+// Here follows the functions that map to the GL calls
+
+
+int OGLES11Wrapper::glActiveTexture()
+{
+    GLenum texture;
+    m_currentFunctionCall.GetParamValue(texture, 0);
+    ::glActiveTexture(texture);
+    return WriteReply();
+}
+int OGLES11Wrapper::glAlphaFunc()
+{
+    GLenum func;
+    m_currentFunctionCall.GetParamValue(func, 0);
+    GLclampf ref;
+    m_currentFunctionCall.GetParamValue(ref, 1);
+    ::glAlphaFunc(func, ref);
+    return WriteReply();
+}
+int OGLES11Wrapper::glAlphaFuncx()
+{
+    GLenum func;
+    m_currentFunctionCall.GetParamValue(func, 0);
+    GLclampx ref;
+    m_currentFunctionCall.GetParamValue(ref, 1);
+    ::glAlphaFuncx(func, ref);
+    return WriteReply();
+}
+int OGLES11Wrapper::glBindBuffer()
+{
+    GLenum target;
+    m_currentFunctionCall.GetParamValue(target, 0);    
+    GLuint buffer;
+    m_currentFunctionCall.GetParamValue(buffer, 1);
+    ::glBindBuffer(target, buffer);
+    return WriteReply();
+}
+int OGLES11Wrapper::glBindTexture()
+{
+    GLenum target;
+    m_currentFunctionCall.GetParamValue(target, 0);    
+    GLuint texIndex;
+    m_currentFunctionCall.GetParamValue(texIndex, 1);
+    ::glBindTexture(target, texIndex);
+    return WriteReply();
+}
+int OGLES11Wrapper::glBlendFunc()
+{
+    GLenum src;
+    m_currentFunctionCall.GetParamValue(src, 0);
+    GLenum dst;
+    m_currentFunctionCall.GetParamValue(dst, 1);
+    ::glBlendFunc(src, dst);
+    return WriteReply();
+}
+int OGLES11Wrapper::glBufferData()
+{
+    GLenum target;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    //GLsizeiptr size;    
+    GLint size;
+    m_currentFunctionCall.GetParamValue(size, 1);
+    
+    void* data;
+    //GLsizeiptr size2;
+    GLint size2;
+    m_currentFunctionCall.GetVectorData(data, size2, 2); //is this correct??
+    //size == size2 ?
+    
+    GLenum usage;
+    m_currentFunctionCall.GetParamValue(usage, 3);
+    ::glBufferData(target, size, data, usage);
+    return WriteReply();
+}
+int OGLES11Wrapper::glBufferSubData()
+{
+    GLenum target;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    //GLintptr offset;
+    GLint offset;
+    m_currentFunctionCall.GetParamValue(offset, 1);
+    //GLsizeiptr size;
+    GLint size;
+    m_currentFunctionCall.GetParamValue(size, 2);
+    void* data;
+    //GLsizeiptr size2;
+    GLint size2;
+    m_currentFunctionCall.GetVectorData(data, size2, 3); //is this correct??
+    ::glBufferSubData(target,offset,size,data);
+    return WriteReply();
+}
+int OGLES11Wrapper::glClear()
+{
+    GLbitfield buf;
+    m_currentFunctionCall.GetParamValue(buf, 0);
+    ::glClear(buf);
+    return WriteReply();
+}
+int OGLES11Wrapper::glClearColor()
+{
+    GLclampf r;
+    m_currentFunctionCall.GetParamValue(r, 0);
+    GLclampf g;
+    m_currentFunctionCall.GetParamValue(g, 1);
+    GLclampf b;
+    m_currentFunctionCall.GetParamValue(b, 2);
+    GLclampf a;
+    m_currentFunctionCall.GetParamValue(a, 3);
+    ::glClearColor(r,g,b,a);
+    return WriteReply();
+}
+int OGLES11Wrapper::glClearColorx()
+{
+    GLclampx r;
+    m_currentFunctionCall.GetParamValue(r, 0);
+    GLclampx g;
+    m_currentFunctionCall.GetParamValue(g, 1);
+    GLclampx b;
+    m_currentFunctionCall.GetParamValue(b, 2);
+    GLclampx a;
+    m_currentFunctionCall.GetParamValue(a, 3);
+    ::glClearColorx(r,g,b,a);
+    return WriteReply();
+}
+int OGLES11Wrapper::glClearDepthf()
+{
+    GLclampf d;
+    m_currentFunctionCall.GetParamValue(d, 0);
+    ::glClearDepthf(d);
+    return WriteReply();
+}
+int OGLES11Wrapper::glClearDepthx()
+{
+    GLfixed d;
+    m_currentFunctionCall.GetParamValue(d, 0);
+    ::glClearDepthx(d);    
+    return WriteReply();
+}
+int OGLES11Wrapper::glClearStencil()
+{
+    GLint s;
+    m_currentFunctionCall.GetParamValue(s, 0);
+    ::glClearStencil(s);     
+    return WriteReply();
+}
+int OGLES11Wrapper::glClientActiveTexture()
+{
+    GLenum texture;
+    m_currentFunctionCall.GetParamValue(texture, 0);
+    ::glClientActiveTexture(texture);     
+    return WriteReply();
+}
+int OGLES11Wrapper::glClipPlanef()
+{
+    GLenum plane;
+    GLfloat* equation;
+    m_currentFunctionCall.GetParamValue(plane, 0);
+    //GLsizeiptr size;
+    GLint size;
+    m_currentFunctionCall.GetVectorData(equation, size, 1);
+    ::glClipPlanef(plane,equation);
+    return WriteReply();
+}
+int OGLES11Wrapper::glClipPlanex()
+{
+    GLenum plane;
+    GLfixed* equation;
+    //GLsizeiptr size;
+    GLint size;
+    m_currentFunctionCall.GetParamValue(plane, 0);
+    m_currentFunctionCall.GetVectorData(equation, size, 1);
+    ::glClipPlanex(plane,equation);
+    return WriteReply();
+}
+int OGLES11Wrapper::glColor4f()
+{
+    GLfloat r,g,b,a;
+    m_currentFunctionCall.GetParamValue(r, 0);
+    m_currentFunctionCall.GetParamValue(g, 1);
+    m_currentFunctionCall.GetParamValue(b, 2);
+    m_currentFunctionCall.GetParamValue(a, 3);
+    ::glColor4f(r,g,b,a);    
+    return WriteReply();
+}
+int OGLES11Wrapper::glColor4ub()
+{
+    GLubyte r,g,b,a;
+    m_currentFunctionCall.GetParamValue(r, 0);
+    m_currentFunctionCall.GetParamValue(g, 1);
+    m_currentFunctionCall.GetParamValue(b, 2);
+    m_currentFunctionCall.GetParamValue(a, 3);
+    ::glColor4ub(r,g,b,a);  
+    return WriteReply();
+}
+int OGLES11Wrapper::glColor4x()
+{
+    GLfixed r,g,b,a;
+    m_currentFunctionCall.GetParamValue(r, 0);
+    m_currentFunctionCall.GetParamValue(g, 1);
+    m_currentFunctionCall.GetParamValue(b, 2);
+    m_currentFunctionCall.GetParamValue(a, 3);
+    ::glColor4x(r,g,b,a);
+    return WriteReply();
+}
+int OGLES11Wrapper::glColorMask()
+{
+    GLboolean r,g,b,a;
+    m_currentFunctionCall.GetParamValue(r, 0);
+    m_currentFunctionCall.GetParamValue(g, 1);
+    m_currentFunctionCall.GetParamValue(b, 2);
+    m_currentFunctionCall.GetParamValue(a, 3);
+    ::glColorMask(r,g,b,a);
+    return WriteReply();
+}
+
+int OGLES11Wrapper::glCompressedTexImage2D()
+{
+    GLenum target;
+    GLint level;
+    GLenum internalFormat;
+    GLsizei width;
+    GLsizei height;
+    GLint border;
+    GLsizei imageSize;
+    GLvoid* data;
+    //GLsizeiptr size;
+    GLint size;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(level, 1);
+    m_currentFunctionCall.GetParamValue(internalFormat, 2);
+    m_currentFunctionCall.GetParamValue(width, 3);
+    m_currentFunctionCall.GetParamValue(height, 4);
+    m_currentFunctionCall.GetParamValue(border, 5);
+    m_currentFunctionCall.GetParamValue(imageSize, 6);
+    m_currentFunctionCall.GetVectorData(data, size, 7);
+    ::glCompressedTexImage2D(target,level,internalFormat,width,height,border,imageSize,data);
+    return WriteReply();
+}
+int OGLES11Wrapper::glCompressedTexSubImage2D()
+{
+    GLenum target;
+    GLint level;
+    GLint xoffset;
+    GLint yoffset;
+    GLsizei width;
+    GLsizei height;
+    GLenum format;
+    GLsizei imageSize;
+    GLvoid*   data;
+    //GLsizeiptr size;
+    GLint size;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(level, 1);
+    m_currentFunctionCall.GetParamValue(xoffset, 2);
+    m_currentFunctionCall.GetParamValue(yoffset, 3);
+    m_currentFunctionCall.GetParamValue(width, 4);
+    m_currentFunctionCall.GetParamValue(height, 5);
+    m_currentFunctionCall.GetParamValue(format, 6);
+    m_currentFunctionCall.GetParamValue(imageSize, 7);
+    m_currentFunctionCall.GetVectorData(data, size, 8);
+    ::glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data);
+    return WriteReply();
+}
+int OGLES11Wrapper::glCopyTexImage2D()
+{
+    GLenum target;    
+    GLint level;
+    GLenum internalFormat;
+    GLint x;
+    GLint y;
+    GLsizei width;
+    GLsizei height;
+    GLint border;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(level, 1);
+    m_currentFunctionCall.GetParamValue(internalFormat, 2);
+    m_currentFunctionCall.GetParamValue(x, 3);
+    m_currentFunctionCall.GetParamValue(y, 4);    
+    m_currentFunctionCall.GetParamValue(width, 5);    
+    m_currentFunctionCall.GetParamValue(height, 6);    
+    m_currentFunctionCall.GetParamValue(border, 7);
+    ::glCopyTexImage2D(target,level,internalFormat,x,y,width,height,border);
+    return WriteReply();
+}
+int OGLES11Wrapper::glCopyTexSubImage2D()
+{
+    GLenum  target;
+    GLint   level;
+    GLint   xoffset;
+    GLint   yoffset;
+    GLint   x;
+    GLint   y;
+    GLsizei width;
+    GLsizei height;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(level, 1);
+    m_currentFunctionCall.GetParamValue(xoffset, 2);
+    m_currentFunctionCall.GetParamValue(yoffset, 3);
+    m_currentFunctionCall.GetParamValue(x, 4);
+    m_currentFunctionCall.GetParamValue(y, 5);
+    m_currentFunctionCall.GetParamValue(width, 6);
+    m_currentFunctionCall.GetParamValue(height, 7);    
+    ::glCopyTexSubImage2D(target,level,xoffset,yoffset,x,y,width,height);
+    return WriteReply();
+}
+int OGLES11Wrapper::glCullFace()
+{
+    GLenum mode;
+
+    m_currentFunctionCall.GetParamValue(mode, 0);
+
+    ::glCullFace(mode);
+    return WriteReply();
+}
+int OGLES11Wrapper::glDeleteBuffers()
+{
+    GLsizei n;
+    GLuint *buffers;
+
+    m_currentFunctionCall.GetParamValue(n, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(buffers, size1, 1);
+
+    ::glDeleteBuffers(n, buffers);
+    return WriteReply();
+}
+int OGLES11Wrapper::glDeleteTextures()
+{
+    GLsizei n;
+    GLuint *textures;
+
+    m_currentFunctionCall.GetParamValue(n, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(textures, size1, 1);
+
+    ::glDeleteTextures(n, textures);
+    return WriteReply();
+}
+int OGLES11Wrapper::glDepthFunc()
+{
+    GLenum func;
+
+    m_currentFunctionCall.GetParamValue(func, 0);
+
+    ::glDepthFunc(func);
+    return WriteReply();
+}
+int OGLES11Wrapper::glDepthMask()
+{
+    GLboolean flag;
+
+    m_currentFunctionCall.GetParamValue(flag, 0);
+
+    ::glDepthMask(flag);
+    return WriteReply();
+}
+int OGLES11Wrapper::glDepthRangef()
+{
+    GLclampf zNear;
+    GLclampf zFar;
+
+    m_currentFunctionCall.GetParamValue(zNear, 0);
+    m_currentFunctionCall.GetParamValue(zFar, 1);
+
+    ::glDepthRangef(zNear, zFar);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glDepthRangex()
+{
+    GLclampx zNear;
+    GLclampx zFar;
+
+    m_currentFunctionCall.GetParamValue(zNear, 0);
+    m_currentFunctionCall.GetParamValue(zFar, 1);
+
+    ::glDepthRangex(zNear, zFar);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glDisable()
+{
+    GLenum cap;
+
+    m_currentFunctionCall.GetParamValue(cap, 0);
+
+    ::glDisable(cap);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glDisableClientState()
+{
+    GLenum array;
+
+    m_currentFunctionCall.GetParamValue(array, 0);
+
+    ::glDisableClientState(array);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glDrawArrays()
+{
+    GLenum mode;
+    GLint first;
+    GLsizei count;
+
+    m_currentFunctionCall.GetParamValue(mode, 0);
+    m_currentFunctionCall.GetParamValue(first, 1);
+    m_currentFunctionCall.GetParamValue(count, 2);
+
+    // Get the data arrays themselves -- note that this is additional data
+    TInt arrayCount, arrayEnabled;
+    m_currentFunctionCall.GetParamValue(arrayCount, 3);
+    m_currentFunctionCall.GetParamValue(arrayEnabled, 4);
+
+    vertexArrayInfo *vertexArrays;
+    vertexArrays = (vertexArrayInfo *) malloc(arrayCount * sizeof(vertexArrayInfo));
+
+    for (int i=0; i<arrayCount; i++)
+    {
+        m_currentFunctionCall.GetParamValue(vertexArrays[i].size, 5 + 4*i);
+        m_currentFunctionCall.GetParamValue(vertexArrays[i].type, 6 + 4*i);
+        m_currentFunctionCall.GetParamValue(vertexArrays[i].stride, 7 + 4*i);
+        TInt size;
+        m_currentFunctionCall.GetVectorData(vertexArrays[i].pointer, size, 8 + 4*i);
+    }
+    
+    int x = 0; //position in the vertexArrays, 'i' in the loop above
+    for(int i=0; i<NUM_ARRAYS; i++) 
+    {
+        switch( i )
+        {
+            case COLOR_ARRAY:
+                if (arrayEnabled & (1<<6))
+                {
+                    ::glColorPointer(vertexArrays[x].size, vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case NORMAL_ARRAY:
+                if (arrayEnabled & (1<<5))
+                {
+                    ::glNormalPointer(vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case POINT_SIZE_ARRAY:
+                if (arrayEnabled & (1<<4))
+                {
+                    ::glPointSizePointerOES(vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case TEX_COORD_ARRAY:
+                if (arrayEnabled & (1<<3))
+                {
+                    ::glTexCoordPointer(vertexArrays[x].size, vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case VERTEX_ARRAY:
+                if (arrayEnabled & (1<<2)){
+                    ::glVertexPointer(vertexArrays[x].size, vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case MATRIX_INDEX_ARRAY:
+                break;
+            case WEIGHT_ARRAY:
+                break;
+            default:
+                // Do nothing
+                break;
+        }   
+    }
+
+    ::glDrawArrays(mode, first, count);
+    return WriteReply();
+}
+int OGLES11Wrapper::glDrawElements()
+{
+    GLenum mode;
+    GLsizei count;
+    GLenum type;
+    GLvoid *indices;
+
+    m_currentFunctionCall.GetParamValue(mode, 0);
+    m_currentFunctionCall.GetParamValue(count, 1);
+    m_currentFunctionCall.GetParamValue(type, 2);
+    TInt size3;
+    m_currentFunctionCall.GetVectorData(indices, size3, 3);
+
+    // Get the data arrays themselves -- note that this is additional data
+    TInt arrayCount, arrayEnabled;
+    m_currentFunctionCall.GetParamValue(arrayCount, 4);
+    m_currentFunctionCall.GetParamValue(arrayEnabled, 5);
+
+    vertexArrayInfo *vertexArrays;
+    vertexArrays = (vertexArrayInfo *) malloc(arrayCount * sizeof(vertexArrayInfo));
+
+    for (int i=0; i<arrayCount; i++)
+    {
+        m_currentFunctionCall.GetParamValue(vertexArrays[i].size, 6 + 4*i);
+        m_currentFunctionCall.GetParamValue(vertexArrays[i].type, 7 + 4*i);
+        m_currentFunctionCall.GetParamValue(vertexArrays[i].stride, 8 + 4*i);
+        TInt size;
+        m_currentFunctionCall.GetVectorData(vertexArrays[i].pointer, size, 9 + 4*i);
+    }
+    
+    int x = 0; //position in the vertexArrays, 'i' in the loop above
+    for(int i=0; i<NUM_ARRAYS; i++) 
+    {
+        switch( i )
+        {
+            case COLOR_ARRAY:
+                if (arrayEnabled & (1<<6))
+                {
+                    ::glColorPointer(vertexArrays[x].size, vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case NORMAL_ARRAY:
+                if (arrayEnabled & (1<<5))
+                {
+                    ::glNormalPointer(vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case POINT_SIZE_ARRAY:
+                if (arrayEnabled & (1<<4))
+                {
+                    ::glPointSizePointerOES(vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case TEX_COORD_ARRAY:
+                if (arrayEnabled & (1<<3))
+                {
+                    ::glTexCoordPointer(vertexArrays[x].size, vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case VERTEX_ARRAY:
+                if (arrayEnabled & (1<<2)){
+                    ::glVertexPointer(vertexArrays[x].size, vertexArrays[x].type, vertexArrays[x].stride, vertexArrays[x].pointer);
+                    x++;
+                }
+                break;
+            case MATRIX_INDEX_ARRAY:
+                break;
+            case WEIGHT_ARRAY:
+                break;
+            default:
+                // Do nothing
+                break;
+        }   
+    }
+
+
+    ::glDrawElements(mode, count, type, indices);
+    return WriteReply();
+}
+int OGLES11Wrapper::glEnable()
+{
+    GLenum cap;
+
+    m_currentFunctionCall.GetParamValue(cap, 0);
+
+    ::glEnable(cap);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glEnableClientState()
+{
+    GLenum array;
+
+    m_currentFunctionCall.GetParamValue(array, 0);
+
+    ::glEnableClientState(array);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glFinish()
+{
+    ::glFinish();
+    return WriteReply();
+}
+int OGLES11Wrapper::glFlush()
+{
+    ::glFlush();
+    return WriteReply();
+}
+int OGLES11Wrapper::glFogf()
+{
+    GLenum pname;
+    GLfloat param;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    m_currentFunctionCall.GetParamValue(param, 1);
+
+    ::glFogf(pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glFogfv()
+{
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    ::glFogfv(pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glFogx()
+{
+    GLenum pname;
+    GLfixed param;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    m_currentFunctionCall.GetParamValue(param, 1);
+
+    ::glFogx(pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glFogxv()
+{
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    ::glFogxv(pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glFrontFace()
+{
+    GLenum mode;
+
+    m_currentFunctionCall.GetParamValue(mode, 0);
+
+    ::glFrontFace(mode);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glFrustumf()
+{
+    GLfloat left;
+    GLfloat right;
+    GLfloat bottom;
+    GLfloat top;
+    GLfloat zNear;
+    GLfloat zFar;
+
+    m_currentFunctionCall.GetParamValue(left, 0);
+    m_currentFunctionCall.GetParamValue(right, 1);
+    m_currentFunctionCall.GetParamValue(bottom, 2);
+    m_currentFunctionCall.GetParamValue(top, 3);
+    m_currentFunctionCall.GetParamValue(zNear, 4);
+    m_currentFunctionCall.GetParamValue(zFar, 5);
+
+    ::glFrustumf(left, right, bottom, top, zNear, zFar);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glFrustumx()
+{
+    GLfixed left;
+    GLfixed right;
+    GLfixed bottom;
+    GLfixed top;
+    GLfixed zNear;
+    GLfixed zFar;
+
+    m_currentFunctionCall.GetParamValue(left, 0);
+    m_currentFunctionCall.GetParamValue(right, 1);
+    m_currentFunctionCall.GetParamValue(bottom, 2);
+    m_currentFunctionCall.GetParamValue(top, 3);
+    m_currentFunctionCall.GetParamValue(zNear, 4);
+    m_currentFunctionCall.GetParamValue(zFar, 5);
+
+    ::glFrustumx(left, right, bottom, top, zNear, zFar);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glGenBuffers()
+{
+    GLsizei n;
+    m_currentFunctionCall.GetParamValue(n, 0);
+    
+    GLuint *buffers = (GLuint*)iStack->AllocFromStack( n*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLuint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLuint ) );
+
+    ::glGenBuffers(n, buffers);
+
+    m_currentFunctionCall.SetVectorData( buffers, n, 1 ); // EOut
+    //TODO: when do we free the allocated buffer??
+    
+    int ret = WriteReply(); //TODO: clarify the copy-pasted magic sequence
+    iStack->ClearStack();
+    buffers = NULL;
+    return ret; 
+}
+int OGLES11Wrapper::glGenTextures()
+{
+    GLsizei n;
+    m_currentFunctionCall.GetParamValue(n, 0);
+    
+    GLuint *textures = (GLuint*)iStack->AllocFromStack( n*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLuint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLuint ) );
+
+    ::glGenTextures(n, textures);
+
+    m_currentFunctionCall.SetVectorData( textures, n, 1 ); // EOut
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    textures = NULL;
+    return ret;    
+}
+int OGLES11Wrapper::glGetBooleanv()
+{
+    GLenum pname;
+    GLboolean *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+    
+    params = (GLboolean*)iStack->AllocFromStack( size1*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLboolean ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLboolean ) );
+        
+    ::glGetBooleanv(pname, params); //TODO: how does the ::glGetBooleanv know the array size?
+    
+    m_currentFunctionCall.SetVectorData( params, size1, 1 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret; 
+}
+int OGLES11Wrapper::glGetBufferParameteriv()
+{
+    GLenum target;
+    GLenum pname;
+    GLint *params;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLint*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );
+
+    ::glGetBufferParameteriv(target, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret; 
+}
+int OGLES11Wrapper::glGetClipPlanef()
+{
+    GLenum pname;
+    GLfloat *equation;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(equation, size1, 1);
+
+    equation = (GLfloat*)iStack->AllocFromStack( size1*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLfloat ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLfloat ) );
+
+
+    ::glGetClipPlanef(pname, equation);
+
+    m_currentFunctionCall.SetVectorData( equation, size1, 1 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    equation = NULL;
+    return ret; 
+}
+int OGLES11Wrapper::glGetClipPlanex()
+{
+    GLenum pname;
+    GLfixed *eqn;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(eqn, size1, 1);
+
+    eqn = (GLfixed*)iStack->AllocFromStack( size1*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );
+
+    ::glGetClipPlanex(pname, eqn);
+    
+    m_currentFunctionCall.SetVectorData( eqn, size1, 1 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    eqn = NULL;
+    return ret; 
+}
+int OGLES11Wrapper::glGetError()
+{
+    GLenum ret = ::glGetError();
+    m_currentFunctionCall.SetReturnValue((TUint32) ret);
+    return WriteReply();
+}
+int OGLES11Wrapper::glGetFixedv()
+{
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    params = (GLfixed*)iStack->AllocFromStack( size1*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+    m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );        
+
+    ::glGetFixedv(pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size1, 1 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret; 
+}
+int OGLES11Wrapper::glGetFloatv()
+{
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    params = (GLfloat*)iStack->AllocFromStack( size1*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLfloat ),
+    m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLfloat ) ); 
+    
+    ::glGetFloatv(pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size1, 1 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret; 
+}
+int OGLES11Wrapper::glGetIntegerv()
+{
+    GLenum pname;
+    GLint *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    params = (GLint*)iStack->AllocFromStack( size1*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+    m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) ); 
+    
+    ::glGetIntegerv(pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size1, 1 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetLightfv()
+{
+    GLenum light;
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(light, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLfloat*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLfloat ),
+    m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLfloat ) );
+    
+    ::glGetLightfv(light, pname, params);
+    
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetLightxv()
+{
+    GLenum light;
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(light, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+    
+    params = (GLfixed*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );
+
+    ::glGetLightxv(light, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetMaterialfv()
+{
+    GLenum face;
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(face, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLfloat*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLfloat ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLfloat ) );
+    
+    ::glGetMaterialfv(face, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetMaterialxv()
+{
+    GLenum face;
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(face, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLfixed*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );
+        
+    ::glGetMaterialxv(face, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetPointerv()
+{
+    //never gets called?
+    return WriteReply();
+}
+int OGLES11Wrapper::glGetString()
+{
+    // Not used
+    return WriteReply();
+}
+int OGLES11Wrapper::glGetTexEnvfv()
+{
+    GLenum env;
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(env, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLfloat*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLfloat ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLfloat ) );
+        
+    ::glGetTexEnvfv(env, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetTexEnviv()
+{
+    GLenum env;
+    GLenum pname;
+    GLint *params;
+
+    m_currentFunctionCall.GetParamValue(env, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLint*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );
+        
+    ::glGetTexEnviv(env, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetTexEnvxv()
+{
+    GLenum env;
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(env, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLfixed*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );
+        
+    ::glGetTexEnvxv(env, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetTexParameterfv()
+{
+    GLenum target;
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLfloat*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLfloat ),    
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLfloat ) );
+        
+    ::glGetTexParameterfv(target, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetTexParameteriv()
+{
+    GLenum target;
+    GLenum pname;
+    GLint *params;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLint*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );
+        
+    ::glGetTexParameteriv(target, pname, params);
+
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glGetTexParameterxv()
+{
+    GLenum target;
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    params = (GLint*)iStack->AllocFromStack( size2*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLint ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLint ) );
+        
+    ::glGetTexParameterxv(target, pname, params);
+    
+    m_currentFunctionCall.SetVectorData( params, size2, 2 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    params = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glHint()
+{
+    GLenum target;
+    GLenum mode;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(mode, 1);
+
+    ::glHint(target, mode);
+    
+    return WriteReply();
+}
+int OGLES11Wrapper::glIsBuffer()
+{
+    GLuint buffer;
+
+    m_currentFunctionCall.GetParamValue(buffer, 0);
+
+    GLboolean ret = ::glIsBuffer(buffer);
+    m_currentFunctionCall.SetReturnValue( ret);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glIsEnabled()
+{
+    GLenum cap;
+    m_currentFunctionCall.GetParamValue(cap, 0);
+    
+    GLboolean ret = ::glIsEnabled(cap);
+    m_currentFunctionCall.SetReturnValue( ret);
+    
+    return WriteReply();
+}
+int OGLES11Wrapper::glIsTexture()
+{
+    GLuint texIndex;
+    m_currentFunctionCall.GetParamValue(texIndex, 0);
+    
+    GLboolean ret = ::glIsEnabled(texIndex);
+    m_currentFunctionCall.SetReturnValue( ret);
+        
+    return WriteReply();
+}
+int OGLES11Wrapper::glLightModelf()
+{
+    GLenum pname;
+    GLfloat param;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    m_currentFunctionCall.GetParamValue(param, 1);
+
+    ::glLightModelf(pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLightModelfv()
+{
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    ::glLightModelfv(pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLightModelx()
+{
+    GLenum pname;
+    GLfixed param;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    m_currentFunctionCall.GetParamValue(param, 1);
+
+    ::glLightModelx(pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLightModelxv()
+{
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    ::glLightModelxv(pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLightf()
+{
+    GLenum light;
+    GLenum pname;
+    GLfloat param;
+
+    m_currentFunctionCall.GetParamValue(light, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+
+    ::glLightf(light, pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLightfv()
+{
+    GLenum light;
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(light, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    ::glLightfv(light, pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLightx()
+{
+    GLenum light;
+    GLenum pname;
+    GLfixed param;
+
+    m_currentFunctionCall.GetParamValue(light, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+
+    ::glLightx(light, pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLightxv()
+{
+    GLenum light;
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(light, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    ::glLightxv(light, pname, params);
+    return WriteReply();
+}
+int OGLES11Wrapper::glLineWidth()
+{
+    GLfloat width;
+
+    m_currentFunctionCall.GetParamValue(width, 0);
+
+    ::glLineWidth(width);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLineWidthx()
+{
+    GLfixed width;
+
+    m_currentFunctionCall.GetParamValue(width, 0);
+
+    ::glLineWidthx(width);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLoadIdentity()
+{
+    ::glLoadIdentity();
+    return WriteReply();
+}
+int OGLES11Wrapper::glLoadMatrixf()
+{
+    GLfloat *m;
+
+    TInt size0;
+    m_currentFunctionCall.GetVectorData(m, size0, 0);
+
+    ::glLoadMatrixf(m);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glLoadMatrixx()
+{
+    GLfixed *m;
+
+    TInt size0;
+    m_currentFunctionCall.GetVectorData(m, size0, 0);
+
+    ::glLoadMatrixx(m);
+    return WriteReply();
+}
+int OGLES11Wrapper::glLogicOp()
+{
+    GLenum opcode;
+
+    m_currentFunctionCall.GetParamValue(opcode, 0);
+
+    ::glLogicOp(opcode);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMaterialf()
+{
+    GLenum face;
+    GLenum pname;
+    GLfloat param;
+
+    m_currentFunctionCall.GetParamValue(face, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+
+    ::glMaterialf(face, pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMaterialfv()
+{
+    GLenum face;
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(face, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    ::glMaterialfv(face, pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMaterialx()
+{
+    GLenum face;
+    GLenum pname;
+    GLfixed param;
+
+    m_currentFunctionCall.GetParamValue(face, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+
+    ::glMaterialx(face, pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMaterialxv()
+{
+    GLenum face;
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(face, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    TInt size2;
+    m_currentFunctionCall.GetVectorData(params, size2, 2);
+
+    ::glMaterialxv(face, pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMatrixMode()
+{
+    GLenum mode;
+
+    m_currentFunctionCall.GetParamValue(mode, 0);
+
+    ::glMatrixMode(mode);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMultMatrixf()
+{
+    GLfloat *m;
+
+    TInt size0;
+    m_currentFunctionCall.GetVectorData(m, size0, 0);
+
+    ::glMultMatrixf(m);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMultMatrixx()
+{
+    GLfixed *m;
+
+    TInt size0;
+    m_currentFunctionCall.GetVectorData(m, size0, 0);
+
+    ::glMultMatrixx(m);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMultiTexCoord4f()
+{
+    GLenum target;
+    GLfloat s;
+    GLfloat t;
+    GLfloat r;
+    GLfloat q;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(s, 1);
+    m_currentFunctionCall.GetParamValue(t, 2);
+    m_currentFunctionCall.GetParamValue(r, 3);
+    m_currentFunctionCall.GetParamValue(q, 4);
+
+    ::glMultiTexCoord4f(target, s, t, r, q);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glMultiTexCoord4x()
+{
+    GLenum target;
+    GLfixed s;
+    GLfixed t;
+    GLfixed r;
+    GLfixed q;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(s, 1);
+    m_currentFunctionCall.GetParamValue(t, 2);
+    m_currentFunctionCall.GetParamValue(r, 3);
+    m_currentFunctionCall.GetParamValue(q, 4);
+
+    ::glMultiTexCoord4x(target, s, t, r, q);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glNormal3f()
+{
+    GLfloat nx;
+    GLfloat ny;
+    GLfloat nz;
+
+    m_currentFunctionCall.GetParamValue(nx, 0);
+    m_currentFunctionCall.GetParamValue(ny, 1);
+    m_currentFunctionCall.GetParamValue(nz, 2);
+
+    ::glNormal3f(nx, ny, nz);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glNormal3x()
+{
+    GLfixed nx;
+    GLfixed ny;
+    GLfixed nz;
+
+    m_currentFunctionCall.GetParamValue(nx, 0);
+    m_currentFunctionCall.GetParamValue(ny, 1);
+    m_currentFunctionCall.GetParamValue(nz, 2);
+
+    ::glNormal3x(nx, ny, nz);
+
+    return WriteReply();
+}
+
+int OGLES11Wrapper::glOrthof()
+{
+    GLfloat left;
+    GLfloat right;
+    GLfloat bottom;
+    GLfloat top;
+    GLfloat zNear;
+    GLfloat zFar;
+
+    m_currentFunctionCall.GetParamValue(left, 0);
+    m_currentFunctionCall.GetParamValue(right, 1);
+    m_currentFunctionCall.GetParamValue(bottom, 2);
+    m_currentFunctionCall.GetParamValue(top, 3);
+    m_currentFunctionCall.GetParamValue(zNear, 4);
+    m_currentFunctionCall.GetParamValue(zFar, 5);
+
+    ::glOrthof(left, right, bottom, top, zNear, zFar);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glOrthox()
+{
+    GLfixed left;
+    GLfixed right;
+    GLfixed bottom;
+    GLfixed top;
+    GLfixed zNear;
+    GLfixed zFar;
+
+    m_currentFunctionCall.GetParamValue(left, 0);
+    m_currentFunctionCall.GetParamValue(right, 1);
+    m_currentFunctionCall.GetParamValue(bottom, 2);
+    m_currentFunctionCall.GetParamValue(top, 3);
+    m_currentFunctionCall.GetParamValue(zNear, 4);
+    m_currentFunctionCall.GetParamValue(zFar, 5);
+
+    ::glOrthox(left, right, bottom, top, zNear, zFar);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPixelStorei()
+{
+    GLenum pname;
+    GLint param;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    m_currentFunctionCall.GetParamValue(param, 1);
+
+    ::glPixelStorei(pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPointParameterf()
+{
+    GLenum pname;
+    GLfloat param;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    m_currentFunctionCall.GetParamValue(param, 1);
+
+    ::glPointParameterf(pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPointParameterfv()
+{
+    GLenum pname;
+    GLfloat *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    ::glPointParameterfv(pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPointParameterx()
+{
+    GLenum pname;
+    GLfixed param;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    m_currentFunctionCall.GetParamValue(param, 1);
+
+    ::glPointParameterx(pname, param);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPointParameterxv()
+{
+    GLenum pname;
+    GLfixed *params;
+
+    m_currentFunctionCall.GetParamValue(pname, 0);
+    TInt size1;
+    m_currentFunctionCall.GetVectorData(params, size1, 1);
+
+    ::glPointParameterxv(pname, params);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPointSize()
+{
+    GLfloat size;
+
+    m_currentFunctionCall.GetParamValue(size, 0);
+
+    ::glPointSize(size);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPointSizex()
+{
+    GLfixed size;
+
+    m_currentFunctionCall.GetParamValue(size, 0);
+
+    ::glPointSizex(size);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPolygonOffset()
+{
+    GLfloat factor;
+    GLfloat units;
+
+    m_currentFunctionCall.GetParamValue(factor, 0);
+    m_currentFunctionCall.GetParamValue(units, 1);
+
+    ::glPolygonOffset(factor, units);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPolygonOffsetx()
+{
+    GLfixed factor;
+    GLfixed units;
+
+    m_currentFunctionCall.GetParamValue(factor, 0);
+    m_currentFunctionCall.GetParamValue(units, 1);
+
+    ::glPolygonOffsetx(factor, units);
+
+    return WriteReply();
+}
+int OGLES11Wrapper::glPopMatrix()
+{
+    ::glPopMatrix();
+    return WriteReply();
+}
+int OGLES11Wrapper::glPushMatrix()
+{
+    ::glPushMatrix();
+    return WriteReply();
+}
+int OGLES11Wrapper::glReadPixels()
+{
+    GLint x;
+    GLint y;
+    GLsizei width;
+    GLsizei height;
+    GLenum format;
+    GLenum type;
+    GLvoid *pixels;
+
+    m_currentFunctionCall.GetParamValue(x, 0);
+    m_currentFunctionCall.GetParamValue(y, 1);
+    m_currentFunctionCall.GetParamValue(width, 2);
+    m_currentFunctionCall.GetParamValue(height, 3);
+    m_currentFunctionCall.GetParamValue(format, 4);
+    m_currentFunctionCall.GetParamValue(type, 5);
+    TInt size6;
+    m_currentFunctionCall.GetVectorData(pixels, size6, 6);
+
+    pixels = (GLvoid*)iStack->AllocFromStack( size6*m_currentFunctionCall.GetTypeSize( OpenGlES11RFC::EGLvoid ),
+        m_currentFunctionCall.GetTypeAlignment( OpenGlES11RFC::EGLvoid ) );
+
+    ::glReadPixels(x, y, width, height, format, type, pixels);
+
+    m_currentFunctionCall.SetVectorData( pixels, size6, 6 ); // EOut    
+
+    int ret = WriteReply();
+    iStack->ClearStack();
+    pixels = NULL;
+    return ret;
+}
+int OGLES11Wrapper::glRotatef()
+{
+    GLfloat angle, x, y, z;
+    m_currentFunctionCall.GetParamValue(angle, 0);
+    m_currentFunctionCall.GetParamValue(x, 1);
+    m_currentFunctionCall.GetParamValue(y, 2);
+    m_currentFunctionCall.GetParamValue(z, 3);
+    ::glRotatef(angle, x, y, z);
+    return WriteReply();
+}
+int OGLES11Wrapper::glRotatex()
+{
+    GLfixed angle, x, y, z;
+    m_currentFunctionCall.GetParamValue(angle, 0);
+    m_currentFunctionCall.GetParamValue(x, 1);
+    m_currentFunctionCall.GetParamValue(y, 2);
+    m_currentFunctionCall.GetParamValue(z, 3);
+    ::glRotatex(angle, x, y, z);
+    return WriteReply();
+}
+int OGLES11Wrapper::glSampleCoverage()
+{
+    GLclampf value;
+    GLboolean invert;
+    m_currentFunctionCall.GetParamValue(value, 0);
+    m_currentFunctionCall.GetParamValue(invert, 1);
+    ::glSampleCoverage(value, invert);
+    return WriteReply();
+}
+int OGLES11Wrapper::glSampleCoveragex()
+{
+    GLclampx value;
+    GLboolean invert;
+    m_currentFunctionCall.GetParamValue(value, 0);
+    m_currentFunctionCall.GetParamValue(invert, 1);
+    ::glSampleCoveragex(value, invert);
+    return WriteReply();
+}
+int OGLES11Wrapper::glScalef()
+{
+    GLfloat x, y, z;
+    m_currentFunctionCall.GetParamValue(x, 0);
+    m_currentFunctionCall.GetParamValue(y, 1);
+    m_currentFunctionCall.GetParamValue(z, 2);
+    ::glScalef(x, y, z);
+    return WriteReply();
+}
+int OGLES11Wrapper::glScalex()
+{
+    GLfixed x, y, z;
+    m_currentFunctionCall.GetParamValue(x, 0);
+    m_currentFunctionCall.GetParamValue(y, 1);
+    m_currentFunctionCall.GetParamValue(z, 2);
+    ::glScalex(x, y, z);
+    return WriteReply();
+}
+int OGLES11Wrapper::glScissor()
+{
+    GLint x, y;
+    GLsizei width, height;
+    m_currentFunctionCall.GetParamValue(x, 0);
+    m_currentFunctionCall.GetParamValue(y, 1);
+    m_currentFunctionCall.GetParamValue(width, 2);
+    m_currentFunctionCall.GetParamValue(height, 3);
+    ::glScissor(x, y, width, height);
+    return WriteReply();
+}
+int OGLES11Wrapper::glShadeModel()
+{
+    GLenum mode;
+    m_currentFunctionCall.GetParamValue(mode, 0);
+    ::glShadeModel(mode);
+    return WriteReply();
+}
+int OGLES11Wrapper::glStencilFunc()
+{
+    GLenum func;
+    GLint ref;
+    GLuint mask;
+    m_currentFunctionCall.GetParamValue(func, 0);
+    m_currentFunctionCall.GetParamValue(ref, 1);
+    m_currentFunctionCall.GetParamValue(mask, 2);
+    ::glStencilFunc(func, ref, mask);
+    return WriteReply();
+}
+int OGLES11Wrapper::glStencilMask()
+{
+    GLuint mask;
+    m_currentFunctionCall.GetParamValue(mask, 0);
+    ::glStencilMask(mask);
+    return WriteReply();
+}
+int OGLES11Wrapper::glStencilOp()
+{
+    GLenum fail, zfail, zpass;
+    m_currentFunctionCall.GetParamValue(fail, 0);
+    m_currentFunctionCall.GetParamValue(zfail, 1);
+    m_currentFunctionCall.GetParamValue(zpass, 2);
+    ::glStencilOp (fail, zfail, zpass);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexEnvf()
+{
+    GLenum target, pname;
+    GLfloat param;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+    ::glTexEnvf(target, pname, param);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexEnvfv()
+{
+    GLenum target, pname;
+    GLfloat *params;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+
+    TInt size;
+    m_currentFunctionCall.GetVectorData(params, size, 2);
+
+    ::glTexEnvfv(target, pname, params);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexEnvi()
+{
+    GLenum target, pname;
+    GLint param;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+    ::glTexEnvi(target, pname, param);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexEnviv()
+{
+    GLenum target, pname;
+    GLint *params;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+
+    TInt size;
+    m_currentFunctionCall.GetVectorData(params, size, 2);
+
+    ::glTexEnviv(target, pname, params);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexEnvx()
+{
+    GLenum target, pname;
+    GLfixed param;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+    ::glTexEnvx(target, pname, param);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexEnvxv()
+{
+    GLenum target, pname;
+    GLfixed *params;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+
+    TInt size;
+    m_currentFunctionCall.GetVectorData(params, size, 2);
+
+    ::glTexEnvxv(target, pname, params);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexImage2D()
+{
+    GLenum target;
+    GLint level;
+    GLint internalformat;
+    GLsizei width;
+    GLsizei height;
+    GLint border;
+    GLenum format;
+    GLenum type;
+    GLvoid *pixels;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(level, 1);
+    m_currentFunctionCall.GetParamValue(internalformat, 2);
+    m_currentFunctionCall.GetParamValue(width, 3);
+    m_currentFunctionCall.GetParamValue(height, 4);
+    m_currentFunctionCall.GetParamValue(border, 5);
+    m_currentFunctionCall.GetParamValue(format, 6);
+    m_currentFunctionCall.GetParamValue(type, 7);
+
+    TInt size;
+    m_currentFunctionCall.GetVectorData(pixels, size, 8);
+
+    ::glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexParameterf()
+{
+    GLenum target, pname;
+    GLfloat param;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+    ::glTexParameterf(target, pname, param);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexParameterfv()
+{
+    GLenum target, pname;
+    GLfloat *params;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+
+    TInt size;
+    m_currentFunctionCall.GetVectorData(params, size, 2);
+
+    ::glTexParameterfv(target, pname, params);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexParameteri()
+{
+    GLenum target, pname;
+    GLint param;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+    ::glTexParameteri(target, pname, param);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexParameteriv()
+{
+    GLenum target, pname;
+    GLint *params;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+
+    TInt size;
+    m_currentFunctionCall.GetVectorData(params, size, 2);
+
+    ::glTexParameteriv(target, pname, params);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexParameterx()
+{
+    GLenum target, pname;
+    GLfixed param;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+    m_currentFunctionCall.GetParamValue(param, 2);
+    ::glTexParameterx(target, pname, param);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexParameterxv()
+{
+    GLenum target, pname;
+    GLfixed *params;
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(pname, 1);
+
+    TInt size;
+    m_currentFunctionCall.GetVectorData(params, size, 2);
+
+    ::glTexParameterxv(target, pname, params);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTexSubImage2D()
+{
+    GLenum target;
+    GLint level;
+    GLint xoffset;
+    GLint yoffset;
+    GLsizei width;
+    GLsizei height;
+    GLenum format;
+    GLenum type;
+    GLvoid *pixels;
+
+    m_currentFunctionCall.GetParamValue(target, 0);
+    m_currentFunctionCall.GetParamValue(level, 1);
+    m_currentFunctionCall.GetParamValue(xoffset, 2);
+    m_currentFunctionCall.GetParamValue(yoffset, 3);
+    m_currentFunctionCall.GetParamValue(width, 4);
+    m_currentFunctionCall.GetParamValue(height, 5);
+    m_currentFunctionCall.GetParamValue(format, 6);
+    m_currentFunctionCall.GetParamValue(type, 7);
+    TInt size8;
+    m_currentFunctionCall.GetVectorData(pixels, size8, 8);
+
+    ::glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTranslatef()
+{
+    GLfloat x, y, z;
+    m_currentFunctionCall.GetParamValue(x, 0);
+    m_currentFunctionCall.GetParamValue(y, 1);
+    m_currentFunctionCall.GetParamValue(z, 2);
+    ::glTranslatef(x, y, z);
+    return WriteReply();
+}
+int OGLES11Wrapper::glTranslatex()
+{
+    GLfixed x, y, z;
+    m_currentFunctionCall.GetParamValue(x, 0);
+    m_currentFunctionCall.GetParamValue(y, 1);
+    m_currentFunctionCall.GetParamValue(z, 2);
+    ::glTranslatex(x, y, z);
+    return WriteReply();
+}
+int OGLES11Wrapper::glViewport()
+{
+    GLint x, y;
+    GLsizei width, height;
+    m_currentFunctionCall.GetParamValue(x, 0);
+    m_currentFunctionCall.GetParamValue(y, 1);
+    m_currentFunctionCall.GetParamValue(width, 2);
+    m_currentFunctionCall.GetParamValue(height, 3);
+    ::glViewport(x, y, width, height);
+    return WriteReply();
+}
+int OGLES11Wrapper::glCurrentPaletteMatrixOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glDrawTexfOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glDrawTexfvOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glDrawTexiOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glDrawTexivOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glDrawTexsOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glDrawTexsvOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glDrawTexxOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glDrawTexxvOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glLoadPaletteFromModelViewMatrixOES()
+{
+    return 0;
+}
+int OGLES11Wrapper::glQueryMatrixxOES()
+{
+    return 0;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/src/openvgapiwrapper.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,2173 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// 
+
+#ifdef WIN32
+#define WIN32_LEAN_AND_MEAN                       // Exclude rarely-used stuff from Windows headers
+#include <windows.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <vg/openvg.h>
+#include <EGL/egl.h>
+#include "KhronosAPIWrapper.h"
+#include "serializedfunctioncall.h"
+#include "remotefunctioncall.h"
+#include "openvgrfc.h"
+#include "graphicsvhwcallback.h"        //callback interface Wrapper=>Virtual HW
+#include "serialisedapiuids.h"
+#include "openvgapiwrapper.h"
+#include "khronosapiwrapperdefs.h"
+#include "driverapiwrapper.h" //For calling the sync functions
+
+int OpenVGAPIWrapper::vgePathCoordsSizeInBytes()
+{
+    VGPath dstPath;
+    m_currentFunctionCall.GetParamValue( dstPath, 0 );
+    VGint startIndex;
+    m_currentFunctionCall.GetParamValue( startIndex, 1 );
+    VGint numSegments;
+    m_currentFunctionCall.GetParamValue( numSegments, 2 );
+    if ( !vgePathCoordsSizeInBytesPtr )
+        {
+        vgePathCoordsSizeInBytesPtr = (vgePathCoordsSizeInBytesPtrType)::eglGetProcAddress("vgePathCoordsSizeInBytes");
+        }
+	if ( vgePathCoordsSizeInBytesPtr )
+	{
+		VGint ret = vgePathCoordsSizeInBytesPtr( dstPath, startIndex, numSegments );
+		m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+	}
+	else
+	{
+		m_currentFunctionCall.SetReturnValue( (TUint32)(-1) );
+	}
+
+    return WriteReply();
+}
+
+int OpenVGAPIWrapper::vgCreatePaint()
+{
+    VGPaint paint = ::vgCreatePaint();
+    m_currentFunctionCall.SetReturnValue((TUint32)paint);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgDestroyPaint()
+{
+    VGPaint paint;
+    m_currentFunctionCall.GetParamValue( paint, 0 );
+    ::vgDestroyPaint( paint );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetPaint()
+{
+    VGPaint paint;
+    m_currentFunctionCall.GetParamValue( paint, 0 );
+    VGbitfield paintModes;
+    m_currentFunctionCall.GetParamValue( paintModes, 1 );
+    ::vgSetPaint(paint, paintModes);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetParameteri()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGint value;
+    m_currentFunctionCall.GetParamValue( value, 2 );
+    ::vgSetParameteri(object, paramType, value);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetParameterf()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGfloat value;
+    m_currentFunctionCall.GetParamValue( value, 2 );
+    ::vgSetParameterf(object, paramType, value);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetParameterfv()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGint count;
+    m_currentFunctionCall.GetParamValue( count, 2 );
+    VGfloat * values;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( values, size, 3 );
+
+    ::vgSetParameterfv(object, paramType, count, values);
+    return WriteReply();
+}
+
+int OpenVGAPIWrapper::vgCreatePath()
+{
+    VGint pathFormat;
+    m_currentFunctionCall.GetParamValue( pathFormat, 0 );
+
+    VGPathDatatype datatype;
+    m_currentFunctionCall.GetParamValue( datatype, 1 );
+
+    VGfloat scale;
+    m_currentFunctionCall.GetParamValue( scale, 2 );
+
+    VGfloat bias;
+    m_currentFunctionCall.GetParamValue( bias, 3 );
+
+    VGint segmentCapacityHint;
+    m_currentFunctionCall.GetParamValue( segmentCapacityHint, 4 );
+
+    VGint coordCapacityHint;
+    m_currentFunctionCall.GetParamValue( coordCapacityHint, 5 );
+
+    VGbitfield capabilities;
+    m_currentFunctionCall.GetParamValue( capabilities, 6 );
+
+    VGPath path = ::vgCreatePath( pathFormat, datatype, scale, bias, segmentCapacityHint, coordCapacityHint, capabilities);
+    m_currentFunctionCall.SetReturnValue((TUint32)path);
+    return WriteReply();
+
+}
+
+int OpenVGAPIWrapper::vgDrawPath()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+
+    VGbitfield paintModes;
+    m_currentFunctionCall.GetParamValue( paintModes, 1 );
+
+    ::vgDrawPath( path, paintModes );
+    return WriteReply();
+}
+
+int OpenVGAPIWrapper::vgDestroyPath()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+
+    ::vgDestroyPath(path);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgAppendPathData()
+{
+    VGPath dstPath;
+    m_currentFunctionCall.GetParamValue( dstPath, 0 );
+    VGint numSegments;
+    m_currentFunctionCall.GetParamValue( numSegments, 1 );
+    VGubyte * pathSegments;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( pathSegments, size, 2 );
+
+    void * pathData;
+    m_currentFunctionCall.GetVectorData( pathData, size, 3 );
+
+    ::vgAppendPathData( dstPath, numSegments, pathSegments, pathData );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetError()
+{
+    VGErrorCode error = ::vgGetError();
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSeti()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGint value;
+    m_currentFunctionCall.GetParamValue( value, 1 );
+    ::vgSeti( type, value);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetf()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGfloat value;
+    m_currentFunctionCall.GetParamValue( value, 1 );
+    ::vgSetf( type, value );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetfv()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGint count;
+    m_currentFunctionCall.GetParamValue( count, 1 );
+    VGfloat * values;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( values, size, 2 );
+    ::vgSetfv( type, count, values);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgClear()
+{
+    VGint x;
+    m_currentFunctionCall.GetParamValue( x, 0 );
+    VGint y;
+    m_currentFunctionCall.GetParamValue( y, 1 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 2 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 3 );
+    ::vgClear( x, y, width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgLoadIdentity()
+{
+    ::vgLoadIdentity();
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgRotate()
+{
+    VGfloat angle;
+    m_currentFunctionCall.GetParamValue( angle, 0 );
+    ::vgRotate( angle );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgScale()
+{
+    VGfloat sx;
+    m_currentFunctionCall.GetParamValue( sx, 0 );
+    VGfloat sy;
+    m_currentFunctionCall.GetParamValue( sy, 1 );
+    ::vgScale( sx, sy );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgTranslate()
+{
+    VGfloat tx;
+    m_currentFunctionCall.GetParamValue( tx, 0 );
+    VGfloat ty;
+    m_currentFunctionCall.GetParamValue( ty, 1 );
+    ::vgTranslate( tx, ty );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgReadPixels()
+{
+    VGint dataStride;
+    m_currentFunctionCall.GetParamValue( dataStride, 1 );
+    VGImageFormat dataFormat;
+    m_currentFunctionCall.GetParamValue( dataFormat, 2 );
+    VGint sx;
+    m_currentFunctionCall.GetParamValue( sx, 3 );
+    VGint sy;
+    m_currentFunctionCall.GetParamValue( sy, 4 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 5 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 6 );
+	VGint pixmapSize;
+	m_currentFunctionCall.GetParamValue(pixmapSize, 7);
+
+    void *dataBuffer = iStack->AllocFromStack(pixmapSize, 4);
+
+    ::vgReadPixels( dataBuffer, dataStride, dataFormat, sx, sy, width, height );
+    m_currentFunctionCall.SetVectorData( dataBuffer, pixmapSize, 0 );
+    int ret = WriteReply();
+    iStack->ClearStack();
+    dataBuffer = NULL;
+    return ret;
+}
+
+
+int OpenVGAPIWrapper::vgFlush()
+{
+    ::vgFlush();
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgFinish()
+{
+    ::vgFinish();
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetiv()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGint count;
+    m_currentFunctionCall.GetParamValue( count, 1 );
+    VGint * values;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( values, size, 2 );
+    ::vgSetiv( type, count, values);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetf()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGfloat ret = ::vgGetf( type );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGeti()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGint ret = ::vgGeti( type );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetVectorSize()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGint ret = ::vgGetVectorSize( type );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetParameterf()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGfloat ret = ::vgGetParameterf( object, paramType );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetParameteri()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGint ret = ::vgGetParameteri( object, paramType );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetParameterVectorSize()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGint ret = ::vgGetParameterVectorSize( object, paramType );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgShear()
+{
+    VGfloat shx;
+    m_currentFunctionCall.GetParamValue( shx, 0 );
+    VGfloat shy;
+    m_currentFunctionCall.GetParamValue( shy, 1 );
+    ::vgShear( shx, shy );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgMask()
+{
+    VGHandle mask;
+    m_currentFunctionCall.GetParamValue( mask, 0 );
+    VGMaskOperation operation;
+    m_currentFunctionCall.GetParamValue( operation, 1 );
+    VGint x;
+    m_currentFunctionCall.GetParamValue( x, 2 );
+    VGint y;
+    m_currentFunctionCall.GetParamValue( y, 3 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 4 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 5 );
+
+    ::vgMask( mask, operation, x, y, width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgRenderToMask()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    VGbitfield paintModes;
+    m_currentFunctionCall.GetParamValue( paintModes, 1 );
+    VGMaskOperation operation;
+    m_currentFunctionCall.GetParamValue( operation, 2 );
+
+    ::vgRenderToMask( path, paintModes, operation);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgCreateMaskLayer()
+{
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 0 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 1 );
+    ::vgCreateMaskLayer( width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgDestroyMaskLayer()
+{
+    VGMaskLayer maskLayer;
+    m_currentFunctionCall.GetParamValue( maskLayer, 0 );
+    ::vgDestroyMaskLayer( maskLayer );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgFillMaskLayer()
+{
+    VGMaskLayer maskLayer;
+    m_currentFunctionCall.GetParamValue( maskLayer, 0 );
+    VGint x;
+    m_currentFunctionCall.GetParamValue( x, 1 );
+    VGint y;
+    m_currentFunctionCall.GetParamValue( y, 2 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 3 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 4 );
+    VGfloat value;
+    m_currentFunctionCall.GetParamValue( value, 5 );
+
+    ::vgFillMaskLayer( maskLayer, x, y,
+        width, height, value );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgCopyMask()
+{
+    VGMaskLayer maskLayer;
+    m_currentFunctionCall.GetParamValue( maskLayer, 0 );
+    VGint sx;
+    m_currentFunctionCall.GetParamValue( sx, 1 );
+    VGint sy;
+    m_currentFunctionCall.GetParamValue( sy, 2 );
+    VGint dx;
+    m_currentFunctionCall.GetParamValue( dx, 3 );
+    VGint dy;
+    m_currentFunctionCall.GetParamValue( dy, 4 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 5 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 6 );
+
+    ::vgCopyMask( maskLayer, sx, sy, dx, dy,
+        width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgClearPath()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    VGbitfield capabilities;
+    m_currentFunctionCall.GetParamValue( capabilities, 1 );
+
+    ::vgClearPath( path, capabilities );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgRemovePathCapabilities()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    VGbitfield capabilities;
+    m_currentFunctionCall.GetParamValue( capabilities, 1 );
+    ::vgRemovePathCapabilities( path, capabilities );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetPathCapabilities()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    VGbitfield ret = ::vgGetPathCapabilities( path );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgAppendPath()
+{
+    VGPath dstPath;
+    m_currentFunctionCall.GetParamValue( dstPath, 0 );
+    VGPath srcPath;
+    m_currentFunctionCall.GetParamValue( srcPath, 1 );
+    ::vgAppendPath( dstPath, srcPath );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgTransformPath()
+{
+    VGPath dstPath;
+    m_currentFunctionCall.GetParamValue( dstPath, 0 );
+    VGPath srcPath;
+    m_currentFunctionCall.GetParamValue( srcPath, 1 );
+    ::vgTransformPath( dstPath, srcPath );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgInterpolatePath()
+{
+    VGPath dstPath;
+    m_currentFunctionCall.GetParamValue( dstPath, 0 );
+    VGPath startPath;
+    m_currentFunctionCall.GetParamValue( startPath, 1 );
+    VGPath endPath;
+    m_currentFunctionCall.GetParamValue( endPath, 2 );
+    VGfloat amount;
+    m_currentFunctionCall.GetParamValue( amount, 3 );
+
+    ::vgInterpolatePath( dstPath, startPath, endPath, amount );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgPathLength()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    VGint startSegment;
+    m_currentFunctionCall.GetParamValue( startSegment, 1 );
+    VGint numSegments;
+    m_currentFunctionCall.GetParamValue( numSegments, 2 );
+
+    VGfloat ret = ::vgPathLength( path, startSegment, numSegments );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetPaint()
+{
+    VGPaintMode paintMode;
+    m_currentFunctionCall.GetParamValue( paintMode, 0 );
+    VGPaint ret = ::vgGetPaint( paintMode );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetColor()
+{
+    VGPaint paint;
+    m_currentFunctionCall.GetParamValue( paint, 0 );
+    VGuint rgba;
+    m_currentFunctionCall.GetParamValue( rgba, 1 );
+
+    ::vgSetColor( paint, rgba );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetColor()
+{
+    VGPaint paint;
+    m_currentFunctionCall.GetParamValue( paint, 0 );
+    VGuint ret = ::vgGetColor( paint );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgPaintPattern()
+{
+    VGPaint paint;
+    m_currentFunctionCall.GetParamValue( paint, 0 );
+    VGImage pattern;
+    m_currentFunctionCall.GetParamValue( pattern, 1 );
+
+    ::vgPaintPattern( paint, pattern );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgCreateImage()
+{
+    VGImageFormat format;
+    m_currentFunctionCall.GetParamValue( format, 0 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 1 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 2 );
+    VGbitfield allowedQuality;
+    m_currentFunctionCall.GetParamValue( allowedQuality, 3 );
+
+    VGImage ret = ::vgCreateImage( format, width, height, allowedQuality );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgDestroyImage()
+{
+    VGImage image;
+    m_currentFunctionCall.GetParamValue( image, 0 );
+    ::vgDestroyImage( image );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgClearImage()
+{
+    VGImage image;
+    m_currentFunctionCall.GetParamValue( image, 0 );
+    VGint x;
+    m_currentFunctionCall.GetParamValue( x, 1 );
+    VGint y;
+    m_currentFunctionCall.GetParamValue( y, 2 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 3 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 4 );
+
+	doSync( 5, image );
+
+    ::vgClearImage( image, x, y, width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgChildImage()
+{
+    VGImage parent;
+    m_currentFunctionCall.GetParamValue( parent, 0 );
+    VGint x;
+    m_currentFunctionCall.GetParamValue( x, 1 );
+    VGint y;
+    m_currentFunctionCall.GetParamValue( y, 2 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 3 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 4 );
+    VGImage ret = ::vgChildImage( parent, x, y, width, height );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetParent()
+{
+    VGImage image;
+    m_currentFunctionCall.GetParamValue( image, 0 );
+    VGImage ret = ::vgGetParent( image );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgCopyImage()
+{
+    VGImage dst;
+    m_currentFunctionCall.GetParamValue( dst, 0 );
+    VGint dx;
+    m_currentFunctionCall.GetParamValue( dx, 1 );
+    VGint dy;
+    m_currentFunctionCall.GetParamValue( dy, 2 );
+    VGImage src;
+    m_currentFunctionCall.GetParamValue( src, 3 );
+    VGint sx;
+    m_currentFunctionCall.GetParamValue( sx, 4 );
+    VGint sy;
+    m_currentFunctionCall.GetParamValue( sy, 5 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 6 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 7 );
+    VGboolean dither;
+    m_currentFunctionCall.GetParamValue( dither, 8 );
+
+	doSync( 9, dst, src );
+
+    ::vgCopyImage( dst, dx, dy, src, sx, sy, width, height, dither );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgDrawImage()
+{
+    VGImage image;
+    m_currentFunctionCall.GetParamValue( image, 0 );
+
+
+    ::vgDrawImage( image );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetPixels()
+{
+    VGint dx;
+    m_currentFunctionCall.GetParamValue( dx, 0 );
+    VGint dy;
+    m_currentFunctionCall.GetParamValue( dy, 1 );
+    VGImage src;
+    m_currentFunctionCall.GetParamValue( src, 2 );
+    VGint sx;
+    m_currentFunctionCall.GetParamValue( sx, 3 );
+    VGint sy;
+    m_currentFunctionCall.GetParamValue( sy, 4 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 5 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 6 );
+
+	doSync( 7, src );
+
+    ::vgSetPixels( dx, dy, src, sx, sy, width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetPixels()
+{
+    VGImage dst;
+    m_currentFunctionCall.GetParamValue( dst, 0 );
+    VGint dx;
+    m_currentFunctionCall.GetParamValue( dx, 1 );
+    VGint dy;
+    m_currentFunctionCall.GetParamValue( dy, 2 );
+    VGint sx;
+    m_currentFunctionCall.GetParamValue( sx, 3 );
+    VGint sy;
+    m_currentFunctionCall.GetParamValue( sy, 4 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 5 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 6 );
+
+	doSync( 7, dst );
+
+    ::vgGetPixels( dst, dx, dy, sx, sy, width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgCopyPixels()
+{
+    VGint dx;
+    m_currentFunctionCall.GetParamValue( dx, 0 );
+    VGint dy;
+    m_currentFunctionCall.GetParamValue( dy, 1 );
+    VGint sx;
+    m_currentFunctionCall.GetParamValue( sx, 2 );
+    VGint sy;
+    m_currentFunctionCall.GetParamValue( sy, 3 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 4 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 5 );
+
+    ::vgCopyPixels( dx, dy, sx, sy, width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgCreateFont()
+{
+    VGint glyphCapacityHint;
+    m_currentFunctionCall.GetParamValue( glyphCapacityHint, 0 );
+    VGFont ret = ::vgCreateFont( glyphCapacityHint );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgDestroyFont()
+{
+    VGFont font;
+    m_currentFunctionCall.GetParamValue( font, 0 );
+    ::vgDestroyFont( font );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgClearGlyph()
+{
+    VGFont font;
+    m_currentFunctionCall.GetParamValue( font, 0 );
+    VGuint glyphIndex;
+    m_currentFunctionCall.GetParamValue( glyphIndex, 1 );
+    ::vgClearGlyph( font, glyphIndex );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgDrawGlyph()
+{
+    VGFont font;
+    m_currentFunctionCall.GetParamValue( font, 0 );
+
+    VGuint glyphIndex;
+    m_currentFunctionCall.GetParamValue( glyphIndex, 1 );
+
+    VGbitfield paintModes;
+    m_currentFunctionCall.GetParamValue( paintModes, 2 );
+
+    VGboolean allowAutoHinting;
+    m_currentFunctionCall.GetParamValue( allowAutoHinting, 3 );
+
+    ::vgDrawGlyph( font, glyphIndex, paintModes, allowAutoHinting );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGaussianBlur()
+{
+    VGImage dst;
+    m_currentFunctionCall.GetParamValue( dst, 0 );
+    VGImage src;
+    m_currentFunctionCall.GetParamValue( src, 1 );
+    VGfloat stdDeviationX;
+    m_currentFunctionCall.GetParamValue( stdDeviationX, 2 );
+    VGfloat stdDeviationY;
+    m_currentFunctionCall.GetParamValue( stdDeviationY, 3 );
+    VGTilingMode tilingMode;
+    m_currentFunctionCall.GetParamValue( tilingMode, 4 );
+
+	doSync( 5, dst, src );
+
+    ::vgGaussianBlur( dst, src, stdDeviationX, stdDeviationY, tilingMode );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgHardwareQuery()
+{
+    VGHardwareQueryType key;
+    m_currentFunctionCall.GetParamValue( key, 0 );
+    VGint setting;
+    m_currentFunctionCall.GetParamValue( setting, 1 );
+    VGHardwareQueryResult ret =::vgHardwareQuery( key, setting );
+    m_currentFunctionCall.SetReturnValue( (TUint32)ret );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgWritePixels()
+{
+    void* data;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( data, size, 0 );
+    VGint dataStride;
+    m_currentFunctionCall.GetParamValue( dataStride, 1 );
+    VGImageFormat dataFormat;
+    m_currentFunctionCall.GetParamValue( dataFormat, 2 );
+    VGint dx;
+    m_currentFunctionCall.GetParamValue( dx, 3 );
+    VGint dy;
+    m_currentFunctionCall.GetParamValue( dy, 4 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 5 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 6 );
+
+    ::vgWritePixels( data, dataStride, dataFormat, dx, dy, width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgImageSubData()
+{
+    VGImage image;
+    m_currentFunctionCall.GetParamValue( image, 0 );
+    void* data;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( data, size, 1 );
+    VGint dataStride;
+    m_currentFunctionCall.GetParamValue( dataStride, 2 );
+    VGImageFormat dataFormat;
+    m_currentFunctionCall.GetParamValue( dataFormat, 3 );
+    VGint x;
+    m_currentFunctionCall.GetParamValue( x, 4 );
+    VGint y;
+    m_currentFunctionCall.GetParamValue( y, 5 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 6 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 7 );
+
+	doSync( 8, image );
+
+    ::vgImageSubData( image, data, dataStride, dataFormat, x, y, width, height );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetParameteriv()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGint count;
+    m_currentFunctionCall.GetParamValue( count, 2 );
+    VGint * values;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( values, size, 3 );
+
+    ::vgSetParameteriv( object, paramType, count, values );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgLoadMatrix()
+{
+    VGfloat * m;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( m, size, 0 );
+    ::vgLoadMatrix( m );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgMultMatrix()
+{
+    VGfloat * m;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( m, size, 0 );
+    ::vgMultMatrix( m );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgModifyPathCoords()
+{
+    VGPath dstPath;
+    m_currentFunctionCall.GetParamValue( dstPath, 0 );
+    VGint startIndex;
+    m_currentFunctionCall.GetParamValue( startIndex, 1 );
+    VGint numSegments;
+    m_currentFunctionCall.GetParamValue( numSegments, 2 );
+    void * pathData;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( pathData, size, 3 );
+
+    ::vgModifyPathCoords( dstPath, startIndex, numSegments, pathData);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetGlyphToPath()
+{
+    VGFont font;
+    m_currentFunctionCall.GetParamValue( font, 0 );
+    VGuint glyphIndex;
+    m_currentFunctionCall.GetParamValue( glyphIndex, 1 );
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 2 );
+    VGboolean isHinted;
+    m_currentFunctionCall.GetParamValue( isHinted, 3 );
+    VGfloat* glyphOrigin;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( glyphOrigin, size, 4 );
+    VGfloat* escapement;
+    m_currentFunctionCall.GetVectorData( escapement, size, 5 );
+
+    ::vgSetGlyphToPath( font, glyphIndex, path, isHinted, glyphOrigin, escapement );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSetGlyphToImage()
+{
+    VGFont font;
+    m_currentFunctionCall.GetParamValue( font, 0 );
+    VGuint glyphIndex;
+    m_currentFunctionCall.GetParamValue( glyphIndex, 1 );
+    VGImage image;
+    m_currentFunctionCall.GetParamValue( image, 2 );
+    VGfloat* glyphOrigin;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( glyphOrigin, size, 3 );
+    VGfloat* escapement;
+    m_currentFunctionCall.GetVectorData( escapement, size, 4 );
+
+    ::vgSetGlyphToImage( font, glyphIndex, image, glyphOrigin, escapement );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgDrawGlyphs()
+{
+    VGFont font;
+    m_currentFunctionCall.GetParamValue( font, 0 );
+    VGint glyphCount;
+    m_currentFunctionCall.GetParamValue( glyphCount, 1 );
+    VGuint * glyphIndices;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( glyphIndices, size, 2 );
+    VGfloat * adjustments_x;
+    m_currentFunctionCall.GetVectorData( adjustments_x, size, 3 );
+    VGfloat * adjustments_y;
+    m_currentFunctionCall.GetVectorData( adjustments_y, size, 4 );
+    VGbitfield paintModes;
+    m_currentFunctionCall.GetParamValue( paintModes, 5 );
+    VGboolean allowAutoHinting;
+    m_currentFunctionCall.GetParamValue( allowAutoHinting, 6 );
+
+    ::vgDrawGlyphs( font, glyphCount, glyphIndices, adjustments_x, adjustments_y, paintModes, allowAutoHinting );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgColorMatrix()
+{
+    VGImage dst;
+    m_currentFunctionCall.GetParamValue( dst, 0 );
+    VGImage src;
+    m_currentFunctionCall.GetParamValue( src, 1 );
+    VGfloat * matrix;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( matrix, size, 2 );
+
+	doSync( 3, dst, src );
+
+    ::vgColorMatrix( dst, src, matrix );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgConvolve()
+{
+    VGImage dst;
+    m_currentFunctionCall.GetParamValue( dst, 0 );
+    VGImage src;
+    m_currentFunctionCall.GetParamValue( src, 1 );
+    VGint kernelWidth;
+    m_currentFunctionCall.GetParamValue( kernelWidth, 2 );
+    VGint kernelHeight;
+    m_currentFunctionCall.GetParamValue( kernelHeight, 3 );
+    VGint shiftX;
+    m_currentFunctionCall.GetParamValue( shiftX, 4 );
+    VGint shiftY;
+    m_currentFunctionCall.GetParamValue( shiftY, 5 );
+    VGshort * kernel;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( kernel, size, 6 );
+    VGfloat scale;
+    m_currentFunctionCall.GetParamValue( scale, 7 );
+    VGfloat bias;
+    m_currentFunctionCall.GetParamValue( bias, 8 );
+    VGTilingMode tilingMode;
+    m_currentFunctionCall.GetParamValue( tilingMode, 9 );
+
+	doSync( 10, dst, src );
+
+    ::vgConvolve( dst, src, kernelWidth, kernelHeight, shiftX, shiftY, kernel, scale, bias, tilingMode );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgSeparableConvolve()
+{
+    VGImage dst;
+    m_currentFunctionCall.GetParamValue( dst, 0 );
+    VGImage src;
+    m_currentFunctionCall.GetParamValue( src, 1 );
+    VGint kernelWidth;
+    m_currentFunctionCall.GetParamValue( kernelWidth, 2 );
+    VGint kernelHeight;
+    m_currentFunctionCall.GetParamValue( kernelHeight, 3 );
+    VGint shiftX;
+    m_currentFunctionCall.GetParamValue( shiftX, 4 );
+    VGint shiftY;
+    m_currentFunctionCall.GetParamValue( shiftY, 5 );
+    VGshort * kernelX;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( kernelX, size, 6 );
+    VGshort * kernelY;
+    m_currentFunctionCall.GetVectorData( kernelY, size, 7 );
+    VGfloat scale;
+    m_currentFunctionCall.GetParamValue( scale, 8 );
+    VGfloat bias;
+    m_currentFunctionCall.GetParamValue( bias, 9 );
+    VGTilingMode tilingMode;
+    m_currentFunctionCall.GetParamValue( tilingMode, 10 );
+
+	doSync( 11, dst, src );
+
+    ::vgSeparableConvolve( dst, src, kernelWidth, kernelHeight, shiftX, shiftY, kernelX, kernelY, scale, bias, tilingMode );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgLookup()
+{
+    VGImage dst;
+    m_currentFunctionCall.GetParamValue( dst, 0 );
+    VGImage src;
+    m_currentFunctionCall.GetParamValue( src, 1 );
+    VGubyte * redLUT;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( redLUT, size, 2 );
+    VGubyte * greenLUT;
+    m_currentFunctionCall.GetVectorData( greenLUT, size, 3 );
+    VGubyte * blueLUT;
+    m_currentFunctionCall.GetVectorData( blueLUT, size, 4 );
+    VGubyte * alphaLUT;
+    m_currentFunctionCall.GetVectorData( alphaLUT, size, 5 );
+    VGboolean outputLinear;
+    m_currentFunctionCall.GetParamValue( outputLinear, 6 );
+    VGboolean outputPremultiplied;
+    m_currentFunctionCall.GetParamValue( outputPremultiplied, 7 );
+
+	doSync( 8, dst, src );
+
+    ::vgLookup( dst, src, redLUT, greenLUT, blueLUT, alphaLUT, outputLinear, outputPremultiplied );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgLookupSingle()
+{
+    VGImage dst;
+    m_currentFunctionCall.GetParamValue( dst, 0 );
+    VGImage src;
+    m_currentFunctionCall.GetParamValue( src, 1 );
+    VGuint * lookupTable;
+    TInt size;
+    m_currentFunctionCall.GetVectorData( lookupTable, size, 2 );
+    VGImageChannel sourceChannel;
+    m_currentFunctionCall.GetParamValue( sourceChannel, 3 );
+    VGboolean outputLinear;
+    m_currentFunctionCall.GetParamValue( outputLinear, 4 );
+    VGboolean outputPremultiplied;
+    m_currentFunctionCall.GetParamValue( outputPremultiplied, 5 );
+
+	doSync( 6, dst, src );
+
+    ::vgLookupSingle( dst, src, lookupTable, sourceChannel, outputLinear, outputPremultiplied );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetMatrix()
+{
+    VGfloat m[9];
+    ::vgGetMatrix( m );
+    m_currentFunctionCall.SetVectorData( m, 9, 0 );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgGetfv()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGint count;
+    m_currentFunctionCall.GetParamValue( count, 1 );
+    VGfloat *values = (VGfloat*)iStack->AllocFromStack( count*m_currentFunctionCall.GetTypeSize( OpenVgRFC::EVGfloat),
+        m_currentFunctionCall.GetTypeAlignment( OpenVgRFC::EVGfloat) );
+    ::vgGetfv( type, count, values);
+    m_currentFunctionCall.SetVectorData( values, count, 2 );
+    int ret = WriteReply();
+    iStack->ClearStack();
+    values = NULL;
+    return ret;
+}
+
+
+int OpenVGAPIWrapper::vgGetiv()
+{
+    VGParamType type;
+    m_currentFunctionCall.GetParamValue( type, 0 );
+    VGint count;
+    m_currentFunctionCall.GetParamValue( count, 1 );
+    VGint* values = (VGint*)iStack->AllocFromStack( count*m_currentFunctionCall.GetTypeSize( OpenVgRFC::EVGint),
+        m_currentFunctionCall.GetTypeAlignment( OpenVgRFC::EVGint) );
+    ::vgGetiv( type, count, values);
+    m_currentFunctionCall.SetVectorData( values, count, 2 );
+    int ret = WriteReply();
+    iStack->ClearStack();
+    values = NULL;
+    return ret;
+}
+
+
+int OpenVGAPIWrapper::vgGetParameterfv()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGint count;
+    m_currentFunctionCall.GetParamValue( count, 2 );
+    VGfloat *values = (VGfloat*)iStack->AllocFromStack( count*m_currentFunctionCall.GetTypeSize( OpenVgRFC::EVGfloat),
+        m_currentFunctionCall.GetTypeAlignment( OpenVgRFC::EVGfloat) );
+
+    ::vgGetParameterfv( object, paramType, count, values );
+    m_currentFunctionCall.SetVectorData( values, count, 3 );
+    int ret = WriteReply();
+    return ret;
+}
+
+
+int OpenVGAPIWrapper::vgGetParameteriv()
+{
+    VGHandle object;
+    m_currentFunctionCall.GetParamValue( object, 0 );
+    VGint paramType;
+    m_currentFunctionCall.GetParamValue( paramType, 1 );
+    VGint count;
+    m_currentFunctionCall.GetParamValue( count, 2 );
+    VGint* values = (VGint*)iStack->AllocFromStack( count*m_currentFunctionCall.GetTypeSize( OpenVgRFC::EVGint),
+        m_currentFunctionCall.GetTypeAlignment( OpenVgRFC::EVGint) );
+
+    ::vgGetParameteriv( object, paramType, count, values );
+    m_currentFunctionCall.SetVectorData( values, count, 3 );
+    int ret = WriteReply();
+    iStack->ClearStack();
+    values = NULL;
+
+    return ret;
+}
+
+
+int OpenVGAPIWrapper::vgGetImageSubData()
+{
+    VGImage image;
+    m_currentFunctionCall.GetParamValue( image, 0 );
+    VGint dataStride;
+    m_currentFunctionCall.GetParamValue( dataStride, 2 );
+    VGImageFormat dataFormat;
+    m_currentFunctionCall.GetParamValue( dataFormat, 3 );
+    VGint x;
+    m_currentFunctionCall.GetParamValue( x, 4 );
+    VGint y;
+    m_currentFunctionCall.GetParamValue( y, 5 );
+    VGint width;
+    m_currentFunctionCall.GetParamValue( width, 6 );
+    VGint height;
+    m_currentFunctionCall.GetParamValue( height, 7 );
+	VGint pixmapSize;
+	m_currentFunctionCall.GetParamValue(pixmapSize, 8);
+
+    void *data = iStack->AllocFromStack(pixmapSize, 4 );
+
+    ::vgGetImageSubData( image, data, dataStride, dataFormat, x, y, width, height );
+    m_currentFunctionCall.SetVectorData( data, pixmapSize, 1 );
+
+    int ret = WriteReply();
+
+    iStack->ClearStack();
+    data = NULL;
+
+    return ret;
+}
+
+
+int OpenVGAPIWrapper::vgPointAlongPath()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    VGint startSegment;
+    m_currentFunctionCall.GetParamValue( startSegment, 1 );
+    VGint numSegments;
+    m_currentFunctionCall.GetParamValue( numSegments, 2 );
+    VGfloat distance;
+    m_currentFunctionCall.GetParamValue( distance, 3 );
+    VGfloat * x(NULL);
+    VGfloat * y(NULL);
+    VGfloat * tangentX(NULL);
+    VGfloat * tangentY(NULL);
+    VGfloat xval;
+    VGfloat yval;
+    VGfloat tangentXval;
+    VGfloat tangentYval;
+
+    TInt size;
+    VGfloat *data;
+    m_currentFunctionCall.GetVectorData( data, size, 4 );
+    if ( size )
+    {
+        x = &xval;
+    }
+    m_currentFunctionCall.GetVectorData( data, size, 5 );
+    if ( size )
+    {
+        y = &yval;
+    }
+    m_currentFunctionCall.GetVectorData( data, size, 6 );
+    if ( size )
+    {
+        tangentX = &tangentXval;
+    }
+    m_currentFunctionCall.GetVectorData( data, size, 7 );
+    if ( size )
+    {
+        tangentY = &tangentYval;
+    }
+
+    ::vgPointAlongPath( path, startSegment, numSegments, distance, x, y, tangentX, tangentY );
+
+    if ( x )
+    {
+        m_currentFunctionCall.SetVectorData( x, 1, 4 );
+    }
+    if ( y )
+    {
+        m_currentFunctionCall.SetVectorData( y, 1, 5 );
+    }
+    if ( tangentX )
+    {
+        m_currentFunctionCall.SetVectorData( tangentX, 1, 6 );
+    }
+    if ( tangentY )
+    {
+        m_currentFunctionCall.SetVectorData( tangentY, 1, 7 );
+    }
+
+    int ret = WriteReply();
+
+    return ret;
+}
+
+
+int OpenVGAPIWrapper::vgPathBounds()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    VGfloat minX;
+    VGfloat minY;
+    VGfloat width;
+    VGfloat height;
+
+    ::vgPathBounds( path, &minX, &minY, &width, &height );
+
+    m_currentFunctionCall.SetVectorData( &minX, 1, 1 );
+    m_currentFunctionCall.SetVectorData( &minY, 1, 2 );
+    m_currentFunctionCall.SetVectorData( &width, 1, 3 );
+    m_currentFunctionCall.SetVectorData( &height, 1, 4 );
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vgPathTransformedBounds()
+{
+    VGPath path;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    VGfloat minX;
+    VGfloat minY;
+    VGfloat width;
+    VGfloat height;
+
+    ::vgPathTransformedBounds( path, &minX, &minY, &width, &height );
+
+    m_currentFunctionCall.SetVectorData( &minX, 1, 1 );
+    m_currentFunctionCall.SetVectorData( &minY, 1, 2 );
+    m_currentFunctionCall.SetVectorData( &width, 1, 3 );
+    m_currentFunctionCall.SetVectorData( &height, 1, 4 );
+    return WriteReply();
+}
+
+//vgu 1.1
+int OpenVGAPIWrapper::vguLine()
+{
+    VGHandle path;
+    VGfloat x0, y0, x1, y1;
+
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    m_currentFunctionCall.GetParamValue( x0, 1 );
+    m_currentFunctionCall.GetParamValue( y0, 2 );
+    m_currentFunctionCall.GetParamValue( x1, 3 );
+    m_currentFunctionCall.GetParamValue( y1, 4 );
+
+    VGUErrorCode error = ::vguLine(path, x0, y0, x1, y1);
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vguPolygon()
+{
+    VGHandle path;
+    VGint count;
+    VGfloat *points;
+    TInt size;
+    VGboolean closed;
+
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    m_currentFunctionCall.GetParamValue( count, 1 );
+    m_currentFunctionCall.GetParamValue( closed, 2 );
+    m_currentFunctionCall.GetVectorData( points, size, 3 );
+
+    VGUErrorCode error = ::vguPolygon(path, points, count, closed );
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vguRect()
+{
+    VGHandle path;
+    VGfloat x, y, width, height;
+
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    m_currentFunctionCall.GetParamValue( x, 1 );
+    m_currentFunctionCall.GetParamValue( y, 2 );
+    m_currentFunctionCall.GetParamValue( width, 3 );
+    m_currentFunctionCall.GetParamValue( height, 4 );
+
+    VGUErrorCode error = ::vguRect(path, x, y, width, height);
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vguRoundRect()
+{
+    VGHandle path;
+    VGfloat x, y, width, height, arcWidth, arcHeight;
+
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    m_currentFunctionCall.GetParamValue( x, 1 );
+    m_currentFunctionCall.GetParamValue( y, 2 );
+    m_currentFunctionCall.GetParamValue( width, 3 );
+    m_currentFunctionCall.GetParamValue( height, 4 );
+    m_currentFunctionCall.GetParamValue( arcWidth, 5 );
+    m_currentFunctionCall.GetParamValue( arcHeight, 6 );
+
+    VGUErrorCode error = ::vguRoundRect(path, x, y, width, height,
+        arcWidth, arcHeight);
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vguEllipse()
+{
+    VGHandle path;
+    VGfloat cx, cy, width, height;
+
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    m_currentFunctionCall.GetParamValue( cx, 1 );
+    m_currentFunctionCall.GetParamValue( cy, 2 );
+    m_currentFunctionCall.GetParamValue( width, 3 );
+    m_currentFunctionCall.GetParamValue( height, 4 );
+
+    VGUErrorCode error = ::vguEllipse(path, cx, cy, width, height);
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vguArc()
+{
+    VGHandle path;
+    VGfloat x, y, width, height, startAngle, angleExtent;
+    VGUArcType arcType;
+    m_currentFunctionCall.GetParamValue( path, 0 );
+    m_currentFunctionCall.GetParamValue( x, 1 );
+    m_currentFunctionCall.GetParamValue( y, 2 );
+    m_currentFunctionCall.GetParamValue( width, 3 );
+    m_currentFunctionCall.GetParamValue( height, 4 );
+    m_currentFunctionCall.GetParamValue( startAngle, 5 );
+    m_currentFunctionCall.GetParamValue( angleExtent, 6 );
+    m_currentFunctionCall.GetParamValue( arcType, 7 );
+
+    VGUErrorCode error = ::vguArc(path, x, y, width, height,
+        startAngle, angleExtent, arcType);
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vguComputeWarpQuadToSquare()
+{
+    VGfloat sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3;
+    VGfloat matrix[9];
+
+    m_currentFunctionCall.GetParamValue( sx0, 0 );
+    m_currentFunctionCall.GetParamValue( sy0, 1 );
+    m_currentFunctionCall.GetParamValue( sx1, 2 );
+    m_currentFunctionCall.GetParamValue( sy1, 3 );
+    m_currentFunctionCall.GetParamValue( sx2, 4 );
+    m_currentFunctionCall.GetParamValue( sy2, 5 );
+    m_currentFunctionCall.GetParamValue( sx3, 6 );
+    m_currentFunctionCall.GetParamValue( sy3, 7 );
+
+    VGUErrorCode error = ::vguComputeWarpQuadToSquare( sx0, sy0,
+        sx1, sy1, sx2, sy2, sx3, sy3, matrix );
+    m_currentFunctionCall.SetVectorData( matrix, 9, 8 );
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vguComputeWarpSquareToQuad()
+{
+    VGfloat dx0, dy0, dx1, dy1, dx2, dy2, dx3, dy3;
+    VGfloat matrix[9];
+
+    m_currentFunctionCall.GetParamValue( dx0, 0 );
+    m_currentFunctionCall.GetParamValue( dy0, 1 );
+    m_currentFunctionCall.GetParamValue( dx1, 2 );
+    m_currentFunctionCall.GetParamValue( dy1, 3 );
+    m_currentFunctionCall.GetParamValue( dx2, 4 );
+    m_currentFunctionCall.GetParamValue( dy2, 5 );
+    m_currentFunctionCall.GetParamValue( dx3, 6 );
+    m_currentFunctionCall.GetParamValue( dy3, 7 );
+
+    VGUErrorCode error = ::vguComputeWarpSquareToQuad( dx0, dy0,
+        dx1, dy1, dx2, dy2, dx3, dy3, matrix );
+    m_currentFunctionCall.SetVectorData( matrix, 9, 8 );
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+
+int OpenVGAPIWrapper::vguComputeWarpQuadToQuad()
+{
+    VGfloat dx0, dy0, dx1, dy1, dx2, dy2, dx3, dy3;
+    VGfloat sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3;
+    VGfloat matrix[9];
+
+    m_currentFunctionCall.GetParamValue( dx0, 0 );
+    m_currentFunctionCall.GetParamValue( dy0, 1 );
+    m_currentFunctionCall.GetParamValue( dx1, 2 );
+    m_currentFunctionCall.GetParamValue( dy1, 3 );
+    m_currentFunctionCall.GetParamValue( dx2, 4 );
+    m_currentFunctionCall.GetParamValue( dy2, 5 );
+    m_currentFunctionCall.GetParamValue( dx3, 6 );
+    m_currentFunctionCall.GetParamValue( dy3, 7 );
+    m_currentFunctionCall.GetParamValue( sx0, 8 );
+    m_currentFunctionCall.GetParamValue( sy0, 9 );
+    m_currentFunctionCall.GetParamValue( sx1, 10 );
+    m_currentFunctionCall.GetParamValue( sy1, 11 );
+    m_currentFunctionCall.GetParamValue( sx2, 12 );
+    m_currentFunctionCall.GetParamValue( sy2, 13 );
+    m_currentFunctionCall.GetParamValue( sx3, 14 );
+    m_currentFunctionCall.GetParamValue( sy3, 15 );
+
+    VGUErrorCode error = ::vguComputeWarpQuadToQuad( dx0, dy0, dx1, dy1, dx2,
+        dy2, dx3, dy3, sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3, matrix );
+    m_currentFunctionCall.SetVectorData( matrix, 9, 16 );
+    m_currentFunctionCall.SetReturnValue((TUint32)error);
+    return WriteReply();
+}
+
+/**
+*
+*@param aParamIndex the index where the first pbuffer surface handle is located. The other(s) are located in the subsequent positions.
+*@param aDst destination image
+*@param aSrc source image
+*/
+
+void OpenVGAPIWrapper::doSync( int aParamIndex, VGImage aDst, VGImage aSrc )
+{
+	TRACE("DriverAPIWrapper::doSync ->\n");
+	int pbuffer(0);
+
+	if( aParamIndex >= m_currentFunctionCall.Data().Header().iParameterCount ){return;}
+	m_currentFunctionCall.GetParamValue( pbuffer, aParamIndex++ );
+	if( pbuffer )
+	{	
+		m_APIWrapper->GetDriverWrapper()->SyncVGImageFromPBuffer( (EGLSurface)pbuffer, aDst );
+	}
+
+	if( aParamIndex >= m_currentFunctionCall.Data().Header().iParameterCount ){return;}
+	m_currentFunctionCall.GetParamValue( pbuffer, aParamIndex++ );
+	if( pbuffer )
+	{
+		m_APIWrapper->GetDriverWrapper()->SyncVGImageFromPBuffer( (EGLSurface)pbuffer, aSrc );
+	}
+	TRACE("DriverAPIWrapper::doSync <-\n");
+}
+
+OpenVGAPIWrapper::OpenVGAPIWrapper(RemoteFunctionCallData& currentFunctionCallData, APIWrapperStack* stack, void* result, MGraphicsVHWCallback* serviceIf, KhronosAPIWrapper *aAPIWrapper ):
+	APIWrapper( currentFunctionCallData, stack, result, serviceIf ),
+	m_currentFunctionCall( m_currentFunctionCallData ),
+	vgePathCoordsSizeInBytesPtr( NULL ),
+	m_APIWrapper( aAPIWrapper )
+{
+	//vgePathCoordsSizeInBytesPtr = (vgePathCoordsSizeInBytesPtrType)::eglGetProcAddress("vgePathCoordsSizeInBytes");
+}
+
+int OpenVGAPIWrapper::WriteReply()
+{
+#ifdef LOG_ERROR
+	int operationid = (int)m_currentFunctionCall.Data().Header().iOpCode;
+	
+	/*int vgerror*/VGErrorCode vgerror = ::vgPlatsimGetError();
+	if ( m_lastVgError != vgerror )
+	{
+		if ( VG_NO_ERROR != vgerror )
+		{
+			printf("OpenVG error 0x%X, for request %d\n", vgerror, operationid );
+		}
+		m_lastVgError = vgerror;
+	}
+#endif
+	return APIWrapper::WriteReply();
+}
+
+int OpenVGAPIWrapper::DispatchRequest( unsigned long aCode )
+{
+    int ret(0);
+    switch ( aCode )
+    {
+        case OpenVgRFC::EvgCreatePaint:
+        {
+            ret = vgCreatePaint();
+            break;
+        }
+        case OpenVgRFC::EvgDestroyPaint:
+        {
+            ret = vgDestroyPaint();
+            break;
+        }
+        case OpenVgRFC::EvgSetPaint:
+        {
+            ret = vgSetPaint();
+            break;
+        }
+        case OpenVgRFC::EvgSetParameteri:
+        {
+            ret = vgSetParameteri();
+            break;
+        }
+        case OpenVgRFC::EvgSetParameterfv:
+        {
+            ret = vgSetParameterfv();
+            break;
+        }
+        case OpenVgRFC::EvgCreatePath:
+        {
+            ret = vgCreatePath();
+            break;
+        }
+        case OpenVgRFC::EvgDrawPath:
+        {
+            ret = vgDrawPath();
+            break;
+        }
+        case OpenVgRFC::EvgDestroyPath:
+        {
+            ret = vgDestroyPath();
+            break;
+        }
+        case OpenVgRFC::EvgAppendPathData:
+        {
+            ret = vgAppendPathData();
+            break;
+        }
+        case OpenVgRFC::EvgGetError:
+        {
+            ret = vgGetError();
+            break;
+        }
+        case OpenVgRFC::EvgSeti:
+        {
+            ret = vgSeti();
+            break;
+        }
+        case OpenVgRFC::EvgSetf:
+        {
+            ret = vgSetf();
+            break;
+        }
+        case OpenVgRFC::EvgSetfv:
+        {
+            ret = vgSetfv();
+            break;
+        }
+        case OpenVgRFC::EvgClear:
+        {
+            ret = vgClear();
+            break;
+        }
+        case OpenVgRFC::EvgLoadIdentity:
+        {
+            ret = vgLoadIdentity();
+            break;
+        }
+        case OpenVgRFC::EvgRotate:
+        {
+            ret = vgRotate();
+            break;
+        }
+        case OpenVgRFC::EvgScale:
+        {
+            ret = vgScale();
+            break;
+        }
+        case OpenVgRFC::EvgTranslate:
+        {
+            ret = vgTranslate();
+            break;
+        }
+        case OpenVgRFC::EvgReadPixels:
+        {
+            ret = vgReadPixels();
+            break;
+        }
+        case OpenVgRFC::EvgFlush:
+        {
+            ret = vgFlush();
+            break;
+        }
+        case OpenVgRFC::EvgFinish:
+        {
+            ret = vgFinish();
+            break;
+        }
+        case OpenVgRFC::EvgSetiv:
+        {
+            ret = vgSetiv();
+            break;
+        }
+        case OpenVgRFC::EvgGetPaint:
+        {
+            ret = vgGetPaint();
+            break;
+        }
+        case OpenVgRFC::EvgInterpolatePath:
+        {
+            ret =vgInterpolatePath();
+            break;
+        }
+        case OpenVgRFC::EvgPathLength:
+        {
+            ret = vgPathLength();
+            break;
+        }
+        case OpenVgRFC::EvgGetPathCapabilities:
+        {
+            ret = vgGetPathCapabilities();
+            break;
+        }
+        case OpenVgRFC::EvgGetf:
+        {
+            ret = vgGetf();
+            break;
+        }
+        case OpenVgRFC::EvgGeti:
+        {
+            ret = vgGeti();
+            break;
+        }
+        case OpenVgRFC::EvgGetVectorSize:
+        {
+            ret = vgGetVectorSize();
+            break;
+        }
+        case OpenVgRFC::EvgGetParameterf://10
+        {
+            ret = vgGetParameterf();
+            break;
+        }
+        case OpenVgRFC::EvgGetParameteri:
+        {
+            ret = vgGetParameteri();
+            break;
+        }
+        case OpenVgRFC::EvgGetParameterVectorSize:
+        {
+            ret = vgGetParameterVectorSize();
+            break;
+        }
+        case OpenVgRFC::EvgCreateMaskLayer:
+        {
+            ret = vgCreateMaskLayer();
+            break;
+        }
+        case OpenVgRFC::EvgGetColor:
+        {
+            ret = vgGetColor();
+            break;
+        }
+        case OpenVgRFC::EvgCreateImage:
+        {
+            ret = vgCreateImage();
+            break;
+        }
+        case OpenVgRFC::EvgChildImage:
+        {
+            ret = vgChildImage();
+            break;
+        }
+        case OpenVgRFC::EvgGetParent:
+        {
+            ret = vgGetParent();
+            break;
+        }
+        case OpenVgRFC::EvgCreateFont:
+        {
+            ret = vgCreateFont();
+            break;
+        }
+        case OpenVgRFC::EvgHardwareQuery:
+        {
+            ret = vgHardwareQuery();
+            break;
+        }
+//20
+        case OpenVgRFC::EvgGetParameterfv:
+        {
+            ret = vgGetParameterfv();
+            break;
+        }
+        case OpenVgRFC::EvgGetParameteriv:
+        {
+            ret = vgGetParameteriv();
+            break;
+        }
+        case OpenVgRFC::EvgGetfv:
+        {
+            ret = vgGetfv();
+            break;
+        }
+        case OpenVgRFC::EvgGetiv:
+        {
+            ret = vgGetiv();
+            break;
+        }
+        case OpenVgRFC::EvgGetMatrix:
+        {
+            ret = vgGetMatrix();
+            break;
+        }
+        case OpenVgRFC::EvgGetImageSubData:
+        {
+            ret = vgGetImageSubData();
+            break;
+        }
+        case OpenVgRFC::EvgSetParameterf:
+        {
+            ret = vgSetParameterf();
+            break;
+        }
+        case OpenVgRFC::EvgSetParameteriv:
+        {
+            ret = vgSetParameteriv();
+            break;
+        }
+        case OpenVgRFC::EvgLoadMatrix:
+        {
+            ret = vgLoadMatrix();
+            break;
+        }
+        case OpenVgRFC::EvgMultMatrix:   //40
+        {
+            ret = vgMultMatrix();
+            break;
+        }
+        case OpenVgRFC::EvgShear:
+        {
+            ret = vgShear();
+            break;
+        }
+        case OpenVgRFC::EvgMask:
+        {
+            ret = vgMask();
+            break;
+        }
+        case OpenVgRFC::EvgRenderToMask:
+        {
+            ret = vgRenderToMask();
+            break;
+        }
+        case OpenVgRFC::EvgDestroyMaskLayer:
+        {
+            ret = vgDestroyMaskLayer();
+            break;
+        }
+        case OpenVgRFC::EvgFillMaskLayer:
+        {
+            ret = vgFillMaskLayer();
+            break;
+        }
+        case OpenVgRFC::EvgCopyMask:
+        {
+            ret = vgCopyMask();
+            break;
+        }
+        case OpenVgRFC::EvgClearPath:
+        {
+            ret = vgClearPath();
+            break;
+        }
+        case OpenVgRFC::EvgRemovePathCapabilities:
+        {
+            ret = vgRemovePathCapabilities();
+            break;
+        }
+        case OpenVgRFC::EvgAppendPath:
+        {
+            ret = vgAppendPath();
+            break;
+        }
+        case OpenVgRFC::EvgModifyPathCoords:
+        {
+            ret = vgModifyPathCoords();
+            break;
+        }
+        case OpenVgRFC::EvgTransformPath:
+        {
+            ret = vgTransformPath();
+            break;
+        }
+        case OpenVgRFC::EvgPointAlongPath:
+        {
+            ret = vgPointAlongPath();
+            break;
+        }
+        case OpenVgRFC::EvgPathBounds:
+        {
+            ret = vgPathBounds();
+            break;
+        }
+        case OpenVgRFC::EvgPathTransformedBounds:
+        {
+            ret = vgPathTransformedBounds();
+            break;
+        }
+        case OpenVgRFC::EvgSetColor:
+        {
+            ret = vgSetColor();
+            break;
+        }
+        case OpenVgRFC::EvgPaintPattern:
+        {
+            ret = vgPaintPattern();
+            break;
+        }
+        case OpenVgRFC::EvgDestroyImage:
+        {
+            ret = vgDestroyImage();
+            break;
+        }
+        case OpenVgRFC::EvgClearImage:
+        {
+            ret = vgClearImage();
+            break;
+        }
+        case OpenVgRFC::EvgImageSubData:
+        {
+            ret = vgImageSubData();
+            break;
+        }
+        case OpenVgRFC::EvgCopyImage:
+        {
+            ret = vgCopyImage();
+            break;
+        }
+        case OpenVgRFC::EvgDrawImage:
+        {
+            ret = vgDrawImage();
+            break;
+        }
+        case OpenVgRFC::EvgSetPixels:
+        {
+            ret = vgSetPixels();
+            break;
+        }
+        case OpenVgRFC::EvgWritePixels:
+        {
+            ret = vgWritePixels();
+            break;
+        }
+        case OpenVgRFC::EvgGetPixels:
+        {
+            ret = vgGetPixels();
+            break;
+        }
+        case OpenVgRFC::EvgCopyPixels:
+        {
+            ret = vgCopyPixels();
+            break;
+        }
+        case OpenVgRFC::EvgDestroyFont:
+        {
+            ret = vgDestroyFont();
+            break;
+        }
+        case OpenVgRFC::EvgSetGlyphToPath:
+        {
+            ret = vgSetGlyphToPath();
+            break;
+        }
+        case OpenVgRFC::EvgSetGlyphToImage:
+        {
+            ret = vgSetGlyphToImage();
+            break;
+        }
+        case OpenVgRFC::EvgClearGlyph:
+        {
+            ret = vgClearGlyph();
+            break;
+        }
+        case OpenVgRFC::EvgDrawGlyph:
+        {
+            ret = vgDrawGlyph();
+            break;
+        }
+        case OpenVgRFC::EvgDrawGlyphs:
+        {
+            ret = vgDrawGlyphs();
+            break;
+        }
+        case OpenVgRFC::EvgColorMatrix:
+        {
+            ret = vgColorMatrix();
+            break;
+        }
+        case OpenVgRFC::EvgConvolve:
+        {
+            ret = vgConvolve();
+            break;
+        }
+        case OpenVgRFC::EvgSeparableConvolve:
+        {
+            ret = vgSeparableConvolve();
+            break;
+        }
+        case OpenVgRFC::EvgGaussianBlur:
+        {
+            ret = vgGaussianBlur();
+            break;
+        }
+        case OpenVgRFC::EvgLookup:
+        {
+            ret = vgLookup();
+            break;
+        }
+        case OpenVgRFC::EvgLookupSingle:
+        {
+            ret = vgLookupSingle();
+            break;
+        }
+        case OpenVgRFC::EvgePathCoordsSizeInBytes:
+        {
+            ret = vgePathCoordsSizeInBytes();
+            break;
+        }
+        case OpenVgRFC::EvgGetString:
+//		{
+//		ret = vgGetString();
+//		break;
+//		}
+        case OpenVgRFC::EvguLine:
+        {
+            ret = vguLine();
+            break;
+        }
+        case OpenVgRFC::EvguPolygon:
+        {
+            ret = vguPolygon();
+            break;
+        }
+        case OpenVgRFC::EvguRect:
+        {
+            ret = vguRect();
+            break;
+        }
+        case OpenVgRFC::EvguRoundRect:
+        {
+            ret = vguRoundRect();
+            break;
+        }
+        case OpenVgRFC::EvguEllipse:
+        {
+            ret = vguEllipse();
+            break;
+        }
+        case OpenVgRFC::EvguArc:
+        {
+            ret = vguArc();
+            break;
+        }
+        case OpenVgRFC::EvguComputeWarpQuadToSquare:
+        {
+            ret = vguComputeWarpQuadToSquare();
+            break;
+        }
+        case OpenVgRFC::EvguComputeWarpSquareToQuad:
+        {
+            ret = vguComputeWarpSquareToQuad();
+            break;
+        }
+        case OpenVgRFC::EvguComputeWarpQuadToQuad:
+        {
+            ret = vguComputeWarpQuadToQuad();
+            break;
+        }
+        default:
+            TRACE("Unimplemented Openvg Op code %u\n",aCode);
+            break;
+    }
+    return ret;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/src/platformthreading.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,271 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+// Cross platform threading support library
+
+#include "hostthreadadapter.h"
+
+#ifdef WIN32
+#include <windows.h>
+#include <WinBase.h>
+#else
+#include <unistd.h>
+#include <time.h>
+#include <signal.h>
+#endif
+
+#include <stdio.h>
+
+#ifdef WIN32
+#ifdef __GNUG__
+static void CALLBACK default_interrupt_handler(ULONG_PTR)
+#else // MSVC
+static VOID CALLBACK default_interrupt_handler(__in  ULONG_PTR)
+#endif
+#else // LINUX
+static void default_interrupt_handler(int)
+#endif
+{
+    // does nothing
+    ;
+}
+
+namespace Psu
+{
+
+#ifndef WIN32
+    const int MicrosecsInMillisec = 1000;
+#endif
+
+
+    int platform_create_simple_thread(PLATFORM_THREAD_T * pThreadHandle,
+                                      PLATFORM_THREADFUNC pFunc,
+                                      void * param)
+    {
+        int
+            rv = 0;
+
+#ifdef WIN32
+        DWORD
+            threadId,
+            stackSize = 0,
+            creationFlags = 0;
+
+        PLATFORM_THREAD_T
+            tmp =  CreateThread(NULL,
+                                stackSize,
+                                pFunc,
+                                param,
+                                creationFlags,
+                                &threadId);
+        if (tmp == NULL)
+            {
+                rv = GetLastError();
+            }
+        else
+            {
+                *pThreadHandle = tmp;
+            }
+#else
+        rv = pthread_create(pThreadHandle,
+                            0,
+                            pFunc,
+                            param);
+#endif
+
+        return rv;
+    }
+
+
+    void platform_release_thread(PLATFORM_THREAD_T threadHandle)
+    {
+#ifdef WIN32
+        CloseHandle(threadHandle);
+#else
+        pthread_detach(threadHandle);
+#endif
+    }
+
+
+    STATUS_T platform_join_thread(PLATFORM_THREAD_T threadHandle)
+    {
+		STATUS_T retVal;
+#ifdef WIN32
+
+        retVal = WaitForSingleObject(threadHandle,INFINITE);
+#else
+        retVal = pthread_join(threadHandle, NULL);
+#endif
+		return retVal;
+    }
+
+
+    void platform_mutex_init(PLATFORM_MUTEX_T * pMutex)
+    {
+#ifdef WIN32
+        InitializeCriticalSection(pMutex);
+#else
+        pthread_mutex_init(pMutex,
+                           0);
+#endif
+    }
+
+
+    void platform_mutex_destroy(PLATFORM_MUTEX_T * pMutex)
+    {
+#ifdef WIN32
+        DeleteCriticalSection(pMutex);
+#else
+        pthread_mutex_destroy(pMutex);
+#endif
+    }
+
+
+    void platform_mutex_lock(PLATFORM_MUTEX_T * pMutex)
+    {
+#ifdef WIN32
+        EnterCriticalSection(pMutex);
+#else
+        pthread_mutex_lock(pMutex);
+#endif
+    }
+
+
+    void platform_mutex_unlock(PLATFORM_MUTEX_T * pMutex)
+    {
+#ifdef WIN32
+        LeaveCriticalSection(pMutex);
+#else
+        pthread_mutex_unlock(pMutex);
+#endif
+    }
+
+
+    void platform_sleep(int millisecs)
+    {
+#ifdef WIN32
+        Sleep(millisecs);
+#else
+        usleep(millisecs * MicrosecsInMillisec);
+#endif
+    }
+
+
+    STATUS_T platform_create_semaphore(PLATFORM_SEMAPHORE_T& semHandle,
+    					int initialCount,int maximumCount)
+    {
+
+ 		STATUS_T rv =0;
+#ifdef WIN32
+
+        PLATFORM_SEMAPHORE_T
+            tmp =  CreateSemaphore(NULL,
+                                initialCount,
+                                maximumCount,
+                                NULL);
+        if (tmp == NULL)
+            {
+                rv = GetLastError();
+            }
+        else
+            {
+                semHandle = tmp;
+            }
+#else
+        rv = sem_init(&semHandle,
+                            0,
+                            initialCount);
+#endif
+
+        return rv;
+    }
+
+
+    STATUS_T platform_wait_for_signal(PLATFORM_SEMAPHORE_T& semHandle)
+    {
+		STATUS_T retVal;
+#ifdef WIN32
+
+        retVal = WaitForSingleObject(semHandle,	INFINITE);
+#else
+        retVal = sem_wait(&semHandle);
+#endif
+		return retVal;
+    }
+
+
+    void platform_signal_semaphore(PLATFORM_SEMAPHORE_T& semHandle)
+    {
+#ifdef WIN32
+        ReleaseSemaphore(semHandle, 1, NULL);
+#else
+        sem_post(&semHandle);
+#endif
+    }
+
+    void platform_release_semaphore(PLATFORM_SEMAPHORE_T& semHandle)
+    {
+#ifdef WIN32
+
+        CloseHandle(semHandle);
+#else
+
+        sem_destroy(&semHandle);
+#endif
+    }
+
+    int32_t platform_interruptable_sleep(int64_t length)
+    {
+#ifdef WIN32
+        return SleepEx(static_cast<DWORD>(length), TRUE);
+#else
+        struct timespec req = {0};
+        time_t sec = (int)(length/1000);
+        length = length - (sec*1000);
+        req.tv_sec = sec;
+        req.tv_nsec = length*1000000L;
+
+        int ret = nanosleep(&req, NULL);
+
+        return ret;
+#endif
+    }
+
+    bool platform_interrupt_sleep(PLATFORM_THREAD_T handle)
+    {
+#ifdef WIN32
+        int32_t result = QueueUserAPC(default_interrupt_handler, handle, 0);
+
+        return (result!=0);
+#else
+        return (0 == pthread_kill(handle, SIGUSR1));
+#endif
+    }
+
+#ifndef WIN32
+    SignalUSR1Handler SignalUSR1Handler::instance;
+
+    SignalUSR1Handler::SignalUSR1Handler()
+    {
+        //sa = {0}, old = {0};
+        sa.sa_handler = &default_interrupt_handler;
+        sigaction(SIGUSR1, &sa, &old);
+    }
+
+    SignalUSR1Handler::~SignalUSR1Handler()
+    {
+        sigaction(SIGUSR1, &old, NULL);
+    }
+#endif
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/vghwinterface/vghwapiwrapper/src/syborg-graphicswrapper.cpp	Wed Oct 06 17:59:01 2010 +0100
@@ -0,0 +1,150 @@
+// This is the main DLL file.
+
+#include "platformtypes.h"
+#include <KhronosAPIWrapper.h>
+#include <guestvideodriverinterfaceconstants.h>  //Registers and enums 
+#include <platformthreading.h>  //mutex
+#include <graphicsvhwcallback.h>
+#include "syborg-graphicswrapper.h"
+
+SyborgGraphicsWrapper::SyborgGraphicsWrapper()
+    {															
+    }
+
+SyborgGraphicsWrapper::~SyborgGraphicsWrapper()
+    {
+    delete m_wrapper;
+    m_wrapper = 0;
+
+    Psu::platform_release_semaphore(m_outputBufferSemaphore);
+    }
+
+int SyborgGraphicsWrapper::Reset( uint32_t *aGraphicsMemBase,  uint32_t *aCommandMemBase )
+    {
+    int ret = -1;
+    if ( m_wrapper )
+        {
+        delete m_wrapper;
+	    }
+    m_wrapper = NULL;
+
+    uint8_t *cmd_buffer = (uint8_t *)aCommandMemBase;
+    uint8_t *frame_buffer = (uint8_t *)aGraphicsMemBase;
+    if( (cmd_buffer != NULL) && (frame_buffer != NULL) )
+        {
+        m_wrapper = new KhronosAPIWrapper( (MGraphicsVHWCallback*)this,
+            frame_buffer, &cmd_buffer[VVHW_INPUT_BASE], &cmd_buffer[VVHW_OUTPUT_BASE] );
+        //Reset synchronisation mechanisms
+        Psu::platform_release_semaphore(m_outputBufferSemaphore);
+        Psu::platform_create_semaphore(m_outputBufferSemaphore, 1, 1);
+        ret = 0;
+        }
+    else
+        {
+        ret = -1;
+        }
+    return ret;
+    }
+
+void SyborgGraphicsWrapper::LockOutputBuffer()
+    {
+    #ifdef KHRONOS_API_W_MULTITHREAD
+    Psu::platform_wait_for_signal(m_outputBufferSemaphore);
+    #endif
+    }
+
+void SyborgGraphicsWrapper::ReleaseOutputBuffer(){}
+
+void SyborgGraphicsWrapper::ProcessingDone(int i)
+    {
+    m_pythonCallBack( i );
+    }
+
+extern "C"
+    {
+    SYBORG_GRAPHICSWRAPPER_API SyborgGraphicsWrapper* create_SyborgGraphicsWrapper()
+        {
+        return new SyborgGraphicsWrapper();
+        }
+    SYBORG_GRAPHICSWRAPPER_API int initialize_SyborgGraphicsWrapper( SyborgGraphicsWrapper* aSyborgGraphicsWrapper )
+        {
+        Psu::platform_create_semaphore(m_outputBufferSemaphore, 1, 1);
+        // Change to proper error handling
+        return 0;
+        }
+
+    SYBORG_GRAPHICSWRAPPER_API int set_GraphicsCallBack( SyborgGraphicsWrapper* aSyborgGraphicsWrapper, int (*aGraphicsCallBack) (int) )
+        {
+        m_pythonCallBack = aGraphicsCallBack;
+        // Change to proper error handling
+        return 0;
+        }
+
+    SYBORG_GRAPHICSWRAPPER_API int reset_SyborgGraphicsWrapper(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper, uint32_t *aGraphicsMemBase,  uint32_t *aCommandMemBase )
+        {
+        return aSyborgGraphicsWrapper->Reset( aGraphicsMemBase, aCommandMemBase );
+        }
+
+    SYBORG_GRAPHICSWRAPPER_API uint32_t get_InputBufferTail(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper )
+        {
+        return m_wrapper->InputBufferTail();
+        }
+    SYBORG_GRAPHICSWRAPPER_API uint32_t get_InputBufferHead(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper )
+        {
+        return m_wrapper->InputBufferHead( );
+        }
+    SYBORG_GRAPHICSWRAPPER_API uint32_t get_InputBufferReadCount(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper )
+        {
+        return m_wrapper->InputBufferReadCount( );
+        }
+    SYBORG_GRAPHICSWRAPPER_API uint32_t get_InputBufferWriteCount(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper )
+        {
+        return m_wrapper->InputBufferWriteCount( );
+        }
+    SYBORG_GRAPHICSWRAPPER_API uint32_t get_InputMaxTailIndex(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper )
+        {
+        return m_wrapper->InputMaxTailIndex( );
+        }
+    SYBORG_GRAPHICSWRAPPER_API uint32_t get_cmd_memsize( void )
+        {
+        return (VVI_PARAMETERS_INPUT_MEMORY_SIZE +
+                VVI_PARAMETERS_OUTPUT_MEMORY_SIZE);
+        }
+    SYBORG_GRAPHICSWRAPPER_API uint32_t get_framebuffer_memsize( void )
+        {
+        return VVI_SURFACEBUFFER_BASE_ADDRESS;
+        }
+
+    
+    SYBORG_GRAPHICSWRAPPER_API unsigned int execute_command(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper )
+        {
+        return m_wrapper->Execute( );
+        }
+    SYBORG_GRAPHICSWRAPPER_API void set_InputBufferTail(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper, uint32_t aVal )
+        {
+        m_wrapper->SetInputBufferTail( aVal );
+        }
+    SYBORG_GRAPHICSWRAPPER_API void set_InputBufferHead(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper, uint32_t aVal )
+        {
+        m_wrapper->SetInputBufferHead( aVal );
+        }
+    SYBORG_GRAPHICSWRAPPER_API void set_InputBufferReadCount(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper, uint32_t aVal )
+        {
+        m_wrapper->SetInputBufferReadCount( aVal );
+        }
+    SYBORG_GRAPHICSWRAPPER_API void set_InputBufferWriteCount(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper, uint32_t aVal )
+        {
+        m_wrapper->SetInputBufferWriteCount( aVal );
+        }
+    SYBORG_GRAPHICSWRAPPER_API void set_InputMaxTailIndex(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper, uint32_t aVal )
+        {
+        m_wrapper->SetInputMaxTailIndex( aVal );
+        }
+    SYBORG_GRAPHICSWRAPPER_API void signal_outputbuffer_semafore(  SyborgGraphicsWrapper* aSyborgGraphicsWrapper )
+        {
+        #ifdef KHRONOS_API_W_MULTITHREAD
+            Psu::platform_signal_semaphore(m_outputBufferSemaphore);
+        #endif
+        }
+
+    }