summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Gall <tom.gall@linaro.org>2014-10-05 23:02:12 -0500
committerTom Gall <tom.gall@linaro.org>2014-10-05 23:02:12 -0500
commitffbf61c267a162c3e5d41c9ff310e2c8dae1c3bd (patch)
treeb966b6d1b2c0a6bcb8787e234defcd47ac2a1f0b
downloadtg-openvg-ffbf61c267a162c3e5d41c9ff310e2c8dae1c3bd.tar.gz
Initial commit
This is the reference implementation with the miniEGL code stripped out Tests are simplistic at this point. Windowing uses traditional egl (mesa test) but should work with mali egl too.
-rw-r--r--CMakeLists.txt92
-rw-r--r--include/EGL/egl.h331
-rw-r--r--include/EGL/egl.h.org318
-rw-r--r--include/EGL/eglext.h539
-rw-r--r--include/EGL/eglplatform.h122
-rw-r--r--include/EGL/fbdev_window.h52
-rw-r--r--include/KHR/khrplatform.h273
-rw-r--r--include/VG/openvg.h752
-rw-r--r--include/VG/vgext.h274
-rw-r--r--include/VG/vgplatform.h106
-rw-r--r--include/VG/vgu.h131
-rw-r--r--include/esUtil.h285
-rw-r--r--src/es/esShader.c155
-rw-r--r--src/es/esShapes.c280
-rw-r--r--src/es/esTransform.c213
-rw-r--r--src/es/esUtil.c428
-rw-r--r--src/vg/Api.cpp3672
-rw-r--r--src/vg/Api.cpp.tg37
-rw-r--r--src/vg/Array.h209
-rw-r--r--src/vg/Context.cpp329
-rw-r--r--src/vg/Context.h257
-rw-r--r--src/vg/Defs.h119
-rw-r--r--src/vg/EGLAddOn.cpp868
-rw-r--r--src/vg/Font.cpp203
-rw-r--r--src/vg/Font.h102
-rw-r--r--src/vg/Image.cpp2675
-rw-r--r--src/vg/Image.h371
-rw-r--r--src/vg/Math.cpp75
-rw-r--r--src/vg/Math.h380
-rw-r--r--src/vg/Path.cpp2579
-rw-r--r--src/vg/Path.h177
-rw-r--r--src/vg/PixelPipe.cpp894
-rw-r--r--src/vg/PixelPipe.h150
-rw-r--r--src/vg/Rasterizer.cpp499
-rw-r--r--src/vg/Rasterizer.h165
-rw-r--r--src/vgu/VGU.cpp469
-rw-r--r--tests/Simple_Texture2D/CMakeLists.txt39
-rw-r--r--tests/Simple_Texture2D/main.c216
-rw-r--r--tests/font/CMakeLists.txt39
-rw-r--r--tests/font/Default-568h@2x.pngbin0 -> 18594 bytes
-rw-r--r--tests/font/DejaVuSans.inc937
-rw-r--r--tests/font/DejaVuSansMono.inc965
-rw-r--r--tests/font/DejaVuSerif.inc1110
-rw-r--r--tests/font/arial.fnt202
-rw-r--r--tests/font/arial.pngbin0 -> 184102 bytes
-rw-r--r--tests/font/circle_poly.svg20
-rw-r--r--tests/font/cmake/modules/FindEGL.cmake15
-rw-r--r--tests/font/delorean.pngbin0 -> 25751 bytes
-rw-r--r--tests/font/eglstate.h11
-rw-r--r--tests/font/fontinfo.h19
-rw-r--r--tests/font/inc/EGL/egl.h329
-rw-r--r--tests/font/inc/EGL/eglext.h539
-rw-r--r--tests/font/inc/EGL/eglplatform.h122
-rw-r--r--tests/font/inc/EGL/fbdev_window.h50
-rw-r--r--tests/font/inc/GLES/gl.h770
-rw-r--r--tests/font/inc/GLES/glext.h1278
-rw-r--r--tests/font/inc/GLES/glplatform.h30
-rw-r--r--tests/font/inc/GLES2/gl2.h620
-rw-r--r--tests/font/inc/GLES2/gl2ext.h1809
-rw-r--r--tests/font/inc/GLES2/gl2platform.h30
-rw-r--r--tests/font/inc/GLES3/gl3.h1061
-rw-r--r--tests/font/inc/GLES3/gl3ext.h24
-rw-r--r--tests/font/inc/GLES3/gl3platform.h30
-rw-r--r--tests/font/inc/KHR/khrplatform.h273
-rw-r--r--tests/font/inc/VG/openvg.h746
-rw-r--r--tests/font/inc/VG/vgext.h233
-rw-r--r--tests/font/inc/VG/vgplatform.h106
-rw-r--r--tests/font/inc/VG/vgu.h131
-rw-r--r--tests/font/inc/tiger.h45
-rw-r--r--tests/font/main.c663
-rw-r--r--tests/font/square.svg4
-rw-r--r--tests/font/testfont.fnt99
-rw-r--r--tests/font/testfont.pngbin0 -> 30638 bytes
-rw-r--r--tests/font/zero.pngbin0 -> 35255 bytes
74 files changed, 31146 insertions, 0 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..84db850
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,92 @@
+cmake_minimum_required(VERSION 2.8)
+
+# Project Options:
+
+
+set(PROJECT_NAME_STR OpenVG)
+set(VG_LIBRARY_NAME_STR ${PROJECT_NAME_STR})
+set(VGU_LIBRARY_NAME_STR ${PROJECT_NAME_STR}U)
+project($(PROJECT_NAME_STR))
+
+MESSAGE(STATUS "Project : OpenVG Library")
+
+
+SET(DEFAULT_DEV_INSTALL_DIR /usr/local)
+MESSAGE(STATUS "Install path is ${CMAKE_INSTALL_PREFIX}")
+
+# choose target
+if(TARGET)
+ if(${TARGET} STREQUAL "arm")
+ message ("Building for ${TARGET} with fb\n")
+ set(EGL_LIB_PATH "\"/usr/lib/libEGL.so\"")
+# INCLUDE_DIRECTORIES(/root/Mali_OpenGL_ES_SDK_v2.4.0/inc/EGL)
+# INCLUDE_DIRECTORIES(/root/Mali_OpenGL_ES_SDK_v2.4.0/inc)
+ elseif(${TARGET} STREQUAL "x86")
+ message ("Building for ${TARGET}\n")
+ set(EGL_LIB_PATH "\"/usr/lib/x86_64-linux-gnu/mesa-egl/libEGL.so\"")
+ INCLUDE_DIRECTORIES(/usr/include/EGL)
+ set(CMAKE_C_FLAGS "-DMESA_EGL_NO_X11_HEADERS")
+ set(CMAKE_CXX_FLAGS "-DMESA_EGL_NO_X11_HEADERS -fpermissive")
+ else()
+ MESSAGE(FATAL_ERROR "Target ${TARGET} is not valid. Choices are \"x86\" and \"arm\".")
+ endif()
+else(TARGET)
+ message ("TARGET was not set. Choices are \"x86\" and \"arm\".")
+ message ("Example usage: cmake .. -DTARGET=arm")
+ message ("Now using [arm] as default.\n")
+ set (TARGET "arm")
+ message ("Building for ${TARGET}\n")
+ set(EGL_LIB_PATH "\"/usr/lib/libEGL.so\"")
+
+endif(TARGET)
+message ("EGL PATH:${EGL_LIB_PATH} \n")
+add_definitions( -DEGLLIB=${EGL_LIB_PATH} )
+message ("PROJECT_SOURCE_DIR=${PROJECT_SOURCE_DIR}\n")
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/include)
+
+# Set up install permissions for file, directories and binaries.
+# !!! Note that these variables are used by the child cmake files so these
+# variables must be set before the add_subdirectories() commands below
+# File permissions (664)
+set(LIB_FPERMS PERMISSIONS
+ OWNER_READ OWNER_WRITE
+ GROUP_READ GROUP_WRITE
+ WORLD_READ)
+
+#set(CMAKE_CXX_FLAGS "-O3 -mcpu=cortex-a15 -mfpu=neon-vfpv4 -ftree-vectorize -funsafe-math-optimizations -mfloat-abi=hard" CACHE STRING "" FORCE)
+set(CMAKE_CXX_FLAGS "-g -std=c++11 -mcpu=cortex-a15 -mfpu=neon-vfpv4 -ftree-vectorize -funsafe-math-optimizations" CACHE STRING "" FORCE)
+set(CMAKE_C_FLAGS "-g -mcpu=cortex-a15 -mfpu=neon-vfpv4 -ftree-vectorize -funsafe-math-optimizations" CACHE STRING "" FORCE)
+# set(CMAKE_CXX_FLAGS "-g -O3 -std=c++11 -mcpu=cortex-a15 -mfpu=neon-vfpv4 -ftree-vectorize -funsafe-math-optimizations" CACHE STRING "" FORCE)
+#LINK_DIRECTORIES(${PROJECT_SOURCE_DIR}/src)
+
+set(VG_SOURCEFILES
+ src/es/esShader.c
+ src/es/esShapes.c
+ src/es/esTransform.c
+ src/es/esUtil.c
+ src/vg/Math.cpp
+ src/vg/Image.cpp
+ src/vg/Context.cpp
+ src/vg/Font.cpp
+ src/vg/Path.cpp
+ src/vg/PixelPipe.cpp
+ src/vg/Rasterizer.cpp
+ src/vg/Api.cpp
+ src/vg/EGLAddOn.cpp
+ )
+
+set(VGU_SOURCEFILES
+ src/vgu/VGU.cpp
+ )
+
+message ("VG_SOURCEFILES = ${VG_SOURCEFILES}\n")
+message ("VGU_SOURCEFILES = ${VGU_SOURCEFILES}\n")
+
+add_library(${VG_LIBRARY_NAME_STR} SHARED ${VG_SOURCEFILES})
+add_library(${VGU_LIBRARY_NAME_STR} SHARED ${VGU_SOURCEFILES})
+
+#target_link_libraries(${PROJECT_NAME_STR})
+
+install(TARGETS ${VG_LIBRARY_NAME_STR} LIBRARY DESTINATION lib ${LIB_FPERMS})
+install(TARGETS ${VGU_LIBRARY_NAME_STR} LIBRARY DESTINATION lib ${LIB_FPERMS})
diff --git a/include/EGL/egl.h b/include/EGL/egl.h
new file mode 100644
index 0000000..18527e9
--- /dev/null
+++ b/include/EGL/egl.h
@@ -0,0 +1,331 @@
+/* -*- 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 void eglOpenVGInit(EGLSurface surface);
+EGLAPI void eglVGDrawFunction(EGLSurface surface);
+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_ */
diff --git a/include/EGL/egl.h.org b/include/EGL/egl.h.org
new file mode 100644
index 0000000..c95dfc9
--- /dev/null
+++ b/include/EGL/egl.h.org
@@ -0,0 +1,318 @@
+#ifndef __egl_h_
+#define __egl_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 EGL 1.3 API.
+ *//*-------------------------------------------------------------------*/
+
+/* All platform-dependent types and macro boilerplate (such as EGLAPI
+ * and EGLAPIENTRY) should go in eglplatform.h.
+ */
+/*#include <EGL/eglplatform.h>*/
+
+/* Platform-specific types and definitions for egl.h */
+
+#ifndef __eglplatform_h_
+#define __eglplatform_h_
+
+#define EGLAPIENTRY /* empty */
+
+#if defined(EGL_STATIC_LIBRARY)
+# define EGLAPI
+#else
+# if defined(_WIN32) || defined(__VC32__) /* Win32 */
+# if defined (OPENVG_DLL_EXPORTS)
+# define EGLAPI __declspec(dllexport)
+# else
+# define EGLAPI __declspec(dllimport)
+# endif
+# elif defined(__APPLE__) /* Mac OS X */
+# define EGLAPI extern
+# endif
+#endif /* defined(EGL_STATIC_LIBRARY) */
+
+typedef struct
+{
+ int format; /*VGImageFormat cast to int*/
+ int width;
+ int height;
+ int stride; /*in bytes*/
+ void* data;
+} NativePixmap;
+
+typedef void* NativeDisplayType;
+typedef void* NativeWindowType;
+typedef NativePixmap* NativePixmapType;
+
+/* EGL 1.2 types, renamed for consistency in EGL 1.3 */
+typedef NativeDisplayType EGLNativeDisplayType;
+typedef NativePixmapType EGLNativePixmapType;
+typedef NativeWindowType EGLNativeWindowType;
+
+#endif /* __eglplatform_h */
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* EGL Types */
+typedef int EGLint; /* NOTE: official EGL 1.3 header defines this as int32_t */
+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
+
+/* 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 ((void *)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_PRESERVED_RESOURCES 0x3030
+#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
+#define EGL_CONFORMANT_KHR EGL_CONFORMANT
+
+/* 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_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 */
+
+/* QueryString targets */
+#define EGL_VENDOR 0x3053
+#define EGL_VERSION 0x3054
+#define EGL_EXTENSIONS 0x3055
+#define EGL_CLIENT_APIS 0x308D
+
+/* QuerySurface / 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
+
+/* 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
+
+/* BindAPI/QueryAPI targets */
+#define EGL_OPENGL_ES_API 0x30A0
+#define EGL_OPENVG_API 0x30A1
+
+/* 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 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);
+EGLAPI void (* EGLAPIENTRY eglGetProcAddress(const char *procname))(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __egl_h_ */
diff --git a/include/EGL/eglext.h b/include/EGL/eglext.h
new file mode 100644
index 0000000..8e9e610
--- /dev/null
+++ b/include/EGL/eglext.h
@@ -0,0 +1,539 @@
+#ifndef __eglext_h_
+#define __eglext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2007-2012 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: 19987 $ on $Date: 2012-12-13 16:46:46 -0800 (Thu, 13 Dec 2012) $ */
+#define EGL_EGLEXT_VERSION 14
+
+#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
+
+#if KHRONOS_SUPPORT_INT64 /* EGLTimeKHR requires 64-bit uint support */
+#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
+#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_KHR_lock_surface2
+#define EGL_KHR_lock_surface2 1
+#define EGL_BITMAP_PIXEL_SIZE_KHR 0x3110
+#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
+
+#if KHRONOS_SUPPORT_INT64 /* EGLTimeNV requires 64-bit uint support */
+#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 khronos_utime_nanoseconds_t EGLTimeNV;
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLSyncNV EGLAPIENTRY eglCreateFenceSyncNV (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncNV (EGLSyncNV sync);
+EGLAPI EGLBoolean EGLAPIENTRY eglFenceNV (EGLSyncNV sync);
+EGLAPI EGLint EGLAPIENTRY eglClientWaitSyncNV (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout);
+EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncNV (EGLSyncNV sync, EGLenum mode);
+EGLAPI EGLBoolean EGLAPIENTRY 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
+#endif
+
+#if KHRONOS_SUPPORT_INT64 /* Dependent on EGL_KHR_reusable_sync which requires 64-bit uint support */
+#ifndef EGL_KHR_fence_sync
+#define EGL_KHR_fence_sync 1
+/* Reuses most tokens and entry points from EGL_KHR_reusable_sync */
+#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_KHR 0x30F0
+#define EGL_SYNC_CONDITION_KHR 0x30F8
+#define EGL_SYNC_FENCE_KHR 0x30F9
+#endif
+#endif
+
+#ifndef EGL_HI_clientpixmap
+#define EGL_HI_clientpixmap 1
+
+/* Surface Attribute */
+#define EGL_CLIENT_PIXMAP_POINTER_HI 0x8F74
+/*
+ * Structure representing a client pixmap
+ * (pixmap's data is in client-space memory).
+ */
+struct EGLClientPixmapHI
+{
+ void* pData;
+ EGLint iWidth;
+ EGLint iHeight;
+ EGLint iStride;
+};
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurfaceHI(EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI* pixmap);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPIXMAPSURFACEHIPROC) (EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI* pixmap);
+#endif /* EGL_HI_clientpixmap */
+
+#ifndef EGL_HI_colorformats
+#define EGL_HI_colorformats 1
+/* Config Attribute */
+#define EGL_COLOR_FORMAT_HI 0x8F70
+/* Color Formats */
+#define EGL_COLOR_RGB_HI 0x8F71
+#define EGL_COLOR_RGBA_HI 0x8F72
+#define EGL_COLOR_ARGB_HI 0x8F73
+#endif /* EGL_HI_colorformats */
+
+#ifndef EGL_MESA_drm_image
+#define EGL_MESA_drm_image 1
+#define EGL_DRM_BUFFER_FORMAT_MESA 0x31D0 /* CreateDRMImageMESA attribute */
+#define EGL_DRM_BUFFER_USE_MESA 0x31D1 /* CreateDRMImageMESA attribute */
+#define EGL_DRM_BUFFER_FORMAT_ARGB32_MESA 0x31D2 /* EGL_IMAGE_FORMAT_MESA attribute value */
+#define EGL_DRM_BUFFER_MESA 0x31D3 /* eglCreateImageKHR target */
+#define EGL_DRM_BUFFER_STRIDE_MESA 0x31D4
+#define EGL_DRM_BUFFER_USE_SCANOUT_MESA 0x00000001 /* EGL_DRM_BUFFER_USE_MESA bits */
+#define EGL_DRM_BUFFER_USE_SHARE_MESA 0x00000002 /* EGL_DRM_BUFFER_USE_MESA bits */
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLImageKHR EGLAPIENTRY eglCreateDRMImageMESA (EGLDisplay dpy, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglExportDRMImageMESA (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEDRMIMAGEMESAPROC) (EGLDisplay dpy, const EGLint *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDRMIMAGEMESAPROC) (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride);
+#endif
+
+#ifndef EGL_NV_post_sub_buffer
+#define EGL_NV_post_sub_buffer 1
+#define EGL_POST_SUB_BUFFER_SUPPORTED_NV 0x30BE
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglPostSubBufferNV (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLPOSTSUBBUFFERNVPROC) (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height);
+#endif
+
+#ifndef EGL_ANGLE_query_surface_pointer
+#define EGL_ANGLE_query_surface_pointer 1
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean eglQuerySurfacePointerANGLE(EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value);
+#endif
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACEPOINTERANGLEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value);
+#endif
+
+#ifndef EGL_ANGLE_surface_d3d_texture_2d_share_handle
+#define EGL_ANGLE_surface_d3d_texture_2d_share_handle 1
+#define EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE 0x3200
+#endif
+
+#ifndef EGL_NV_coverage_sample_resolve
+#define EGL_NV_coverage_sample_resolve 1
+#define EGL_COVERAGE_SAMPLE_RESOLVE_NV 0x3131
+#define EGL_COVERAGE_SAMPLE_RESOLVE_DEFAULT_NV 0x3132
+#define EGL_COVERAGE_SAMPLE_RESOLVE_NONE_NV 0x3133
+#endif
+
+#if KHRONOS_SUPPORT_INT64 /* EGLuint64NV requires 64-bit uint support */
+#ifndef EGL_NV_system_time
+#define EGL_NV_system_time 1
+typedef khronos_utime_nanoseconds_t EGLuint64NV;
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeFrequencyNV(void);
+EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeNV(void);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) (void);
+typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMENVPROC) (void);
+#endif
+#endif
+
+#if KHRONOS_SUPPORT_INT64 /* EGLuint64KHR requires 64-bit uint support */
+#ifndef EGL_KHR_stream
+#define EGL_KHR_stream 1
+typedef void* EGLStreamKHR;
+typedef khronos_uint64_t EGLuint64KHR;
+#define EGL_NO_STREAM_KHR ((EGLStreamKHR)0)
+#define EGL_CONSUMER_LATENCY_USEC_KHR 0x3210
+#define EGL_PRODUCER_FRAME_KHR 0x3212
+#define EGL_CONSUMER_FRAME_KHR 0x3213
+#define EGL_STREAM_STATE_KHR 0x3214
+#define EGL_STREAM_STATE_CREATED_KHR 0x3215
+#define EGL_STREAM_STATE_CONNECTING_KHR 0x3216
+#define EGL_STREAM_STATE_EMPTY_KHR 0x3217
+#define EGL_STREAM_STATE_NEW_FRAME_AVAILABLE_KHR 0x3218
+#define EGL_STREAM_STATE_OLD_FRAME_AVAILABLE_KHR 0x3219
+#define EGL_STREAM_STATE_DISCONNECTED_KHR 0x321A
+#define EGL_BAD_STREAM_KHR 0x321B
+#define EGL_BAD_STATE_KHR 0x321C
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamKHR(EGLDisplay dpy, const EGLint *attrib_list);
+EGLAPI EGLBoolean EGLAPIENTRY eglDestroyStreamKHR(EGLDisplay dpy, EGLStreamKHR stream);
+EGLAPI EGLBoolean EGLAPIENTRY eglStreamAttribKHR(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamKHR(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint *value);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamu64KHR(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR *value);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMKHRPROC)(EGLDisplay dpy, const EGLint *attrib_list);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSTREAMKHRPROC)(EGLDisplay dpy, EGLStreamKHR stream);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMATTRIBKHRPROC)(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMKHRPROC)(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint *value);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMU64KHRPROC)(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR *value);
+#endif
+#endif
+
+#ifdef EGL_KHR_stream /* Requires KHR_stream extension */
+#ifndef EGL_KHR_stream_consumer_gltexture
+#define EGL_KHR_stream_consumer_gltexture 1
+#define EGL_CONSUMER_ACQUIRE_TIMEOUT_USEC_KHR 0x321E
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerGLTextureExternalKHR(EGLDisplay dpy, EGLStreamKHR stream);
+EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerAcquireKHR(EGLDisplay dpy, EGLStreamKHR stream);
+EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerReleaseKHR(EGLDisplay dpy, EGLStreamKHR stream);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC)(EGLDisplay dpy, EGLStreamKHR stream);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREKHRPROC)(EGLDisplay dpy, EGLStreamKHR stream);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEKHRPROC)(EGLDisplay dpy, EGLStreamKHR stream);
+#endif
+#endif
+
+#ifdef EGL_KHR_stream /* Requires KHR_stream extension */
+#ifndef EGL_KHR_stream_producer_eglsurface
+#define EGL_KHR_stream_producer_eglsurface 1
+#define EGL_STREAM_BIT_KHR 0x0800
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLSurface EGLAPIENTRY eglCreateStreamProducerSurfaceKHR(EGLDisplay dpy, EGLConfig config, EGLStreamKHR stream, const EGLint *attrib_list);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC)(EGLDisplay dpy, EGLConfig config, EGLStreamKHR stream, const EGLint *attrib_list);
+#endif
+#endif
+
+#ifdef EGL_KHR_stream /* Requires KHR_stream extension */
+#ifndef EGL_KHR_stream_producer_aldatalocator
+#define EGL_KHR_stream_producer_aldatalocator 1
+#endif
+#endif
+
+#ifdef EGL_KHR_stream /* Requires KHR_stream extension */
+#ifndef EGL_KHR_stream_fifo
+#define EGL_KHR_stream_fifo 1
+/* reuse EGLTimeKHR */
+#define EGL_STREAM_FIFO_LENGTH_KHR 0x31FC
+#define EGL_STREAM_TIME_NOW_KHR 0x31FD
+#define EGL_STREAM_TIME_CONSUMER_KHR 0x31FE
+#define EGL_STREAM_TIME_PRODUCER_KHR 0x31FF
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamTimeKHR(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLTimeKHR *value);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMTIMEKHRPROC)(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLTimeKHR *value);
+#endif
+#endif
+
+#ifndef EGL_EXT_create_context_robustness
+#define EGL_EXT_create_context_robustness 1
+#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT 0x30BF
+#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT 0x3138
+#define EGL_NO_RESET_NOTIFICATION_EXT 0x31BE
+#define EGL_LOSE_CONTEXT_ON_RESET_EXT 0x31BF
+#endif
+
+#ifndef EGL_ANGLE_d3d_share_handle_client_buffer
+#define EGL_ANGLE_d3d_share_handle_client_buffer 1
+/* reuse EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE */
+#endif
+
+#ifndef EGL_KHR_create_context
+#define EGL_KHR_create_context 1
+#define EGL_CONTEXT_MAJOR_VERSION_KHR EGL_CONTEXT_CLIENT_VERSION
+#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB
+#define EGL_CONTEXT_FLAGS_KHR 0x30FC
+#define EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR 0x30FD
+#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR 0x31BD
+#define EGL_NO_RESET_NOTIFICATION_KHR 0x31BE
+#define EGL_LOSE_CONTEXT_ON_RESET_KHR 0x31BF
+#define EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR 0x00000001
+#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR 0x00000002
+#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR 0x00000004
+#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR 0x00000001
+#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR 0x00000002
+#define EGL_OPENGL_ES3_BIT_KHR 0x00000040
+#endif
+
+#ifndef EGL_KHR_surfaceless_context
+#define EGL_KHR_surfaceless_context 1
+/* No tokens/entry points, just relaxes an error condition */
+#endif
+
+#ifdef EGL_KHR_stream /* Requires KHR_stream extension */
+#ifndef EGL_KHR_stream_cross_process_fd
+#define EGL_KHR_stream_cross_process_fd 1
+typedef int EGLNativeFileDescriptorKHR;
+#define EGL_NO_FILE_DESCRIPTOR_KHR ((EGLNativeFileDescriptorKHR)(-1))
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLNativeFileDescriptorKHR EGLAPIENTRY eglGetStreamFileDescriptorKHR(EGLDisplay dpy, EGLStreamKHR stream);
+EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamFromFileDescriptorKHR(EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLNativeFileDescriptorKHR (EGLAPIENTRYP PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC)(EGLDisplay dpy, EGLStreamKHR stream);
+typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC)(EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor);
+#endif
+#endif
+
+#ifndef EGL_EXT_multiview_window
+#define EGL_EXT_multiview_window 1
+#define EGL_MULTIVIEW_VIEW_COUNT_EXT 0x3134
+#endif
+
+#ifndef EGL_KHR_wait_sync
+#define EGL_KHR_wait_sync 1
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLint EGLAPIENTRY eglWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLint (EGLAPIENTRYP PFNEGLWAITSYNCKHRPROC)(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags);
+#endif
+
+#ifndef EGL_NV_post_convert_rounding
+#define EGL_NV_post_convert_rounding 1
+/* No tokens or entry points, just relaxes behavior of SwapBuffers */
+#endif
+
+#ifndef EGL_NV_native_query
+#define EGL_NV_native_query 1
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativeDisplayNV( EGLDisplay dpy, EGLNativeDisplayType* display_id);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativeWindowNV( EGLDisplay dpy, EGLSurface surf, EGLNativeWindowType* window);
+EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativePixmapNV( EGLDisplay dpy, EGLSurface surf, EGLNativePixmapType* pixmap);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEDISPLAYNVPROC)(EGLDisplay dpy, EGLNativeDisplayType *display_id);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEWINDOWNVPROC)(EGLDisplay dpy, EGLSurface surf, EGLNativeWindowType *window);
+typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEPIXMAPNVPROC)(EGLDisplay dpy, EGLSurface surf, EGLNativePixmapType *pixmap);
+#endif
+
+#ifndef EGL_NV_3dvision_surface
+#define EGL_NV_3dvision_surface 1
+#define EGL_AUTO_STEREO_NV 0x3136
+#endif
+
+#ifndef EGL_ANDROID_framebuffer_target
+#define EGL_ANDROID_framebuffer_target 1
+#define EGL_FRAMEBUFFER_TARGET_ANDROID 0x3147
+#endif
+
+#ifndef EGL_ANDROID_blob_cache
+#define EGL_ANDROID_blob_cache 1
+typedef khronos_ssize_t EGLsizeiANDROID;
+typedef void (*EGLSetBlobFuncANDROID) (const void *key, EGLsizeiANDROID keySize, const void *value, EGLsizeiANDROID valueSize);
+typedef EGLsizeiANDROID (*EGLGetBlobFuncANDROID) (const void *key, EGLsizeiANDROID keySize, void *value, EGLsizeiANDROID valueSize);
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI void EGLAPIENTRY eglSetBlobCacheFuncsANDROID(EGLDisplay dpy, EGLSetBlobFuncANDROID set, EGLGetBlobFuncANDROID get);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef void (EGLAPIENTRYP PFNEGLSETBLOBCACHEFUNCSANDROIDPROC)(EGLDisplay dpy, EGLSetBlobFuncANDROID set, EGLGetBlobFuncANDROID get);
+#endif
+
+#ifndef EGL_ANDROID_image_native_buffer
+#define EGL_ANDROID_image_native_buffer 1
+#define EGL_NATIVE_BUFFER_ANDROID 0x3140
+#endif
+
+#ifndef EGL_ANDROID_native_fence_sync
+#define EGL_ANDROID_native_fence_sync 1
+#define EGL_SYNC_NATIVE_FENCE_ANDROID 0x3144
+#define EGL_SYNC_NATIVE_FENCE_FD_ANDROID 0x3145
+#define EGL_SYNC_NATIVE_FENCE_SIGNALED_ANDROID 0x3146
+#define EGL_NO_NATIVE_FENCE_FD_ANDROID -1
+#ifdef EGL_EGLEXT_PROTOTYPES
+EGLAPI EGLint EGLAPIENTRY eglDupNativeFenceFDANDROID( EGLDisplay dpy, EGLSyncKHR);
+#endif /* EGL_EGLEXT_PROTOTYPES */
+typedef EGLint (EGLAPIENTRYP PFNEGLDUPNATIVEFENCEFDANDROIDPROC)(EGLDisplay dpy, EGLSyncKHR);
+#endif
+
+#ifndef EGL_ANDROID_recordable
+#define EGL_ANDROID_recordable 1
+#define EGL_RECORDABLE_ANDROID 0x3142
+#endif
+
+#ifndef EGL_EXT_buffer_age
+#define EGL_EXT_buffer_age 1
+#define EGL_BUFFER_AGE_EXT 0x313D
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __eglext_h_ */
diff --git a/include/EGL/eglplatform.h b/include/EGL/eglplatform.h
new file mode 100644
index 0000000..6d04553
--- /dev/null
+++ b/include/EGL/eglplatform.h
@@ -0,0 +1,122 @@
+#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: 12306 $ on $Date: 2010-08-25 09:51:28 -0700 (Wed, 25 Aug 2010) $
+ *
+ * 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".
+ *
+ * Khronos STRONGLY RECOMMENDS that you use the default definitions
+ * provided below, since these changes affect both binary and source
+ * portability of applications using EGL running on different EGL
+ * implementations.
+ */
+
+#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>
+
+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(__arm__) && defined(__gnu_linux__) /* ARM Linux Mali */
+#include <EGL/fbdev_window.h>
+
+typedef void* EGLNativeDisplayType;
+typedef fbdev_pixmap* EGLNativePixmapType;
+typedef fbdev_window* EGLNativeWindowType;
+
+#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 */
diff --git a/include/EGL/fbdev_window.h b/include/EGL/fbdev_window.h
new file mode 100644
index 0000000..caa35f2
--- /dev/null
+++ b/include/EGL/fbdev_window.h
@@ -0,0 +1,52 @@
+/* vim:set sts=4 ts=4 noexpandtab: */
+/*
+ * This confidential and proprietary software may be used only as
+ * authorised by a licensing agreement from ARM Limited
+ * (C) COPYRIGHT 2008,2009 ARM Limited
+ * ALL RIGHTS RESERVED
+ * The entire notice above must be reproduced on all authorised
+ * copies and copies may only be made to the extent permitted
+ * by a licensing agreement from ARM Limited.
+ */
+
+#ifndef _FBDEV_WINDOW_H_
+#define _FBDEV_WINDOW_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum
+{
+ FBDEV_PIXMAP_SUPPORTS_UMP = (1<<0)
+} fbdev_pixmap_flags;
+
+typedef struct fbdev_window
+{
+ unsigned short width;
+ unsigned short height;
+} fbdev_window;
+
+typedef struct fbdev_pixmap
+{
+ unsigned int height;
+ unsigned int width;
+ unsigned int format;
+ unsigned int stride;
+ unsigned int bytes_per_pixel;
+ unsigned char buffer_size;
+ unsigned char red_size;
+ unsigned char green_size;
+ unsigned char blue_size;
+ unsigned char alpha_size;
+ unsigned char luminance_size;
+ fbdev_pixmap_flags flags;
+ unsigned short *data;
+} fbdev_pixmap;
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif
diff --git a/include/KHR/khrplatform.h b/include/KHR/khrplatform.h
new file mode 100644
index 0000000..11e873e
--- /dev/null
+++ b/include/KHR/khrplatform.h
@@ -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 (_DLL_EXPORTS)
+# 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_ */
diff --git a/include/VG/openvg.h b/include/VG/openvg.h
new file mode 100644
index 0000000..a6a43a0
--- /dev/null
+++ b/include/VG/openvg.h
@@ -0,0 +1,752 @@
+/* $Revision: 6838 $ on $Date:: 2008-11-04 12:46:08 +0100 #$ */
+
+/*------------------------------------------------------------------------
+ *
+ * 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_2x3_GRADIENT = 0x1A08,
+
+ 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,
+
+ /* 2x3 matrix gradients */
+ VG_PAINT_TYPE_LINEAR_2x3_GRADIENT = 0x1B04,
+ VG_PAINT_TYPE_RADIAL_2x3_GRADIENT = 0x1B05,
+
+ 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,
+ VGfloat glyphOrigin [2],
+ VGfloat escapement[2]) VG_API_EXIT;
+VG_API_CALL void VG_API_ENTRY vgSetGlyphToImage(VGFont font,
+ VGuint glyphIndex,
+ VGImage image,
+ VGfloat glyphOrigin [2],
+ 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,
+ VGuint *glyphIndices,
+ VGfloat *adjustments_x,
+ 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;
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* _OPENVG_H */
diff --git a/include/VG/vgext.h b/include/VG/vgext.h
new file mode 100644
index 0000000..ac05994
--- /dev/null
+++ b/include/VG/vgext.h
@@ -0,0 +1,274 @@
+/* $Revision: 6810 $ on $Date:: 2008-10-29 15:31:37 +0100 #$ */
+
+/*------------------------------------------------------------------------
+ *
+ * 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 <stddef.h>
+#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
+
+/*-------------------------------------------------------------------------------
+ * * MonkVG extensions
+ * *------------------------------------------------------------------------------*/
+
+ /* set the number of iterations for tesselating curves. a low number will generate
+ * * less polygons but rougher looking rendering -- and vice versa.
+ * */
+ typedef enum {
+ VG_TESSELLATION_ITERATIONS_MNK = 0x1170,
+
+ /* the rendering buffer dimensions */
+ VG_SURFACE_WIDTH_MNK = 0x1171,
+ VG_SURFACE_HEIGHT_MNK = 0x1172,
+
+ VG_PARAM_TYPE_MNK_FORCE_SIZE = VG_MAX_ENUM
+ } VGParamTypeMNK;
+
+ typedef enum {
+ VG_RENDERING_BACKEND_TYPE_OPENGLES11 = 0,
+ VG_RENDERING_BACKEND_TYPE_OPENGLES20 = 1,
+ VG_RENDERING_BACKEND_TYPE_FORCE_SIZE = VG_MAX_ENUM
+ } VGRenderingBackendTypeMNK;
+
+ /* batches are a method for significantly speeding up rendering of collections of static paths
+ * */
+ typedef VGHandle VGBatchMNK;
+
+ VG_API_CALL VGBatchMNK VG_API_ENTRY vgCreateBatchMNK() VG_API_EXIT;
+ VG_API_CALL void VG_API_ENTRY vgDestroyBatchMNK( VGBatchMNK batch ) VG_API_EXIT;
+ VG_API_CALL void VG_API_ENTRY vgBeginBatchMNK( VGBatchMNK batch ) VG_API_EXIT;
+ VG_API_CALL void VG_API_ENTRY vgEndBatchMNK( VGBatchMNK batch ) VG_API_EXIT;
+ VG_API_CALL void VG_API_ENTRY vgDrawBatchMNK( VGBatchMNK batch ) VG_API_EXIT;
+ VG_API_CALL void VG_API_ENTRY vgDumpBatchMNK( VGBatchMNK batch, void **vertices, size_t *size ) VG_API_EXIT;
+
+ /* context MonkVG */
+ VG_API_CALL VGboolean vgCreateContextMNK( VGint width, VGint height, VGRenderingBackendTypeMNK backend );
+ VG_API_CALL void vgResizeSurfaceMNK( VGint width, VGint height );
+ VG_API_CALL void vgDestroyContextMNK( void );
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* _VGEXT_H */
diff --git a/include/VG/vgplatform.h b/include/VG/vgplatform.h
new file mode 100644
index 0000000..aa9896e
--- /dev/null
+++ b/include/VG/vgplatform.h
@@ -0,0 +1,106 @@
+/* $Revision: 6810 $ on $Date:: 2008-10-29 15:31:37 +0100 #$ */
+
+/*------------------------------------------------------------------------
+ *
+ * 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 */
diff --git a/include/VG/vgu.h b/include/VG/vgu.h
new file mode 100644
index 0000000..7c814f7
--- /dev/null
+++ b/include/VG/vgu.h
@@ -0,0 +1,131 @@
+/* $Revision: 6810 $ on $Date:: 2008-10-29 15:31:37 +0100 #$ */
+
+/*------------------------------------------------------------------------
+ *
+ * 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 */
diff --git a/include/esUtil.h b/include/esUtil.h
new file mode 100644
index 0000000..c41a599
--- /dev/null
+++ b/include/esUtil.h
@@ -0,0 +1,285 @@
+//
+// Book: OpenGL(R) ES 2.0 Programming Guide
+// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
+// ISBN-10: 0321502795
+// ISBN-13: 9780321502797
+// Publisher: Addison-Wesley Professional
+// URLs: http://safari.informit.com/9780321563835
+// http://www.opengles-book.com
+//
+
+//
+/// \file ESUtil.h
+/// \brief A utility library for OpenGL ES. This library provides a
+/// basic common framework for the example applications in the
+/// OpenGL ES 2.0 Programming Guide.
+//
+#ifndef ESUTIL_H
+#define ESUTIL_H
+
+///
+// Includes
+//
+#include <GLES2/gl2.h>
+#include <EGL/egl.h>
+
+#ifdef __cplusplus
+
+extern "C" {
+#endif
+
+
+///
+// Macros
+//
+#define ESUTIL_API
+#define ESCALLBACK
+
+
+/// esCreateWindow flag - RGB color buffer
+#define ES_WINDOW_RGB 0
+/// esCreateWindow flag - ALPHA color buffer
+#define ES_WINDOW_ALPHA 1
+/// esCreateWindow flag - depth buffer
+#define ES_WINDOW_DEPTH 2
+/// esCreateWindow flag - stencil buffer
+#define ES_WINDOW_STENCIL 4
+/// esCreateWindow flat - multi-sample buffer
+#define ES_WINDOW_MULTISAMPLE 8
+
+
+///
+// Types
+//
+
+#ifndef FALSE
+#define FALSE 0
+#endif
+#ifndef TRUE
+#define TRUE 1
+#endif
+
+typedef struct
+{
+ GLfloat m[4][4];
+} ESMatrix;
+
+typedef struct _escontext
+{
+ /// Put your user data here...
+ void* userData;
+
+ /// Window width
+ GLint width;
+
+ /// Window height
+ GLint height;
+
+ /// Window handle
+ EGLNativeWindowType hWnd;
+
+ /// EGL display
+ EGLDisplay eglDisplay;
+
+ /// EGL context
+ EGLContext eglContext;
+
+ /// EGL surface
+ EGLSurface eglSurface;
+
+ EGLConfig eglConfig;
+
+ void *vgContext;
+
+ /// Callbacks
+ void (ESCALLBACK *drawFunc) ( struct _escontext * );
+ void (ESCALLBACK *keyFunc) ( struct _escontext *, unsigned char, int, int );
+ void (ESCALLBACK *updateFunc) ( struct _escontext *, float deltaTime );
+} ESContext;
+
+
+///
+// Public Functions
+//
+
+//
+///
+/// \brief Initialize ES framework context. This must be called before calling any other functions.
+/// \param esContext Application context
+//
+void ESUTIL_API esInitContext ( ESContext *esContext );
+
+//
+/// \brief Create a window with the specified parameters
+/// \param esContext Application context
+/// \param title Name for title bar of window
+/// \param width Width in pixels of window to create
+/// \param height Height in pixels of window to create
+/// \param flags Bitfield for the window creation flags
+/// ES_WINDOW_RGB - specifies that the color buffer should have R,G,B channels
+/// ES_WINDOW_ALPHA - specifies that the color buffer should have alpha
+/// ES_WINDOW_DEPTH - specifies that a depth buffer should be created
+/// ES_WINDOW_STENCIL - specifies that a stencil buffer should be created
+/// ES_WINDOW_MULTISAMPLE - specifies that a multi-sample buffer should be created
+/// \return GL_TRUE if window creation is succesful, GL_FALSE otherwise
+GLboolean ESUTIL_API esCreateWindow ( ESContext *esContext, const char *title, GLint width, GLint height, GLuint flags );
+
+//
+/// \brief Start the main loop for the OpenGL ES application
+/// \param esContext Application context
+//
+void ESUTIL_API esMainLoop ( ESContext *esContext );
+
+//
+/// \brief Register a draw callback function to be used to render each frame
+/// \param esContext Application context
+/// \param drawFunc Draw callback function that will be used to render the scene
+//
+void ESUTIL_API esRegisterDrawFunc ( ESContext *esContext, void (ESCALLBACK *drawFunc) ( ESContext* ) );
+
+//
+/// \brief Register an update callback function to be used to update on each time step
+/// \param esContext Application context
+/// \param updateFunc Update callback function that will be used to render the scene
+//
+void ESUTIL_API esRegisterUpdateFunc ( ESContext *esContext, void (ESCALLBACK *updateFunc) ( ESContext*, float ) );
+
+//
+/// \brief Register an keyboard input processing callback function
+/// \param esContext Application context
+/// \param keyFunc Key callback function for application processing of keyboard input
+//
+void ESUTIL_API esRegisterKeyFunc ( ESContext *esContext,
+ void (ESCALLBACK *drawFunc) ( ESContext*, unsigned char, int, int ) );
+//
+/// \brief Log a message to the debug output for the platform
+/// \param formatStr Format string for error log.
+//
+void ESUTIL_API esLogMessage ( const char *formatStr, ... );
+
+//
+///
+/// \brief Load a shader, check for compile errors, print error messages to output log
+/// \param type Type of shader (GL_VERTEX_SHADER or GL_FRAGMENT_SHADER)
+/// \param shaderSrc Shader source string
+/// \return A new shader object on success, 0 on failure
+//
+GLuint ESUTIL_API esLoadShader ( GLenum type, const char *shaderSrc );
+
+//
+///
+/// \brief Load a vertex and fragment shader, create a program object, link program.
+/// Errors output to log.
+/// \param vertShaderSrc Vertex shader source code
+/// \param fragShaderSrc Fragment shader source code
+/// \return A new program object linked with the vertex/fragment shader pair, 0 on failure
+//
+GLuint ESUTIL_API esLoadProgram ( const char *vertShaderSrc, const char *fragShaderSrc );
+
+
+//
+/// \brief Generates geometry for a sphere. Allocates memory for the vertex data and stores
+/// the results in the arrays. Generate index list for a TRIANGLE_STRIP
+/// \param numSlices The number of slices in the sphere
+/// \param vertices If not NULL, will contain array of float3 positions
+/// \param normals If not NULL, will contain array of float3 normals
+/// \param texCoords If not NULL, will contain array of float2 texCoords
+/// \param indices If not NULL, will contain the array of indices for the triangle strip
+/// \return The number of indices required for rendering the buffers (the number of indices stored in the indices array
+/// if it is not NULL ) as a GL_TRIANGLE_STRIP
+//
+int ESUTIL_API esGenSphere ( int numSlices, float radius, GLfloat **vertices, GLfloat **normals,
+ GLfloat **texCoords, GLuint **indices );
+
+//
+/// \brief Generates geometry for a cube. Allocates memory for the vertex data and stores
+/// the results in the arrays. Generate index list for a TRIANGLES
+/// \param scale The size of the cube, use 1.0 for a unit cube.
+/// \param vertices If not NULL, will contain array of float3 positions
+/// \param normals If not NULL, will contain array of float3 normals
+/// \param texCoords If not NULL, will contain array of float2 texCoords
+/// \param indices If not NULL, will contain the array of indices for the triangle strip
+/// \return The number of indices required for rendering the buffers (the number of indices stored in the indices array
+/// if it is not NULL ) as a GL_TRIANGLES
+//
+int ESUTIL_API esGenCube ( float scale, GLfloat **vertices, GLfloat **normals,
+ GLfloat **texCoords, GLuint **indices );
+
+//
+/// \brief Loads a 24-bit TGA image from a file
+/// \param fileName Name of the file on disk
+/// \param width Width of loaded image in pixels
+/// \param height Height of loaded image in pixels
+/// \return Pointer to loaded image. NULL on failure.
+//
+char* ESUTIL_API esLoadTGA ( char *fileName, int *width, int *height );
+
+
+//
+/// \brief multiply matrix specified by result with a scaling matrix and return new matrix in result
+/// \param result Specifies the input matrix. Scaled matrix is returned in result.
+/// \param sx, sy, sz Scale factors along the x, y and z axes respectively
+//
+void ESUTIL_API esScale(ESMatrix *result, GLfloat sx, GLfloat sy, GLfloat sz);
+
+//
+/// \brief multiply matrix specified by result with a translation matrix and return new matrix in result
+/// \param result Specifies the input matrix. Translated matrix is returned in result.
+/// \param tx, ty, tz Scale factors along the x, y and z axes respectively
+//
+void ESUTIL_API esTranslate(ESMatrix *result, GLfloat tx, GLfloat ty, GLfloat tz);
+
+//
+/// \brief multiply matrix specified by result with a rotation matrix and return new matrix in result
+/// \param result Specifies the input matrix. Rotated matrix is returned in result.
+/// \param angle Specifies the angle of rotation, in degrees.
+/// \param x, y, z Specify the x, y and z coordinates of a vector, respectively
+//
+void ESUTIL_API esRotate(ESMatrix *result, GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+
+//
+// \brief multiply matrix specified by result with a perspective matrix and return new matrix in result
+/// \param result Specifies the input matrix. new matrix is returned in result.
+/// \param left, right Coordinates for the left and right vertical clipping planes
+/// \param bottom, top Coordinates for the bottom and top horizontal clipping planes
+/// \param nearZ, farZ Distances to the near and far depth clipping planes. Both distances must be positive.
+//
+void ESUTIL_API esFrustum(ESMatrix *result, float left, float right, float bottom, float top, float nearZ, float farZ);
+
+//
+/// \brief multiply matrix specified by result with a perspective matrix and return new matrix in result
+/// \param result Specifies the input matrix. new matrix is returned in result.
+/// \param fovy Field of view y angle in degrees
+/// \param aspect Aspect ratio of screen
+/// \param nearZ Near plane distance
+/// \param farZ Far plane distance
+//
+void ESUTIL_API esPerspective(ESMatrix *result, float fovy, float aspect, float nearZ, float farZ);
+
+//
+/// \brief multiply matrix specified by result with a perspective matrix and return new matrix in result
+/// \param result Specifies the input matrix. new matrix is returned in result.
+/// \param left, right Coordinates for the left and right vertical clipping planes
+/// \param bottom, top Coordinates for the bottom and top horizontal clipping planes
+/// \param nearZ, farZ Distances to the near and far depth clipping planes. These values are negative if plane is behind the viewer
+//
+void ESUTIL_API esOrtho(ESMatrix *result, float left, float right, float bottom, float top, float nearZ, float farZ);
+
+//
+/// \brief perform the following operation - result matrix = srcA matrix * srcB matrix
+/// \param result Returns multiplied matrix
+/// \param srcA, srcB Input matrices to be multiplied
+//
+void ESUTIL_API esMatrixMultiply(ESMatrix *result, ESMatrix *srcA, ESMatrix *srcB);
+
+//
+//// \brief return an indentity matrix
+//// \param result returns identity matrix
+//
+void ESUTIL_API esMatrixLoadIdentity(ESMatrix *result);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ESUTIL_H
diff --git a/src/es/esShader.c b/src/es/esShader.c
new file mode 100644
index 0000000..4ea2cbc
--- /dev/null
+++ b/src/es/esShader.c
@@ -0,0 +1,155 @@
+//
+// Book: OpenGL(R) ES 2.0 Programming Guide
+// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
+// ISBN-10: 0321502795
+// ISBN-13: 9780321502797
+// Publisher: Addison-Wesley Professional
+// URLs: http://safari.informit.com/9780321563835
+// http://www.opengles-book.com
+//
+
+// ESShader.c
+//
+// Utility functions for loading shaders and creating program objects.
+//
+
+///
+// Includes
+//
+#include "esUtil.h"
+#include <stdlib.h>
+
+//////////////////////////////////////////////////////////////////
+//
+// Private Functions
+//
+//
+
+
+
+//////////////////////////////////////////////////////////////////
+//
+// Public Functions
+//
+//
+
+//
+///
+/// \brief Load a shader, check for compile errors, print error messages to output log
+/// \param type Type of shader (GL_VERTEX_SHADER or GL_FRAGMENT_SHADER)
+/// \param shaderSrc Shader source string
+/// \return A new shader object on success, 0 on failure
+//
+GLuint ESUTIL_API esLoadShader ( GLenum type, const char *shaderSrc )
+{
+ GLuint shader;
+ GLint compiled;
+
+ // Create the shader object
+ shader = glCreateShader ( type );
+
+ if ( shader == 0 )
+ return 0;
+
+ // Load the shader source
+ glShaderSource ( shader, 1, &shaderSrc, NULL );
+
+ // Compile the shader
+ glCompileShader ( shader );
+
+ // Check the compile status
+ glGetShaderiv ( shader, GL_COMPILE_STATUS, &compiled );
+
+ if ( !compiled )
+ {
+ GLint infoLen = 0;
+
+ glGetShaderiv ( shader, GL_INFO_LOG_LENGTH, &infoLen );
+
+ if ( infoLen > 1 )
+ {
+ char* infoLog = malloc (sizeof(char) * infoLen );
+
+ glGetShaderInfoLog ( shader, infoLen, NULL, infoLog );
+ esLogMessage ( "Error compiling shader:\n%s\n", infoLog );
+
+ free ( infoLog );
+ }
+
+ glDeleteShader ( shader );
+ return 0;
+ }
+
+ return shader;
+
+}
+
+
+//
+///
+/// \brief Load a vertex and fragment shader, create a program object, link program.
+// Errors output to log.
+/// \param vertShaderSrc Vertex shader source code
+/// \param fragShaderSrc Fragment shader source code
+/// \return A new program object linked with the vertex/fragment shader pair, 0 on failure
+//
+GLuint ESUTIL_API esLoadProgram ( const char *vertShaderSrc, const char *fragShaderSrc )
+{
+ GLuint vertexShader;
+ GLuint fragmentShader;
+ GLuint programObject;
+ GLint linked;
+
+ // Load the vertex/fragment shaders
+ vertexShader = esLoadShader ( GL_VERTEX_SHADER, vertShaderSrc );
+ if ( vertexShader == 0 )
+ return 0;
+
+ fragmentShader = esLoadShader ( GL_FRAGMENT_SHADER, fragShaderSrc );
+ if ( fragmentShader == 0 )
+ {
+ glDeleteShader( vertexShader );
+ return 0;
+ }
+
+ // Create the program object
+ programObject = glCreateProgram ( );
+
+ if ( programObject == 0 )
+ return 0;
+
+ glAttachShader ( programObject, vertexShader );
+ glAttachShader ( programObject, fragmentShader );
+
+ // Link the program
+ glLinkProgram ( programObject );
+
+ // Check the link status
+ glGetProgramiv ( programObject, GL_LINK_STATUS, &linked );
+
+ if ( !linked )
+ {
+ GLint infoLen = 0;
+
+ glGetProgramiv ( programObject, GL_INFO_LOG_LENGTH, &infoLen );
+
+ if ( infoLen > 1 )
+ {
+ char* infoLog = malloc (sizeof(char) * infoLen );
+
+ glGetProgramInfoLog ( programObject, infoLen, NULL, infoLog );
+ esLogMessage ( "Error linking program:\n%s\n", infoLog );
+
+ free ( infoLog );
+ }
+
+ glDeleteProgram ( programObject );
+ return 0;
+ }
+
+ // Free up no longer needed shader resources
+ glDeleteShader ( vertexShader );
+ glDeleteShader ( fragmentShader );
+
+ return programObject;
+} \ No newline at end of file
diff --git a/src/es/esShapes.c b/src/es/esShapes.c
new file mode 100644
index 0000000..0fa6505
--- /dev/null
+++ b/src/es/esShapes.c
@@ -0,0 +1,280 @@
+//
+// Book: OpenGL(R) ES 2.0 Programming Guide
+// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
+// ISBN-10: 0321502795
+// ISBN-13: 9780321502797
+// Publisher: Addison-Wesley Professional
+// URLs: http://safari.informit.com/9780321563835
+// http://www.opengles-book.com
+//
+
+// ESShapes.c
+//
+// Utility functions for generating shapes
+//
+
+///
+// Includes
+//
+#include "esUtil.h"
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+
+///
+// Defines
+//
+#define ES_PI (3.14159265f)
+
+//////////////////////////////////////////////////////////////////
+//
+// Private Functions
+//
+//
+
+
+
+//////////////////////////////////////////////////////////////////
+//
+// Public Functions
+//
+//
+
+//
+/// \brief Generates geometry for a sphere. Allocates memory for the vertex data and stores
+/// the results in the arrays. Generate index list for a TRIANGLE_STRIP
+/// \param numSlices The number of slices in the sphere
+/// \param vertices If not NULL, will contain array of float3 positions
+/// \param normals If not NULL, will contain array of float3 normals
+/// \param texCoords If not NULL, will contain array of float2 texCoords
+/// \param indices If not NULL, will contain the array of indices for the triangle strip
+/// \return The number of indices required for rendering the buffers (the number of indices stored in the indices array
+/// if it is not NULL ) as a GL_TRIANGLE_STRIP
+//
+int ESUTIL_API esGenSphere ( int numSlices, float radius, GLfloat **vertices, GLfloat **normals,
+ GLfloat **texCoords, GLuint **indices )
+{
+ int i;
+ int j;
+ int numParallels = numSlices / 2;
+ int numVertices = ( numParallels + 1 ) * ( numSlices + 1 );
+ int numIndices = numParallels * numSlices * 6;
+ float angleStep = (2.0f * ES_PI) / ((float) numSlices);
+
+ // Allocate memory for buffers
+ if ( vertices != NULL )
+ *vertices = malloc ( sizeof(GLfloat) * 3 * numVertices );
+
+ if ( normals != NULL )
+ *normals = malloc ( sizeof(GLfloat) * 3 * numVertices );
+
+ if ( texCoords != NULL )
+ *texCoords = malloc ( sizeof(GLfloat) * 2 * numVertices );
+
+ if ( indices != NULL )
+ *indices = malloc ( sizeof(GLuint) * numIndices );
+
+ for ( i = 0; i < numParallels + 1; i++ )
+ {
+ for ( j = 0; j < numSlices + 1; j++ )
+ {
+ int vertex = ( i * (numSlices + 1) + j ) * 3;
+
+ if ( vertices )
+ {
+ (*vertices)[vertex + 0] = radius * sinf ( angleStep * (float)i ) *
+ sinf ( angleStep * (float)j );
+ (*vertices)[vertex + 1] = radius * cosf ( angleStep * (float)i );
+ (*vertices)[vertex + 2] = radius * sinf ( angleStep * (float)i ) *
+ cosf ( angleStep * (float)j );
+ }
+
+ if ( normals )
+ {
+ (*normals)[vertex + 0] = (*vertices)[vertex + 0] / radius;
+ (*normals)[vertex + 1] = (*vertices)[vertex + 1] / radius;
+ (*normals)[vertex + 2] = (*vertices)[vertex + 2] / radius;
+ }
+
+ if ( texCoords )
+ {
+ int texIndex = ( i * (numSlices + 1) + j ) * 2;
+ (*texCoords)[texIndex + 0] = (float) j / (float) numSlices;
+ (*texCoords)[texIndex + 1] = ( 1.0f - (float) i ) / (float) (numParallels - 1 );
+ }
+ }
+ }
+
+ // Generate the indices
+ if ( indices != NULL )
+ {
+ GLuint *indexBuf = (*indices);
+ for ( i = 0; i < numParallels ; i++ )
+ {
+ for ( j = 0; j < numSlices; j++ )
+ {
+ *indexBuf++ = i * ( numSlices + 1 ) + j;
+ *indexBuf++ = ( i + 1 ) * ( numSlices + 1 ) + j;
+ *indexBuf++ = ( i + 1 ) * ( numSlices + 1 ) + ( j + 1 );
+
+ *indexBuf++ = i * ( numSlices + 1 ) + j;
+ *indexBuf++ = ( i + 1 ) * ( numSlices + 1 ) + ( j + 1 );
+ *indexBuf++ = i * ( numSlices + 1 ) + ( j + 1 );
+ }
+ }
+ }
+
+ return numIndices;
+}
+
+//
+/// \brief Generates geometry for a cube. Allocates memory for the vertex data and stores
+/// the results in the arrays. Generate index list for a TRIANGLES
+/// \param scale The size of the cube, use 1.0 for a unit cube.
+/// \param vertices If not NULL, will contain array of float3 positions
+/// \param normals If not NULL, will contain array of float3 normals
+/// \param texCoords If not NULL, will contain array of float2 texCoords
+/// \param indices If not NULL, will contain the array of indices for the triangle strip
+/// \return The number of indices required for rendering the buffers (the number of indices stored in the indices array
+/// if it is not NULL ) as a GL_TRIANGLE_STRIP
+//
+int ESUTIL_API esGenCube ( float scale, GLfloat **vertices, GLfloat **normals,
+ GLfloat **texCoords, GLuint **indices )
+{
+ int i;
+ int numVertices = 24;
+ int numIndices = 36;
+
+ GLfloat cubeVerts[] =
+ {
+ -0.5f, -0.5f, -0.5f,
+ -0.5f, -0.5f, 0.5f,
+ 0.5f, -0.5f, 0.5f,
+ 0.5f, -0.5f, -0.5f,
+ -0.5f, 0.5f, -0.5f,
+ -0.5f, 0.5f, 0.5f,
+ 0.5f, 0.5f, 0.5f,
+ 0.5f, 0.5f, -0.5f,
+ -0.5f, -0.5f, -0.5f,
+ -0.5f, 0.5f, -0.5f,
+ 0.5f, 0.5f, -0.5f,
+ 0.5f, -0.5f, -0.5f,
+ -0.5f, -0.5f, 0.5f,
+ -0.5f, 0.5f, 0.5f,
+ 0.5f, 0.5f, 0.5f,
+ 0.5f, -0.5f, 0.5f,
+ -0.5f, -0.5f, -0.5f,
+ -0.5f, -0.5f, 0.5f,
+ -0.5f, 0.5f, 0.5f,
+ -0.5f, 0.5f, -0.5f,
+ 0.5f, -0.5f, -0.5f,
+ 0.5f, -0.5f, 0.5f,
+ 0.5f, 0.5f, 0.5f,
+ 0.5f, 0.5f, -0.5f,
+ };
+
+ GLfloat cubeNormals[] =
+ {
+ 0.0f, -1.0f, 0.0f,
+ 0.0f, -1.0f, 0.0f,
+ 0.0f, -1.0f, 0.0f,
+ 0.0f, -1.0f, 0.0f,
+ 0.0f, 1.0f, 0.0f,
+ 0.0f, 1.0f, 0.0f,
+ 0.0f, 1.0f, 0.0f,
+ 0.0f, 1.0f, 0.0f,
+ 0.0f, 0.0f, -1.0f,
+ 0.0f, 0.0f, -1.0f,
+ 0.0f, 0.0f, -1.0f,
+ 0.0f, 0.0f, -1.0f,
+ 0.0f, 0.0f, 1.0f,
+ 0.0f, 0.0f, 1.0f,
+ 0.0f, 0.0f, 1.0f,
+ 0.0f, 0.0f, 1.0f,
+ -1.0f, 0.0f, 0.0f,
+ -1.0f, 0.0f, 0.0f,
+ -1.0f, 0.0f, 0.0f,
+ -1.0f, 0.0f, 0.0f,
+ 1.0f, 0.0f, 0.0f,
+ 1.0f, 0.0f, 0.0f,
+ 1.0f, 0.0f, 0.0f,
+ 1.0f, 0.0f, 0.0f,
+ };
+
+ GLfloat cubeTex[] =
+ {
+ 0.0f, 0.0f,
+ 0.0f, 1.0f,
+ 1.0f, 1.0f,
+ 1.0f, 0.0f,
+ 1.0f, 0.0f,
+ 1.0f, 1.0f,
+ 0.0f, 1.0f,
+ 0.0f, 0.0f,
+ 0.0f, 0.0f,
+ 0.0f, 1.0f,
+ 1.0f, 1.0f,
+ 1.0f, 0.0f,
+ 0.0f, 0.0f,
+ 0.0f, 1.0f,
+ 1.0f, 1.0f,
+ 1.0f, 0.0f,
+ 0.0f, 0.0f,
+ 0.0f, 1.0f,
+ 1.0f, 1.0f,
+ 1.0f, 0.0f,
+ 0.0f, 0.0f,
+ 0.0f, 1.0f,
+ 1.0f, 1.0f,
+ 1.0f, 0.0f,
+ };
+
+ // Allocate memory for buffers
+ if ( vertices != NULL )
+ {
+ *vertices = malloc ( sizeof(GLfloat) * 3 * numVertices );
+ memcpy( *vertices, cubeVerts, sizeof( cubeVerts ) );
+ for ( i = 0; i < numVertices * 3; i++ )
+ {
+ (*vertices)[i] *= scale;
+ }
+ }
+
+ if ( normals != NULL )
+ {
+ *normals = malloc ( sizeof(GLfloat) * 3 * numVertices );
+ memcpy( *normals, cubeNormals, sizeof( cubeNormals ) );
+ }
+
+ if ( texCoords != NULL )
+ {
+ *texCoords = malloc ( sizeof(GLfloat) * 2 * numVertices );
+ memcpy( *texCoords, cubeTex, sizeof( cubeTex ) ) ;
+ }
+
+
+ // Generate the indices
+ if ( indices != NULL )
+ {
+ GLuint cubeIndices[] =
+ {
+ 0, 2, 1,
+ 0, 3, 2,
+ 4, 5, 6,
+ 4, 6, 7,
+ 8, 9, 10,
+ 8, 10, 11,
+ 12, 15, 14,
+ 12, 14, 13,
+ 16, 17, 18,
+ 16, 18, 19,
+ 20, 23, 22,
+ 20, 22, 21
+ };
+
+ *indices = malloc ( sizeof(GLuint) * numIndices );
+ memcpy( *indices, cubeIndices, sizeof( cubeIndices ) );
+ }
+
+ return numIndices;
+}
diff --git a/src/es/esTransform.c b/src/es/esTransform.c
new file mode 100644
index 0000000..5182218
--- /dev/null
+++ b/src/es/esTransform.c
@@ -0,0 +1,213 @@
+//
+// Book: OpenGL(R) ES 2.0 Programming Guide
+// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
+// ISBN-10: 0321502795
+// ISBN-13: 9780321502797
+// Publisher: Addison-Wesley Professional
+// URLs: http://safari.informit.com/9780321563835
+// http://www.opengles-book.com
+//
+
+// ESUtil.c
+//
+// A utility library for OpenGL ES. This library provides a
+// basic common framework for the example applications in the
+// OpenGL ES 2.0 Programming Guide.
+//
+
+///
+// Includes
+//
+#include "esUtil.h"
+#include <math.h>
+#include <string.h>
+
+#define PI 3.1415926535897932384626433832795f
+
+void ESUTIL_API
+esScale(ESMatrix *result, GLfloat sx, GLfloat sy, GLfloat sz)
+{
+ result->m[0][0] *= sx;
+ result->m[0][1] *= sx;
+ result->m[0][2] *= sx;
+ result->m[0][3] *= sx;
+
+ result->m[1][0] *= sy;
+ result->m[1][1] *= sy;
+ result->m[1][2] *= sy;
+ result->m[1][3] *= sy;
+
+ result->m[2][0] *= sz;
+ result->m[2][1] *= sz;
+ result->m[2][2] *= sz;
+ result->m[2][3] *= sz;
+}
+
+void ESUTIL_API
+esTranslate(ESMatrix *result, GLfloat tx, GLfloat ty, GLfloat tz)
+{
+ result->m[3][0] += (result->m[0][0] * tx + result->m[1][0] * ty + result->m[2][0] * tz);
+ result->m[3][1] += (result->m[0][1] * tx + result->m[1][1] * ty + result->m[2][1] * tz);
+ result->m[3][2] += (result->m[0][2] * tx + result->m[1][2] * ty + result->m[2][2] * tz);
+ result->m[3][3] += (result->m[0][3] * tx + result->m[1][3] * ty + result->m[2][3] * tz);
+}
+
+void ESUTIL_API
+esRotate(ESMatrix *result, GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
+{
+ GLfloat sinAngle, cosAngle;
+ GLfloat mag = sqrtf(x * x + y * y + z * z);
+
+ sinAngle = sinf ( angle * PI / 180.0f );
+ cosAngle = cosf ( angle * PI / 180.0f );
+ if ( mag > 0.0f )
+ {
+ GLfloat xx, yy, zz, xy, yz, zx, xs, ys, zs;
+ GLfloat oneMinusCos;
+ ESMatrix rotMat;
+
+ x /= mag;
+ y /= mag;
+ z /= mag;
+
+ xx = x * x;
+ yy = y * y;
+ zz = z * z;
+ xy = x * y;
+ yz = y * z;
+ zx = z * x;
+ xs = x * sinAngle;
+ ys = y * sinAngle;
+ zs = z * sinAngle;
+ oneMinusCos = 1.0f - cosAngle;
+
+ rotMat.m[0][0] = (oneMinusCos * xx) + cosAngle;
+ rotMat.m[0][1] = (oneMinusCos * xy) - zs;
+ rotMat.m[0][2] = (oneMinusCos * zx) + ys;
+ rotMat.m[0][3] = 0.0F;
+
+ rotMat.m[1][0] = (oneMinusCos * xy) + zs;
+ rotMat.m[1][1] = (oneMinusCos * yy) + cosAngle;
+ rotMat.m[1][2] = (oneMinusCos * yz) - xs;
+ rotMat.m[1][3] = 0.0F;
+
+ rotMat.m[2][0] = (oneMinusCos * zx) - ys;
+ rotMat.m[2][1] = (oneMinusCos * yz) + xs;
+ rotMat.m[2][2] = (oneMinusCos * zz) + cosAngle;
+ rotMat.m[2][3] = 0.0F;
+
+ rotMat.m[3][0] = 0.0F;
+ rotMat.m[3][1] = 0.0F;
+ rotMat.m[3][2] = 0.0F;
+ rotMat.m[3][3] = 1.0F;
+
+ esMatrixMultiply( result, &rotMat, result );
+ }
+}
+
+void ESUTIL_API
+esFrustum(ESMatrix *result, float left, float right, float bottom, float top, float nearZ, float farZ)
+{
+ float deltaX = right - left;
+ float deltaY = top - bottom;
+ float deltaZ = farZ - nearZ;
+ ESMatrix frust;
+
+ if ( (nearZ <= 0.0f) || (farZ <= 0.0f) ||
+ (deltaX <= 0.0f) || (deltaY <= 0.0f) || (deltaZ <= 0.0f) )
+ return;
+
+ frust.m[0][0] = 2.0f * nearZ / deltaX;
+ frust.m[0][1] = frust.m[0][2] = frust.m[0][3] = 0.0f;
+
+ frust.m[1][1] = 2.0f * nearZ / deltaY;
+ frust.m[1][0] = frust.m[1][2] = frust.m[1][3] = 0.0f;
+
+ frust.m[2][0] = (right + left) / deltaX;
+ frust.m[2][1] = (top + bottom) / deltaY;
+ frust.m[2][2] = -(nearZ + farZ) / deltaZ;
+ frust.m[2][3] = -1.0f;
+
+ frust.m[3][2] = -2.0f * nearZ * farZ / deltaZ;
+ frust.m[3][0] = frust.m[3][1] = frust.m[3][3] = 0.0f;
+
+ esMatrixMultiply(result, &frust, result);
+}
+
+
+void ESUTIL_API
+esPerspective(ESMatrix *result, float fovy, float aspect, float nearZ, float farZ)
+{
+ GLfloat frustumW, frustumH;
+
+ frustumH = tanf( fovy / 360.0f * PI ) * nearZ;
+ frustumW = frustumH * aspect;
+
+ esFrustum( result, -frustumW, frustumW, -frustumH, frustumH, nearZ, farZ );
+}
+
+void ESUTIL_API
+esOrtho(ESMatrix *result, float left, float right, float bottom, float top, float nearZ, float farZ)
+{
+ float deltaX = right - left;
+ float deltaY = top - bottom;
+ float deltaZ = farZ - nearZ;
+ ESMatrix ortho;
+
+ if ( (deltaX == 0.0f) || (deltaY == 0.0f) || (deltaZ == 0.0f) )
+ return;
+
+ esMatrixLoadIdentity(&ortho);
+ ortho.m[0][0] = 2.0f / deltaX;
+ ortho.m[3][0] = -(right + left) / deltaX;
+ ortho.m[1][1] = 2.0f / deltaY;
+ ortho.m[3][1] = -(top + bottom) / deltaY;
+ ortho.m[2][2] = -2.0f / deltaZ;
+ ortho.m[3][2] = -(nearZ + farZ) / deltaZ;
+
+ esMatrixMultiply(result, &ortho, result);
+}
+
+
+void ESUTIL_API
+esMatrixMultiply(ESMatrix *result, ESMatrix *srcA, ESMatrix *srcB)
+{
+ ESMatrix tmp;
+ int i;
+
+ for (i=0; i<4; i++)
+ {
+ tmp.m[i][0] = (srcA->m[i][0] * srcB->m[0][0]) +
+ (srcA->m[i][1] * srcB->m[1][0]) +
+ (srcA->m[i][2] * srcB->m[2][0]) +
+ (srcA->m[i][3] * srcB->m[3][0]) ;
+
+ tmp.m[i][1] = (srcA->m[i][0] * srcB->m[0][1]) +
+ (srcA->m[i][1] * srcB->m[1][1]) +
+ (srcA->m[i][2] * srcB->m[2][1]) +
+ (srcA->m[i][3] * srcB->m[3][1]) ;
+
+ tmp.m[i][2] = (srcA->m[i][0] * srcB->m[0][2]) +
+ (srcA->m[i][1] * srcB->m[1][2]) +
+ (srcA->m[i][2] * srcB->m[2][2]) +
+ (srcA->m[i][3] * srcB->m[3][2]) ;
+
+ tmp.m[i][3] = (srcA->m[i][0] * srcB->m[0][3]) +
+ (srcA->m[i][1] * srcB->m[1][3]) +
+ (srcA->m[i][2] * srcB->m[2][3]) +
+ (srcA->m[i][3] * srcB->m[3][3]) ;
+ }
+ memcpy(result, &tmp, sizeof(ESMatrix));
+}
+
+
+void ESUTIL_API
+esMatrixLoadIdentity(ESMatrix *result)
+{
+ memset(result, 0x0, sizeof(ESMatrix));
+ result->m[0][0] = 1.0f;
+ result->m[1][1] = 1.0f;
+ result->m[2][2] = 1.0f;
+ result->m[3][3] = 1.0f;
+}
+
diff --git a/src/es/esUtil.c b/src/es/esUtil.c
new file mode 100644
index 0000000..4b0898c
--- /dev/null
+++ b/src/es/esUtil.c
@@ -0,0 +1,428 @@
+//
+// Book: OpenGL(R) ES 2.0 Programming Guide
+// Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner
+// ISBN-10: 0321502795
+// ISBN-13: 9780321502797
+// Publisher: Addison-Wesley Professional
+// URLs: http://safari.informit.com/9780321563835
+// http://www.opengles-book.com
+//
+
+// ESUtil.c
+//
+// A utility library for OpenGL ES. This library provides a
+// basic common framework for the example applications in the
+// OpenGL ES 2.0 Programming Guide.
+//
+
+///
+// Includes
+//
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <sys/time.h>
+#include <GLES2/gl2.h>
+#include <EGL/egl.h>
+#include "esUtil.h"
+
+#include <X11/Xlib.h>
+#include <X11/Xatom.h>
+#include <X11/Xutil.h>
+
+// X11 related local variables
+static Display *x_display = NULL;
+
+void tgOpenVGCreateContext(ESContext *esContext);
+
+///
+// CreateEGLContext()
+//
+// Creates an EGL rendering context and all associated elements
+//
+EGLBoolean CreateEGLContext ( EGLNativeWindowType hWnd, EGLDisplay* eglDisplay,
+ EGLContext* eglContext, EGLSurface* eglSurface,
+ EGLConfig *eglConfig,
+ EGLint attribList[])
+{
+ EGLint numConfigs;
+ EGLint majorVersion;
+ EGLint minorVersion;
+ EGLDisplay display;
+ EGLContext context;
+ EGLSurface surface;
+ EGLConfig config;
+ EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE };
+
+ // Get Display
+ display = eglGetDisplay((EGLNativeDisplayType)x_display);
+ if ( display == EGL_NO_DISPLAY )
+ {
+ return EGL_FALSE;
+ }
+
+ // Initialize EGL
+ if ( !eglInitialize(display, &majorVersion, &minorVersion) )
+ {
+ return EGL_FALSE;
+ }
+
+ // Get configs
+ if ( !eglGetConfigs(display, NULL, 0, &numConfigs) )
+ {
+ return EGL_FALSE;
+ }
+
+ // Choose config
+ if ( !eglChooseConfig(display, attribList, &config, 1, &numConfigs) )
+ {
+ return EGL_FALSE;
+ }
+
+ // Create a surface
+ surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)hWnd, NULL);
+ if ( surface == EGL_NO_SURFACE )
+ {
+ return EGL_FALSE;
+ }
+
+ // Create a GL context
+ context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs );
+ if ( context == EGL_NO_CONTEXT )
+ {
+ return EGL_FALSE;
+ }
+
+ // Make the context current
+ if ( !eglMakeCurrent(display, surface, surface, context) )
+ {
+ return EGL_FALSE;
+ }
+
+ *eglDisplay = display;
+ *eglSurface = surface;
+ *eglContext = context;
+ *eglConfig = config;
+ return EGL_TRUE;
+}
+
+
+///
+// WinCreate()
+//
+// This function initialized the native X11 display and window for EGL
+//
+EGLBoolean WinCreate(ESContext *esContext, const char *title)
+{
+ Window root;
+ XSetWindowAttributes swa;
+ XSetWindowAttributes xattr;
+ Atom wm_state;
+ XWMHints hints;
+ XEvent xev;
+ EGLConfig ecfg;
+ EGLint num_config;
+ Window win;
+
+ /*
+ * X11 native display initialization
+ */
+
+ x_display = XOpenDisplay(NULL);
+ if ( x_display == NULL )
+ {
+ return EGL_FALSE;
+ }
+
+ root = DefaultRootWindow(x_display);
+
+ swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask;
+ win = XCreateWindow(
+ x_display, root,
+ 0, 0, esContext->width, esContext->height, 0,
+ CopyFromParent, InputOutput,
+ CopyFromParent, CWEventMask,
+ &swa );
+
+ xattr.override_redirect = FALSE;
+ XChangeWindowAttributes ( x_display, win, CWOverrideRedirect, &xattr );
+
+ hints.input = TRUE;
+ hints.flags = InputHint;
+ XSetWMHints(x_display, win, &hints);
+
+ // make the window visible on the screen
+ XMapWindow (x_display, win);
+ XStoreName (x_display, win, title);
+
+ // get identifiers for the provided atom name strings
+ wm_state = XInternAtom (x_display, "_NET_WM_STATE", FALSE);
+
+ memset ( &xev, 0, sizeof(xev) );
+ xev.type = ClientMessage;
+ xev.xclient.window = win;
+ xev.xclient.message_type = wm_state;
+ xev.xclient.format = 32;
+ xev.xclient.data.l[0] = 1;
+ xev.xclient.data.l[1] = FALSE;
+ XSendEvent (
+ x_display,
+ DefaultRootWindow ( x_display ),
+ FALSE,
+ SubstructureNotifyMask,
+ &xev );
+
+ esContext->hWnd = (EGLNativeWindowType) win;
+ return EGL_TRUE;
+}
+
+
+///
+// userInterrupt()
+//
+// Reads from X11 event loop and interrupt program if there is a keypress, or
+// window close action.
+//
+GLboolean userInterrupt(ESContext *esContext)
+{
+ XEvent xev;
+ KeySym key;
+ GLboolean userinterrupt = GL_FALSE;
+ char text;
+
+ // Pump all messages from X server. Keypresses are directed to keyfunc (if defined)
+ while ( XPending ( x_display ) )
+ {
+ XNextEvent( x_display, &xev );
+ if ( xev.type == KeyPress )
+ {
+ if (XLookupString(&xev.xkey,&text,1,&key,0)==1)
+ {
+ if (esContext->keyFunc != NULL)
+ esContext->keyFunc(esContext, text, 0, 0);
+ }
+ }
+ if ( xev.type == DestroyNotify )
+ userinterrupt = GL_TRUE;
+ }
+ return userinterrupt;
+}
+
+
+//////////////////////////////////////////////////////////////////
+//
+// Public Functions
+//
+//
+
+///
+// esInitContext()
+//
+// Initialize ES utility context. This must be called before calling any other
+// functions.
+//
+void ESUTIL_API esInitContext ( ESContext *esContext )
+{
+ if ( esContext != NULL )
+ {
+ memset( esContext, 0, sizeof( ESContext) );
+ }
+}
+
+
+///
+// esCreateWindow()
+//
+// title - name for title bar of window
+// width - width of window to create
+// height - height of window to create
+// flags - bitwise or of window creation flags
+// ES_WINDOW_ALPHA - specifies that the framebuffer should have alpha
+// ES_WINDOW_DEPTH - specifies that a depth buffer should be created
+// ES_WINDOW_STENCIL - specifies that a stencil buffer should be created
+// ES_WINDOW_MULTISAMPLE - specifies that a multi-sample buffer should be created
+//
+GLboolean ESUTIL_API esCreateWindow ( ESContext *esContext, const char* title, GLint width, GLint height, GLuint flags )
+{
+ EGLint attribList[] =
+ {
+ EGL_RED_SIZE, 5,
+ EGL_GREEN_SIZE, 6,
+ EGL_BLUE_SIZE, 5,
+ EGL_ALPHA_SIZE, (flags & ES_WINDOW_ALPHA) ? 8 : EGL_DONT_CARE,
+ EGL_DEPTH_SIZE, (flags & ES_WINDOW_DEPTH) ? 8 : EGL_DONT_CARE,
+ EGL_STENCIL_SIZE, (flags & ES_WINDOW_STENCIL) ? 8 : EGL_DONT_CARE,
+ EGL_SAMPLE_BUFFERS, (flags & ES_WINDOW_MULTISAMPLE) ? 1 : 0,
+ EGL_NONE
+ };
+
+ if ( esContext == NULL )
+ {
+ return GL_FALSE;
+ }
+
+ esContext->width = width;
+ esContext->height = height;
+
+ if ( !WinCreate ( esContext, title) )
+ {
+ return GL_FALSE;
+ }
+
+
+ if ( !CreateEGLContext ( esContext->hWnd,
+ &esContext->eglDisplay,
+ &esContext->eglContext,
+ &esContext->eglSurface,
+ &esContext->eglConfig,
+ attribList) )
+ {
+ return GL_FALSE;
+ }
+
+
+ // create VG side of the context
+ tgOpenVGCreateContext(esContext);
+
+ return GL_TRUE;
+}
+
+
+///
+// esMainLoop()
+//
+// Start the main loop for the OpenGL ES application
+//
+
+void ESUTIL_API esMainLoop ( ESContext *esContext )
+{
+ struct timeval t1, t2;
+ struct timezone tz;
+ float deltatime;
+ float totaltime = 0.0f;
+ unsigned int frames = 0;
+
+ gettimeofday ( &t1 , &tz );
+
+ while(userInterrupt(esContext) == GL_FALSE)
+ {
+ gettimeofday(&t2, &tz);
+ deltatime = (float)(t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) * 1e-6);
+ t1 = t2;
+
+ if (esContext->updateFunc != NULL)
+ esContext->updateFunc(esContext, deltatime);
+ if (esContext->drawFunc != NULL)
+ esContext->drawFunc(esContext);
+
+ eglSwapBuffers(esContext->eglDisplay, esContext->eglSurface);
+
+ totaltime += deltatime;
+ frames++;
+ if (totaltime > 2.0f)
+ {
+ printf("%4d frames rendered in %1.4f seconds -> FPS=%3.4f\n", frames, totaltime, frames/totaltime);
+ totaltime -= 2.0f;
+ frames = 0;
+ }
+ }
+}
+
+
+///
+// esRegisterDrawFunc()
+//
+void ESUTIL_API esRegisterDrawFunc ( ESContext *esContext, void (ESCALLBACK *drawFunc) (ESContext* ) )
+{
+ esContext->drawFunc = drawFunc;
+}
+
+
+///
+// esRegisterUpdateFunc()
+//
+void ESUTIL_API esRegisterUpdateFunc ( ESContext *esContext, void (ESCALLBACK *updateFunc) ( ESContext*, float ) )
+{
+ esContext->updateFunc = updateFunc;
+}
+
+
+///
+// esRegisterKeyFunc()
+//
+void ESUTIL_API esRegisterKeyFunc ( ESContext *esContext,
+ void (ESCALLBACK *keyFunc) (ESContext*, unsigned char, int, int ) )
+{
+ esContext->keyFunc = keyFunc;
+}
+
+
+///
+// esLogMessage()
+//
+// Log an error message to the debug output for the platform
+//
+void ESUTIL_API esLogMessage ( const char *formatStr, ... )
+{
+ va_list params;
+ char buf[BUFSIZ];
+
+ va_start ( params, formatStr );
+ vsprintf ( buf, formatStr, params );
+
+ printf ( "%s", buf );
+
+ va_end ( params );
+}
+
+
+///
+// esLoadTGA()
+//
+// Loads a 24-bit TGA image from a file. This is probably the simplest TGA loader ever.
+// Does not support loading of compressed TGAs nor TGAa with alpha channel. But for the
+// sake of the examples, this is sufficient.
+//
+
+char* ESUTIL_API esLoadTGA ( char *fileName, int *width, int *height )
+{
+ char *buffer = NULL;
+ FILE *f;
+ unsigned char tgaheader[12];
+ unsigned char attributes[6];
+ unsigned int imagesize;
+
+ f = fopen(fileName, "rb");
+ if(f == NULL) return NULL;
+
+ if(fread(&tgaheader, sizeof(tgaheader), 1, f) == 0)
+ {
+ fclose(f);
+ return NULL;
+ }
+
+ if(fread(attributes, sizeof(attributes), 1, f) == 0)
+ {
+ fclose(f);
+ return 0;
+ }
+
+ *width = attributes[1] * 256 + attributes[0];
+ *height = attributes[3] * 256 + attributes[2];
+ imagesize = attributes[4] / 8 * *width * *height;
+ buffer = malloc(imagesize);
+ if (buffer == NULL)
+ {
+ fclose(f);
+ return 0;
+ }
+
+ if(fread(buffer, 1, imagesize, f) != imagesize)
+ {
+ free(buffer);
+ return NULL;
+ }
+ fclose(f);
+ return buffer;
+}
diff --git a/src/vg/Api.cpp b/src/vg/Api.cpp
new file mode 100644
index 0000000..5b97a50
--- /dev/null
+++ b/src/vg/Api.cpp
@@ -0,0 +1,3672 @@
+/*------------------------------------------------------------------------
+ *
+ * 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 Implementations of OpenVG API functions.
+ * \note The actual processing is done in Path, Image, Rasterizer and PixelPipe classes.
+ *//*-------------------------------------------------------------------*/
+
+#include "VG/openvg.h"
+#include "EGL/egl.h"
+#include "Context.h"
+#include "Rasterizer.h"
+#include "PixelPipe.h"
+#include "Path.h"
+#include <stdio.h>
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+/* EGL&OS functions for use in an OpenVG implementation */
+void* eglvgGetCurrentVGContext(void);
+bool eglvgIsInUse(void* image);
+void OSAcquireMutex(void);
+void OSReleaseMutex(void);
+
+
+#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 tgOpenVG;
+
+/*-------------------------------------------------------------------*//*!
+* \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);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+namespace tgOpenVG
+{
+
+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_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_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<Rectangle> scissor;
+ for(int i=0;i<RI_INT_MIN(count, RI_MAX_SCISSOR_RECTANGLES*4);i+=4)
+ {
+ 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:
+ 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);
+ paint->m_paintColor = inputColor(paint->m_inputPaintColor);
+ paint->m_paintColor.clamp();
+ paint->m_paintColor.premultiply();
+ 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
+ }
+ 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->m_linearGradientPoint0 = inputVector2(paint->m_inputLinearGradientPoint0);
+ paint->m_linearGradientPoint1 = 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->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().format));
+ intToParam(values, floats, count, 0, image->getDescriptor().format);
+ 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;
+ 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;
+ 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;
+ 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;
+ 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;
+ 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);
+ bool isImage = context->isValidImage(mask);
+ bool isMaskLayer = context->isValidMaskLayer(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((Image*)mask, operation, x, y, width, height);
+ else
+ drawable->getMaskBuffer()->mask((Surface*)mask, operation, x, y, width, height);
+ RI_RETURN(RI_NO_RETVAL);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static void renderStroke(const VGContext* context, int w, int h, int numSamples, Path* path, Rasterizer& rasterizer, const PixelPipe* pixelPipe, const Matrix3x3& userToSurface)
+{
+ RI_ASSERT(context);
+ RI_ASSERT(w > 0 && h > 0 && numSamples >= 1 && numSamples <= 32);
+
+ RIuint32* covBuffer = RI_NEW_ARRAY(RIuint32, w*h);
+ memset(covBuffer, 0, w*h*sizeof(RIuint32));
+
+ rasterizer.setup(0, 0, w, h, VG_NON_ZERO, NULL, covBuffer);
+ path->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
+
+ int sx,sy,ex,ey;
+ rasterizer.getBBox(sx,sy,ex,ey);
+ RI_ASSERT(sx >= 0 && sx <= w);
+ RI_ASSERT(sy >= 0 && sy <= h);
+ RI_ASSERT(ex >= 0 && ex <= w);
+ RI_ASSERT(ey >= 0 && ey <= h);
+
+ for(int j=sy;j<ey;j++)
+ {
+ for(int i=sx;i<ex;i++)
+ {
+ unsigned int c = covBuffer[j*w+i];
+ if(c)
+ {
+ int coverage = 0;
+ for(int k=0;k<numSamples;k++)
+ {
+ if(c & (1<<k))
+ coverage++;
+ }
+ pixelPipe->pixelPipe(i, j, (RIfloat)coverage/(RIfloat)numSamples, c);
+ }
+ }
+ }
+ RI_DELETE_ARRAY(covBuffer);
+}
+
+void RI_APIENTRY vgRenderToMask(VGPath path, VGbitfield paintModes, VGMaskOperation operation)
+{
+ 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();
+ 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)
+ {
+ Surface* dummy = NULL;
+ curr->getMaskBuffer()->mask(dummy, operation, 0, 0, curr->getWidth(), curr->getHeight());
+ RI_RETURN(RI_NO_RETVAL);
+ }
+
+ try
+ {
+ 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;
+ if(context->m_scissoring)
+ rasterizer.setScissor(context->m_scissor); //throws bad_alloc
+ int numSamples = rasterizer.setupSamplingPattern(context->m_renderingQuality, drawable.getNumSamples());
+
+ PixelPipe pixelPipe;
+ pixelPipe.setDrawable(&drawable);
+ pixelPipe.setMask(false);
+ pixelPipe.setPaint(NULL); //use default paint (solid color alpha = 1)
+ pixelPipe.setBlendMode(VG_BLEND_SRC); //write solid color * coverage to dest
+
+ Matrix3x3 userToSurface = context->m_pathUserToSurface;
+ userToSurface[2].set(0,0,1); //force affinity
+
+ if(paintModes & VG_FILL_PATH)
+ {
+ drawable.getColorBuffer()->clear(Color(0,0,0,0,drawable.getColorBuffer()->getDescriptor().internalFormat), 0, 0, drawable.getWidth(), drawable.getHeight());
+ ((Path*)path)->fill(userToSurface, rasterizer); //throws bad_alloc
+ rasterizer.setup(0, 0, drawable.getWidth(), drawable.getHeight(), context->m_fillRule, &pixelPipe, NULL);
+ rasterizer.fill(); //throws bad_alloc
+ curr->getMaskBuffer()->mask(drawable.getColorBuffer(), operation, 0, 0, drawable.getWidth(), drawable.getHeight());
+ }
+
+ if(paintModes & VG_STROKE_PATH && context->m_strokeLineWidth > 0.0f)
+ {
+ drawable.getColorBuffer()->clear(Color(0,0,0,0,drawable.getColorBuffer()->getDescriptor().internalFormat), 0, 0, drawable.getWidth(), drawable.getHeight());
+ renderStroke(context, drawable.getWidth(), drawable.getHeight(), numSamples, (Path*)path, rasterizer, &pixelPipe, userToSurface);
+ curr->getMaskBuffer()->mask(drawable.getColorBuffer(), operation, 0, 0, drawable.getWidth(), drawable.getHeight());
+ }
+ }
+ 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
+ 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)
+{
+ //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;
+ if(context->m_scissoring)
+ rasterizer.setScissor(context->m_scissor); //throws bad_alloc
+ int numSamples = rasterizer.setupSamplingPattern(context->m_renderingQuality, drawable->getNumSamples());
+
+ PixelPipe pixelPipe;
+ pixelPipe.setDrawable(drawable);
+ 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);
+
+ Matrix3x3 userToSurface = userToSurfaceMatrix;
+ userToSurface[2].set(0,0,1); //force affinity
+
+ if(paintModes & VG_FILL_PATH)
+ {
+ pixelPipe.setPaint((Paint*)context->m_fillPaint);
+
+ Matrix3x3 surfaceToPaintMatrix = userToSurface * context->m_fillPaintToUser;
+ if(surfaceToPaintMatrix.invert())
+ {
+ surfaceToPaintMatrix[2].set(0,0,1); //force affinity
+ pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+
+ rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), context->m_fillRule, &pixelPipe, NULL);
+ ((Path*)path)->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 surfaceToPaintMatrix = userToSurface * context->m_strokePaintToUser;
+ if(surfaceToPaintMatrix.invert())
+ {
+ surfaceToPaintMatrix[2].set(0,0,1); //force affinity
+ pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix);
+
+ renderStroke(context, drawable->getWidth(), drawable->getHeight(), numSamples, (Path*)path, rasterizer, &pixelPipe, userToSurface);
+ }
+ }
+ 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
+ {
+ if(!drawPath(context, path, context->m_pathUserToSurface, paintModes))
+ {
+ 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
+*//*-------------------------------------------------------------------*/
+
+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);
+ OSAcquireMutex();
+ VGContext* context = (VGContext*)eglvgGetCurrentVGContext();
+ if(!context)
+ {
+ OSReleaseMutex();
+ return VG_INVALID_HANDLE;
+ }
+ Paint* paint = NULL;
+ try
+ {
+ paint = RI_NEW(Paint, ()); //throws bad_alloc
+ RI_ASSERT(paint);
+ context->m_paintManager->addResource(paint, context); //throws bad_alloc
+ 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_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_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->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
+ unsigned int ret = ((Paint*)paint)->m_inputPaintColor.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);
+ img->clear(context->m_clearColor, x, y, width, height);
+ 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(input, 0, 0, x, y, width, height, false); //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(*img, x, y, 0, 0, width, height, false); //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(*(Image*)src, sx, sy, dx, dy, width, height, 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;
+ if(context->m_scissoring)
+ rasterizer.setScissor(context->m_scissor); //throws bad_alloc
+ rasterizer.setupSamplingPattern(context->m_renderingQuality, drawable->getNumSamples());
+
+ PixelPipe pixelPipe;
+ pixelPipe.setTileFillColor(context->m_tileFillColor);
+ pixelPipe.setPaint((Paint*)context->m_fillPaint);
+ pixelPipe.setImageQuality(context->m_imageQuality);
+ pixelPipe.setBlendMode(context->m_blendMode);
+ pixelPipe.setDrawable(drawable);
+ pixelPipe.setMask(context->m_masking ? true : false);
+ pixelPipe.setColorTransform(context->m_colorTransform ? true : false, context->m_colorTransformValues);
+
+ 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);
+
+ 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.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_EVEN_ODD, &pixelPipe, NULL);
+ 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();
+ if(!drawable)
+ {
+ RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment
+ }
+ try
+ {
+ if(context->m_scissoring)
+ drawable->getColorBuffer()->blit(*(Image*)src, sx, sy, dx, dy, width, height, context->m_scissor); //throws bad_alloc
+ else
+ 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
+ }
+ {
+ Image input(Color::formatToDescriptor(dataFormat), width, height, dataStride, const_cast<RIuint8*>((const RIuint8*)data));
+ input.addReference();
+ try
+ {
+ if(context->m_scissoring)
+ drawable->getColorBuffer()->blit(input, 0, 0, dx, dy, width, height, context->m_scissor); //throws bad_alloc
+ else
+ drawable->getColorBuffer()->blit(input, 0, 0, dx, dy, width, height); //throws bad_alloc
+ }
+ catch(std::bad_alloc)
+ {
+ }
+ 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(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 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(drawable->getColorBuffer(), 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();
+ if(!drawable)
+ {
+ RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment
+ }
+ try
+ {
+ if(context->m_scissoring)
+ drawable->getColorBuffer()->blit(drawable->getColorBuffer(), sx, sy, dx, dy, width, height, context->m_scissor); //throws bad_alloc
+ else
+ 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[] = "Khronos Group";
+ static const VGubyte renderer[] = {"OpenVG 1.1 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, VGfloat glyphOrigin[2], 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, VGfloat glyphOrigin[2], 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;
+ 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;
+ 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, VGuint *glyphIndices, VGfloat *adjustments_x, 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);
+}
diff --git a/src/vg/Api.cpp.tg b/src/vg/Api.cpp.tg
new file mode 100644
index 0000000..4f8a94f
--- /dev/null
+++ b/src/vg/Api.cpp.tg
@@ -0,0 +1,37 @@
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "egl.h"
+#include "openvg.h"
+
+namespace tgOpenVG {
+
+VGPaint RI_APIENTRY vgCreatePaint(void) {
+
+ RI_GET_CONTEXT(VG_INVALID_HANDLE);
+ Paint* paint = NULL;
+ try
+ {
+ paint = RI_NEW(Paint, ()); //throws bad_alloc
+ RI_ASSERT(paint);
+ context->m_paintManager->addResource(paint, context); //throws bad_alloc
+ RI_RETURN((VGPaint)paint);
+ }
+ catch(std::bad_alloc)
+ {
+ RI_DELETE(paint);
+ context->setError(VG_OUT_OF_MEMORY_ERROR);
+ RI_RETURN(VG_INVALID_HANDLE);
+ }
+}
+
+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);
+}
+
+}
diff --git a/src/vg/Array.h b/src/vg/Array.h
new file mode 100644
index 0000000..3d10a6f
--- /dev/null
+++ b/src/vg/Array.h
@@ -0,0 +1,209 @@
+#ifndef __ARRAY_H
+#define __ARRAY_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 Array class.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "Defs.h"
+
+#include <string.h> //for memcpy
+
+namespace tgOpenVG
+{
+
+//=======================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \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:
+ 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);
+ }
+
+ //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;
+ }
+
+ 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;
+ }
+ inline int size() const { return m_size; }
+ inline Item& operator[](int i) { RI_ASSERT(i >= 0 && i < m_size); return m_array[i]; }
+ 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 tgOpenVG
+
+#endif /* __ARRAY_H */
diff --git a/src/vg/Context.cpp b/src/vg/Context.cpp
new file mode 100644
index 0000000..f1fee49
--- /dev/null
+++ b/src/vg/Context.cpp
@@ -0,0 +1,329 @@
+/*------------------------------------------------------------------------
+ *
+ * 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 "Context.h"
+
+namespace tgOpenVG
+{
+
+/*-------------------------------------------------------------------*//*!
+* \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(tgOpenVG::ResourceManager<Image>, ()); //throws bad_alloc
+ m_pathManager = RI_NEW(tgOpenVG::ResourceManager<Path>, ()); //throws bad_alloc
+ m_paintManager = RI_NEW(tgOpenVG::ResourceManager<Paint>, ()); //throws bad_alloc
+ m_fontManager = RI_NEW(tgOpenVG::ResourceManager<Font>, ()); //throws bad_alloc
+ m_maskLayerManager = RI_NEW(tgOpenVG::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 tgOpenVG
diff --git a/src/vg/Context.h b/src/vg/Context.h
new file mode 100644
index 0000000..05aad3a
--- /dev/null
+++ b/src/vg/Context.h
@@ -0,0 +1,257 @@
+#ifndef __CONTEXT_H
+#define __CONTEXT_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
+ *//*-------------------------------------------------------------------*/
+
+#include <VG/openvg.h>
+#include "Defs.h"
+#include "Math.h"
+#include "Image.h"
+#include "Path.h"
+#include "Font.h"
+#include "Array.h"
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+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; }
+
+ 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];
+ 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;
+private:
+ Drawable* m_eglDrawable;
+
+ VGContext(const VGContext&); //!< Not allowed.
+ void operator=(const VGContext&); //!< Not allowed.
+};
+
+//==============================================================================================
+
+} //namespace tgOpenVG
+
+//==============================================================================================
+
+#endif /* __CONTEXT_H */
diff --git a/src/vg/Defs.h b/src/vg/Defs.h
new file mode 100644
index 0000000..4ef264e
--- /dev/null
+++ b/src/vg/Defs.h
@@ -0,0 +1,119 @@
+#ifndef __DEFS_H
+#define __DEFS_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 Platform- and compiler-dependent type and macro definitions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include <float.h>
+#include <math.h>
+#include <assert.h>
+#include <new> //for bad_alloc
+#include <cinttypes>
+
+namespace tgOpenVG
+{
+
+//=======================================================================
+
+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;
+
+
+typedef unsigned long RIuintptr;
+typedef signed long RIintptr;
+
+#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;
+
+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 32
+#define RI_NUM_TESSELLATED_SEGMENTS 256
+
+#define RI_DEBUG
+
+#ifdef RI_DEBUG
+# define RI_ASSERT assert
+#else
+# define RI_ASSERT
+#endif
+
+#define RI_UNREF(X) ((void)(X))
+#define RI_APIENTRY
+
+#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);
+
+//=======================================================================
+
+} //namespace tgOpenVG
+
+#endif /* __DEFS_H */
diff --git a/src/vg/EGLAddOn.cpp b/src/vg/EGLAddOn.cpp
new file mode 100644
index 0000000..e8da666
--- /dev/null
+++ b/src/vg/EGLAddOn.cpp
@@ -0,0 +1,868 @@
+/*------------------------------------------------------------------------
+ *
+ * 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 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 <pthread.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include <EGL/egl.h>
+#include "VG/openvg.h"
+#include "Array.h"
+#include "Math.h"
+#include "Context.h"
+#include "Image.h"
+#include "esUtil.h"
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+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);
+
+static pthread_mutex_t mutex;
+static int mutexRefCount = 0;
+static bool mutexInitialized = false;
+
+class RIEGLThread;
+
+void* OSGetCurrentThreadID(void)
+{
+ return (void*)pthread_self(); //TODO this is not safe
+}
+
+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
+*//*-------------------------------------------------------------------*/
+
+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)
+ {
+ m_desc.redBits = r;
+ m_desc.greenBits = g;
+ m_desc.blueBits = b;
+ m_desc.alphaBits = a;
+ m_desc.luminanceBits = l;
+ 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;
+ m_desc.format = (VGImageFormat)-1;
+ m_desc.internalFormat = l ? Color::sLA : Color::sRGBA;
+ m_desc.bitsPerPixel = bpp;
+ 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(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; }
+ const EGLConfig getConfig() const { return m_config; }
+private:
+ RIEGLContext(const RIEGLContext&);
+ RIEGLContext& operator=(const RIEGLContext&);
+ VGContext* m_vgContext;
+ const EGLConfig m_config;
+ int m_referenceCount;
+};
+
+RIEGLContext::RIEGLContext(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; }
+ const 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);
+ // TAG FIX ME OSDestroyWindowContext(m_OSWindowContext);
+ if(m_drawable)
+ {
+ if(!m_drawable->removeReference())
+ RI_DELETE(m_drawable);
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+#define EGL_NUMCONFIGS 60
+
+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]; }
+
+ const 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()
+{
+ RI_ASSERT(EGL_NUMCONFIGS == 60);
+
+ //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
+ m_configs[0].set(8, 8, 8, 8, 0, 32, 1, 8, 1); //EGL_RGB_BUFFER, buffer size = 32
+ m_configs[1].set(8, 8, 8, 0, 0, 32, 1, 8, 2); //EGL_RGB_BUFFER, buffer size = 24
+ m_configs[2].set(5, 5, 5, 1, 0, 16, 1, 4, 3); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[3].set(5, 6, 5, 0, 0, 16, 1, 4, 4); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[4].set(4, 4, 4, 4, 0, 16, 1, 4, 5); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[5].set(0, 0, 0, 8, 0, 8, 1, 8, 6); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[6].set(0, 0, 0, 4, 0, 4, 1, 4, 7); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[7].set(0, 0, 0, 1, 0, 1, 1, 1, 8); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[8].set(0, 0, 0, 0, 8, 8, 1, 8, 9); //EGL_LUMINANCE_BUFFER, buffer size = 8
+ m_configs[9].set(0, 0, 0, 0, 1, 1, 1, 1, 10); //EGL_LUMINANCE_BUFFER, buffer size = 1
+
+ m_configs[10].set(8, 8, 8, 8, 0, 32, 4, 1, 11); //EGL_RGB_BUFFER, buffer size = 32
+ m_configs[11].set(8, 8, 8, 0, 0, 32, 4, 1, 12); //EGL_RGB_BUFFER, buffer size = 24
+ m_configs[12].set(5, 5, 5, 1, 0, 16, 4, 1, 13); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[13].set(5, 6, 5, 0, 0, 16, 4, 1, 14); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[14].set(4, 4, 4, 4, 0, 16, 4, 1, 15); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[15].set(0, 0, 0, 8, 0, 8, 4, 1, 16); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[16].set(0, 0, 0, 4, 0, 4, 4, 1, 17); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[17].set(0, 0, 0, 1, 0, 1, 4, 1, 18); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[18].set(0, 0, 0, 0, 8, 8, 4, 1, 19); //EGL_LUMINANCE_BUFFER, buffer size = 8
+ m_configs[19].set(0, 0, 0, 0, 1, 1, 4, 1, 20); //EGL_LUMINANCE_BUFFER, buffer size = 1
+
+ m_configs[20].set(8, 8, 8, 8, 0, 32, 32, 1, 21); //EGL_RGB_BUFFER, buffer size = 32
+ m_configs[21].set(8, 8, 8, 0, 0, 32, 32, 1, 22); //EGL_RGB_BUFFER, buffer size = 24
+ m_configs[22].set(5, 5, 5, 1, 0, 16, 32, 1, 23); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[23].set(5, 6, 5, 0, 0, 16, 32, 1, 24); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[24].set(4, 4, 4, 4, 0, 16, 32, 1, 25); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[25].set(0, 0, 0, 8, 0, 8, 32, 1, 26); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[26].set(0, 0, 0, 4, 0, 4, 32, 1, 27); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[27].set(0, 0, 0, 1, 0, 1, 32, 1, 28); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[28].set(0, 0, 0, 0, 8, 8, 32, 1, 29); //EGL_LUMINANCE_BUFFER, buffer size = 8
+ m_configs[29].set(0, 0, 0, 0, 1, 1, 32, 1, 30); //EGL_LUMINANCE_BUFFER, buffer size = 1
+
+ //configs without mask
+ m_configs[30].set(8, 8, 8, 8, 0, 32, 1, 0, 31); //EGL_RGB_BUFFER, buffer size = 32
+ m_configs[31].set(8, 8, 8, 0, 0, 32, 1, 0, 32); //EGL_RGB_BUFFER, buffer size = 24
+ m_configs[32].set(5, 5, 5, 1, 0, 16, 1, 0, 33); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[33].set(5, 6, 5, 0, 0, 16, 1, 0, 34); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[34].set(4, 4, 4, 4, 0, 16, 1, 0, 35); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[35].set(0, 0, 0, 8, 0, 8, 1, 0, 36); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[36].set(0, 0, 0, 4, 0, 4, 1, 0, 37); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[37].set(0, 0, 0, 1, 0, 1, 1, 0, 38); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[38].set(0, 0, 0, 0, 8, 8, 1, 0, 39); //EGL_LUMINANCE_BUFFER, buffer size = 8
+ m_configs[39].set(0, 0, 0, 0, 1, 1, 1, 0, 40); //EGL_LUMINANCE_BUFFER, buffer size = 1
+
+ m_configs[40].set(8, 8, 8, 8, 0, 32, 4, 0, 41); //EGL_RGB_BUFFER, buffer size = 32
+ m_configs[41].set(8, 8, 8, 0, 0, 32, 4, 0, 42); //EGL_RGB_BUFFER, buffer size = 24
+ m_configs[42].set(5, 5, 5, 1, 0, 16, 4, 0, 43); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[43].set(5, 6, 5, 0, 0, 16, 4, 0, 44); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[44].set(4, 4, 4, 4, 0, 16, 4, 0, 45); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[45].set(0, 0, 0, 8, 0, 8, 4, 0, 46); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[46].set(0, 0, 0, 4, 0, 4, 4, 0, 47); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[47].set(0, 0, 0, 1, 0, 1, 4, 0, 48); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[48].set(0, 0, 0, 0, 8, 8, 4, 0, 49); //EGL_LUMINANCE_BUFFER, buffer size = 8
+ m_configs[49].set(0, 0, 0, 0, 1, 1, 4, 0, 50); //EGL_LUMINANCE_BUFFER, buffer size = 1
+
+ m_configs[50].set(8, 8, 8, 8, 0, 32, 32, 0, 51); //EGL_RGB_BUFFER, buffer size = 32
+ m_configs[51].set(8, 8, 8, 0, 0, 32, 32, 0, 52); //EGL_RGB_BUFFER, buffer size = 24
+ m_configs[52].set(5, 5, 5, 1, 0, 16, 32, 0, 53); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[53].set(5, 6, 5, 0, 0, 16, 32, 0, 54); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[54].set(4, 4, 4, 4, 0, 16, 32, 0, 55); //EGL_RGB_BUFFER, buffer size = 16
+ m_configs[55].set(0, 0, 0, 8, 0, 8, 32, 0, 56); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[56].set(0, 0, 0, 4, 0, 4, 32, 0, 57); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[57].set(0, 0, 0, 1, 0, 1, 32, 0, 58); //EGL_RGB_BUFFER, buffer size = 8
+ m_configs[58].set(0, 0, 0, 0, 8, 8, 32, 0, 59); //EGL_LUMINANCE_BUFFER, buffer size = 8
+ m_configs[59].set(0, 0, 0, 0, 1, 1, 32, 0, 60); //EGL_LUMINANCE_BUFFER, buffer size = 1
+/*
+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_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;
+ 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_displays(),
+ m_threads(),
+ m_currentThreads(),
+ 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
+*//*-------------------------------------------------------------------*/
+
+const 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
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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 tgOpenVG
+
+using namespace tgOpenVG;
+
+extern "C"
+void tgOpenVGCreateContext(ESContext *esContext) {
+
+ EGL* egl = getEGL();
+
+ RIEGLThread* thread = egl->getThread();
+ tgOpenVG::VGContext* vgctx = NULL;
+ RIEGLContext* c = NULL;
+
+ try {
+ vgctx = RI_NEW(tgOpenVG::VGContext, (NULL)); //throws bad_alloc
+ c = RI_NEW(RIEGLContext, (vgctx, esContext->eglConfig)); //throws bad_alloc
+ esContext->vgContext = vgctx;
+
+ }
+ catch (std::bad_alloc) {
+ }
+}
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static bool smaller(EGLint c, EGLint filter)
+{
+ return (filter != EGL_DONT_CARE) && (c < filter);
+}
+
diff --git a/src/vg/Font.cpp b/src/vg/Font.cpp
new file mode 100644
index 0000000..c63c129
--- /dev/null
+++ b/src/vg/Font.cpp
@@ -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 "Font.h"
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+/*-------------------------------------------------------------------*//*!
+* \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 tgOpenVG
diff --git a/src/vg/Font.h b/src/vg/Font.h
new file mode 100644
index 0000000..ca29cb7
--- /dev/null
+++ b/src/vg/Font.h
@@ -0,0 +1,102 @@
+#ifndef __FONT_H
+#define __FONT_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
+ *//*-------------------------------------------------------------------*/
+
+#include "VG/openvg.h"
+#include "Math.h"
+#include "Array.h"
+#include "Path.h"
+#include "Image.h"
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+/*-------------------------------------------------------------------*//*!
+* \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 tgOpenVG
+
+//=======================================================================
+
+#endif /* __FONT_H */
diff --git a/src/vg/Image.cpp b/src/vg/Image.cpp
new file mode 100644
index 0000000..1d3c407
--- /dev/null
+++ b/src/vg/Image.cpp
@@ -0,0 +1,2675 @@
+/*------------------------------------------------------------------------
+ *
+ * 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 Color and Image functions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "Image.h"
+#include "Rasterizer.h"
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+
+/*-------------------------------------------------------------------*//*!
+* \brief Converts from numBits into a shifted mask
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static 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
+*//*-------------------------------------------------------------------*/
+
+static unsigned int colorToInt(RIfloat c, int maxc)
+{
+ return RI_INT_MIN(RI_INT_MAX((int)floor(c * (RIfloat)maxc + 0.5f), 0), maxc);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief Converts from int to color (RIfloat) with the given maximum
+* mapped to 1.0f.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+static inline RIfloat intToColor(unsigned int i, unsigned int maxi)
+{
+ return (RIfloat)(i & maxi) / (RIfloat)maxi;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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 (cr << rs) | (cg << gs) | (cb << bs) | (ca << as);
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief Converts from the current internal format to another.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+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)
+{
+ 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
+*//*-------------------------------------------------------------------*/
+
+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.format = format;
+ desc.bitsPerPixel = bpps[baseFormat];
+ desc.internalFormat = internalFormats[baseFormat];
+
+ return desc;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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(rgbaBits && lb)
+ return false; //can't have both rgba and luminance
+ 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.format != -1)
+ {
+ if(!isValidImageFormat(desc.format))
+ return false; //invalid image format
+
+ Descriptor d = formatToDescriptor(desc.format);
+ 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;
+}
+
+//==============================================================================================
+
+
+
+
+//==============================================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \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_mipmapsValid(false),
+ m_mipmaps()
+{
+ 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
+*//*-------------------------------------------------------------------*/
+
+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_mipmapsValid(false),
+ m_mipmaps()
+{
+ RI_ASSERT(Color::isValidDescriptor(m_desc));
+ RI_ASSERT(width > 0 && height > 0);
+ RI_ASSERT(data);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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_mipmapsValid(false),
+ m_mipmaps()
+{
+ 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();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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);
+
+ for(int i=0;i<m_mipmaps.size();i++)
+ {
+ if(!m_mipmaps[i]->removeReference())
+ RI_DELETE(m_mipmaps[i]);
+ else
+ {
+ RI_ASSERT(0); //there can't be any other references to the mipmap levels
+ }
+ }
+ m_mipmaps.clear();
+
+ 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 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(m_desc.internalFormat);
+
+ for(int j=r.y;j<r.y + r.height;j++)
+ {
+ for(int i=r.x;i<r.x + r.width;i++)
+ {
+ writePixel(i, j, col);
+ }
+ }
+
+ m_mipmapsValid = false;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief Blits a source region to destination. Source and destination
+* can overlap.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+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);
+}
+
+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;
+}
+
+void Image::blit(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
+ 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);
+ }
+ }
+ m_mipmapsValid = false;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief Converts from multisampled format to display format.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Image::blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h)
+{
+ //fb=>img: vgGetPixels
+ //fb=>user: vgReadPixels
+ RI_ASSERT(!src->isInUse(this));
+
+ computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), m_width, m_height);
+ if(w <= 0 || h <= 0)
+ return; //zero area
+
+ for(int y=0;y<h;y++)
+ {
+ for(int x=0;x<w;x++)
+ {
+ Color r = src->FSAAResolve(sx + x, sy + y);
+ r.convert(getDescriptor().internalFormat);
+ writePixel(dx + x, dy + y, r);
+ }
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief Returns the color at pixel (x,y).
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+Color Image::readPixel(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);
+ x += m_storageOffsetX;
+ y += m_storageOffsetY;
+
+ unsigned int p = 0;
+ RIuint8* scanline = m_data + y * m_stride;
+ switch(m_desc.bitsPerPixel)
+ {
+ case 32:
+ {
+ RIuint32* s = (((RIuint32*)scanline) + x);
+ p = (unsigned int)*s;
+ break;
+ }
+
+ case 16:
+ {
+ RIuint16* s = ((RIuint16*)scanline) + x;
+ p = (unsigned int)*s;
+ break;
+ }
+
+ case 8:
+ {
+ RIuint8* s = ((RIuint8*)scanline) + x;
+ p = (unsigned int)*s;
+ break;
+ }
+
+ case 4:
+ {
+ RIuint8* s = ((RIuint8*)scanline) + (x>>1);
+ p = (unsigned int)(*s >> ((x&1)<<2)) & 0xf;
+ break;
+ }
+
+ case 2:
+ {
+ RIuint8* s = ((RIuint8*)scanline) + (x>>2);
+ p = (unsigned int)(*s >> ((x&3)<<1)) & 0x3;
+ break;
+ }
+
+ default:
+ {
+ RI_ASSERT(m_desc.bitsPerPixel == 1);
+ RIuint8* s = ((RIuint8*)scanline) + (x>>3);
+ p = (unsigned int)(*s >> (x&7)) & 0x1;
+ break;
+ }
+ }
+ 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(m_data);
+ RI_ASSERT(x >= 0 && x < m_width);
+ RI_ASSERT(y >= 0 && y < m_height);
+ RI_ASSERT(m_referenceCount > 0);
+ RI_ASSERT(c.getInternalFormat() == m_desc.internalFormat);
+ x += m_storageOffsetX;
+ y += m_storageOffsetY;
+
+ unsigned int p = c.pack(m_desc);
+ RIuint8* scanline = m_data + y * m_stride;
+ switch(m_desc.bitsPerPixel)
+ {
+ case 32:
+ {
+ RIuint32* s = ((RIuint32*)scanline) + x;
+ *s = (RIuint32)p;
+ break;
+ }
+
+ case 16:
+ {
+ RIuint16* s = ((RIuint16*)scanline) + x;
+ *s = (RIuint16)p;
+ break;
+ }
+
+ case 8:
+ {
+ RIuint8* s = ((RIuint8*)scanline) + x;
+ *s = (RIuint8)p;
+ break;
+ }
+ case 4:
+ {
+ RIuint8* s = ((RIuint8*)scanline) + (x>>1);
+ *s = (RIuint8)((p << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2))));
+ break;
+ }
+
+ case 2:
+ {
+ RIuint8* s = ((RIuint8*)scanline) + (x>>2);
+ *s = (RIuint8)((p << ((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)((p << (x&7)) | ((unsigned int)*s & ~(0x1 << (x&7))));
+ break;
+ }
+ }
+ m_mipmapsValid = false;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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(level <= m_mipmaps.size());
+ image = m_mipmaps[level-1];
+ }
+ 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(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 if(aq & VG_IMAGE_QUALITY_FASTER)
+ { //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
+ { //point sampling
+ return readTexel((int)floor(uvw.x), (int)floor(uvw.y), 0, tilingMode, tileFillColor);
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief Generates mip maps for an image.
+* \param
+* \return
+* \note Downsampling is done in the input color space. We use a box
+* filter for downsampling.
+*//*-------------------------------------------------------------------*/
+
+void Image::makeMipMaps()
+{
+ RI_ASSERT(m_data);
+ RI_ASSERT(m_referenceCount > 0);
+
+ if(m_mipmapsValid)
+ return;
+
+ //delete existing mipmaps
+ for(int i=0;i<m_mipmaps.size();i++)
+ {
+ if(!m_mipmaps[i]->removeReference())
+ RI_DELETE(m_mipmaps[i]);
+ else
+ {
+ RI_ASSERT(0); //there can't be any other references to the mipmap levels
+ }
+ }
+ m_mipmaps.clear();
+
+ try
+ {
+ Color::InternalFormat procFormat = m_desc.internalFormat;
+ procFormat = (Color::InternalFormat)(procFormat | Color::PREMULTIPLIED); //premultiplied
+
+ //generate mipmaps until width and height are one
+ Image* prev = this;
+ while( prev->m_width > 1 || prev->m_height > 1 )
+ {
+ int nextw = (int)ceil(prev->m_width*0.5f);
+ int nexth = (int)ceil(prev->m_height*0.5f);
+ RI_ASSERT(nextw >= 1 && nexth >= 1);
+ RI_ASSERT(nextw < prev->m_width || nexth < prev->m_height);
+
+ m_mipmaps.resize(m_mipmaps.size()+1); //throws bad_alloc
+ m_mipmaps[m_mipmaps.size()-1] = NULL;
+
+ Image* next = RI_NEW(Image, (m_desc, nextw, nexth, m_allowedQuality)); //throws bad_alloc
+ next->addReference();
+ for(int j=0;j<next->m_height;j++)
+ {
+ for(int i=0;i<next->m_width;i++)
+ {
+ RIfloat u0 = (RIfloat)i / (RIfloat)next->m_width;
+ RIfloat u1 = (RIfloat)(i+1) / (RIfloat)next->m_width;
+ RIfloat v0 = (RIfloat)j / (RIfloat)next->m_height;
+ RIfloat v1 = (RIfloat)(j+1) / (RIfloat)next->m_height;
+
+ u0 *= prev->m_width;
+ u1 *= prev->m_width;
+ v0 *= prev->m_height;
+ v1 *= prev->m_height;
+
+ int su = (int)floor(u0);
+ int eu = (int)ceil(u1);
+ int sv = (int)floor(v0);
+ int ev = (int)ceil(v1);
+
+ Color c(0,0,0,0,procFormat);
+ int samples = 0;
+ for(int y=sv;y<ev;y++)
+ {
+ for(int x=su;x<eu;x++)
+ {
+ Color p = prev->readPixel(x, y);
+ p.convert(procFormat);
+ c += p;
+ samples++;
+ }
+ }
+ c *= (1.0f/samples);
+ c.convert(m_desc.internalFormat);
+ next->writePixel(i,j,c);
+ }
+ }
+ m_mipmaps[m_mipmaps.size()-1] = next;
+ prev = next;
+ }
+ RI_ASSERT(prev->m_width == 1 && prev->m_height == 1);
+ m_mipmapsValid = true;
+ }
+ catch(std::bad_alloc)
+ {
+ //delete existing mipmaps
+ for(int i=0;i<m_mipmaps.size();i++)
+ {
+ if(m_mipmaps[i])
+ {
+ if(!m_mipmaps[i]->removeReference())
+ RI_DELETE(m_mipmaps[i]);
+ else
+ {
+ RI_ASSERT(0); //there can't be any other references to the mipmap levels
+ }
+ }
+ }
+ m_mipmaps.clear();
+ m_mipmapsValid = false;
+ throw;
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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)
+{
+ Rectangle rect;
+ rect.x = 0;
+ rect.y = 0;
+ rect.width = getWidth();
+ rect.height = getHeight();
+ Array<Rectangle> scissors;
+ scissors.push_back(rect);
+ clear(clearColor, x, y, w, h, scissors);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Surface::clear(const Color& clearColor, int x, int y, int w, int h, const Array<Rectangle>& scissors)
+{
+ RI_ASSERT(w > 0 && h > 0);
+
+ //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
+
+ 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();
+
+ //clear the image
+ Color col = clearColor;
+ col.clamp();
+ col.convert(m_image->getDescriptor().internalFormat);
+
+ Array<ScissorEdge> scissorAet;
+ for(int j=r.y;j<r.y + r.height;j++)
+ {
+ //gather scissor edges intersecting this scanline
+ scissorAet.clear();
+ for(int e=0;e<scissorEdges.size();e++)
+ {
+ const ScissorEdge& se = scissorEdges[e];
+ if(j >= se.miny && 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
+
+ //clear a scanline
+ int scissorWinding = 0;
+ int scissorIndex = 0;
+ for(int i=r.x;i<r.x + r.width;i++)
+ {
+ while(scissorIndex < scissorAet.size() && scissorAet[scissorIndex].x <= i)
+ scissorWinding += scissorAet[scissorIndex++].direction;
+ RI_ASSERT(scissorWinding >= 0);
+
+ if(scissorWinding)
+ {
+ for(int s=0;s<m_numSamples;s++)
+ writeSample(i, j, s, col);
+ }
+ }
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+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);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note no overlap is possible. Single sample to single or multisample (replicate)
+*//*-------------------------------------------------------------------*/
+
+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);
+ }
+ }
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+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);
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+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]);
+ }
+ }
+ }
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Surface::mask(const Image* src, VGMaskOperation operation, int x, int y, int w, int h)
+{
+ RI_ASSERT(w > 0 && h > 0);
+
+ 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
+
+ if(m_numSamples == 1)
+ {
+ RIfloat m = 0.0f;
+ if(operation == VG_FILL_MASK)
+ m = 1.0f;
+ for(int j=r.y;j<r.y + r.height;j++)
+ {
+ for(int i=r.x;i<r.x + r.width;i++)
+ {
+ writeMaskCoverage(i, j, m);
+ }
+ }
+ }
+ else
+ {
+ unsigned int m = 0;
+ if(operation == VG_FILL_MASK)
+ m = (1<<m_numSamples)-1;
+ for(int j=r.y;j<r.y + r.height;j++)
+ {
+ for(int i=r.x;i<r.x + r.width;i++)
+ {
+ writeMaskMSAA(i, j, m);
+ }
+ }
+ }
+ }
+ else
+ {
+ 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
+
+ if(m_numSamples == 1)
+ {
+ 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);
+ }
+ }
+ }
+ }
+ else
+ {
+ for(int j=0;j<h;j++)
+ {
+ for(int i=0;i<w;i++)
+ {
+ RIfloat fmask = src->readMaskPixel(sx + i, sy + j);
+ //TODO implement dithering?
+ unsigned int amask = fmask > 0.5f ? (1<<m_numSamples)-1 : 0;
+ if(operation == VG_SET_MASK)
+ writeMaskMSAA(dx + i, dy + j, amask);
+ else
+ {
+ unsigned int aprev = readMaskMSAA(dx + i, dy + j);
+ unsigned int anew = 0;
+ switch(operation)
+ {
+ case VG_UNION_MASK: anew = amask | aprev; break;
+ case VG_INTERSECT_MASK: anew = amask & aprev; break;
+ default: anew = ~amask & aprev; RI_ASSERT(operation == VG_SUBTRACT_MASK); break;
+ }
+ writeMaskMSAA(dx + i, dy + j, anew);
+ }
+ }
+ }
+ }
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+void Surface::mask(const Surface* src, VGMaskOperation operation, int x, int y, int w, int h)
+{
+ RI_ASSERT(w > 0 && h > 0);
+
+ 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
+
+ if(m_numSamples == 1)
+ {
+ RIfloat m = 0.0f;
+ if(operation == VG_FILL_MASK)
+ m = 1.0f;
+ for(int j=r.y;j<r.y + r.height;j++)
+ {
+ for(int i=r.x;i<r.x + r.width;i++)
+ {
+ writeMaskCoverage(i, j, m);
+ }
+ }
+ }
+ else
+ {
+ unsigned int m = 0;
+ if(operation == VG_FILL_MASK)
+ m = (1<<m_numSamples)-1;
+ for(int j=r.y;j<r.y + r.height;j++)
+ {
+ for(int i=r.x;i<r.x + r.width;i++)
+ {
+ writeMaskMSAA(i, j, m);
+ }
+ }
+ }
+ }
+ else
+ {
+ RI_ASSERT(src);
+ RI_ASSERT(m_numSamples == src->m_numSamples);
+
+ 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
+
+ if(m_numSamples == 1)
+ {
+ for(int j=0;j<h;j++)
+ {
+ for(int i=0;i<w;i++)
+ {
+ RIfloat amask = src->readMaskCoverage(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);
+ }
+ }
+ }
+ }
+ else
+ {
+ for(int j=0;j<h;j++)
+ {
+ for(int i=0;i<w;i++)
+ {
+ unsigned int amask = src->readMaskMSAA(sx + i, sy + j);
+ if(operation == VG_SET_MASK)
+ writeMaskMSAA(dx + i, dy + j, amask);
+ else
+ {
+ unsigned int aprev = readMaskMSAA(dx + i, dy + j);
+ unsigned int anew = 0;
+ switch(operation)
+ {
+ case VG_UNION_MASK: anew = amask | aprev; break;
+ case VG_INTERSECT_MASK: anew = amask & aprev; break;
+ default: anew = ~amask & aprev; RI_ASSERT(operation == VG_SUBTRACT_MASK); break;
+ }
+ writeMaskMSAA(dx + i, dy + j, anew);
+ }
+ }
+ }
+ }
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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
+* \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(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->blit(oldcolor, 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->blit(oldmask, 0, 0, 0, 0, wmin, hmin);
+ }
+
+ if(!oldcolor->removeReference())
+ RI_DELETE(oldcolor);
+ if(oldmask)
+ if(!oldmask->removeReference())
+ RI_DELETE(oldmask);
+}
+
+//==============================================================================================
+
+} //namespace OpenVGRI
+
+//==============================================================================================
diff --git a/src/vg/Image.h b/src/vg/Image.h
new file mode 100644
index 0000000..22af28f
--- /dev/null
+++ b/src/vg/Image.h
@@ -0,0 +1,371 @@
+#ifndef __IMAGE_H
+#define __IMAGE_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 Color and Image classes.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "VG/openvg.h"
+#include "Math.h"
+#include "Array.h"
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+/*-------------------------------------------------------------------*//*!
+* \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;
+ }
+ }
+
+ 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 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)
+ };
+ class Descriptor
+ {
+ public:
+ bool isNonlinear() const { return (internalFormat & NONLINEAR) ? true : false; }
+ bool isPremultiplied() const { return (internalFormat & PREMULTIPLIED) ? true : false; }
+ bool isLuminance() const { return (internalFormat & LUMINANCE) ? true : false; }
+ bool isAlphaOnly() const { return (alphaBits && (redBits+greenBits+blueBits+luminanceBits) == 0) ? true : false; }
+
+ int redBits;
+ int redShift;
+ int greenBits;
+ int greenShift;
+ int blueBits;
+ int blueShift;
+ int alphaBits;
+ int alphaShift;
+ int luminanceBits;
+ int luminanceShift;
+ VGImageFormat format;
+ InternalFormat internalFormat;
+ int bitsPerPixel;
+ };
+
+ inline Color() : r(0.0f), g(0.0f), b(0.0f), a(0.0f), m_format(lRGBA) {}
+ 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); }
+ 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); }
+ inline Color(const Color& c) : r(c.r), g(c.g), b(c.b), a(c.a), m_format(c.m_format) {}
+ 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; }
+ inline void operator*=(RIfloat f) { r *= f; g *= f; b *= f; a*= f; }
+ inline void operator+=(const Color& c1) { RI_ASSERT(m_format == c1.getInternalFormat()); r += c1.r; g += c1.g; b += c1.b; a += c1.a; }
+ 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;
+ 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; }
+
+ inline void assertConsistency() const;
+
+ static Descriptor formatToDescriptor(VGImageFormat format);
+ static bool isValidDescriptor(const Descriptor& desc);
+
+ RIfloat r;
+ RIfloat g;
+ RIfloat b;
+ RIfloat a;
+private:
+ InternalFormat m_format;
+};
+
+inline Color operator*(const Color& c, RIfloat f) { return Color(c.r*f, c.g*f, c.b*f, c.a*f, c.getInternalFormat()); }
+inline Color operator*(RIfloat f, const Color& c) { return Color(c.r*f, c.g*f, c.b*f, c.a*f, c.getInternalFormat()); }
+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()); }
+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()); }
+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
+}
+
+//==============================================================================================
+
+/*-------------------------------------------------------------------*//*!
+* \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 clear(const Color& clearColor, int x, int y, int w, int h);
+ void blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h, bool dither); //throws bad_alloc
+ void blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h); //throws bad_alloc
+
+ Color readPixel(int x, int y) const;
+ void writePixel(int x, int y, const Color& c);
+ 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);
+private:
+ Image(const Image&); //!< Not allowed.
+ void operator=(const Image&); //!< Not allowed.
+
+ 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_mipmapsValid;
+ Array<Image*> m_mipmaps;
+};
+
+/*-------------------------------------------------------------------*//*!
+* \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();
+
+ inline const Color::Descriptor& getDescriptor() const { return m_image->getDescriptor(); }
+ inline int getWidth() const { return m_width; }
+ inline int getHeight() const { return m_height; }
+ inline int getNumSamples() const { return m_numSamples; }
+ inline void addReference() { m_referenceCount++; }
+ inline int removeReference() { m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+ inline int isInUse() const { return m_image->isInUse(); }
+ 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);
+ void clear(const Color& clearColor, int x, int y, int w, int h, const Array<Rectangle>& scissors);
+ 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
+ void mask(const Image* src, VGMaskOperation operation, int x, int y, int w, int h);
+ void mask(const Surface* src, VGMaskOperation operation, int x, int y, int w, int h);
+
+ inline Color readSample(int x, int y, int sample) const { return m_image->readPixel(x*m_numSamples+sample, y); }
+ inline void writeSample(int x, int y, int sample, const Color& c) { m_image->writePixel(x*m_numSamples+sample, y, c); }
+
+ 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);
+
+ 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;
+ Image* m_image;
+};
+
+/*-------------------------------------------------------------------*//*!
+* \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();
+
+ inline const Color::Descriptor& getDescriptor() const { return m_color->getDescriptor(); }
+ inline int getNumMaskBits() const { if(!m_mask) return 0; return m_mask->getDescriptor().alphaBits; }
+ inline int getWidth() const { return m_color->getWidth(); }
+ inline int getHeight() const { return m_color->getHeight(); }
+ inline int getNumSamples() const { return m_color->getNumSamples(); }
+ inline void addReference() { m_referenceCount++; }
+ inline int removeReference() { m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; }
+ inline int isInUse() const { return m_color->isInUse() || (m_mask && m_mask->isInUse()); }
+ inline bool isInUse(Image* image) const { return m_color->isInUse(image) || (m_mask && m_mask->isInUse(image)); }
+ inline Surface* getColorBuffer() const { return m_color; }
+ inline Surface* getMaskBuffer() const { return m_mask; }
+
+ void resize(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 /* __IMAGE_H */
diff --git a/src/vg/Math.cpp b/src/vg/Math.cpp
new file mode 100644
index 0000000..1b638ee
--- /dev/null
+++ b/src/vg/Math.cpp
@@ -0,0 +1,75 @@
+/*------------------------------------------------------------------------
+ *
+ * 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 non-inline matrix functions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "Defs.h"
+#include "Math.h"
+
+namespace tgOpenVG
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief Inverts a 3x3 matrix. Returns false if the matrix is singular.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+bool Matrix3x3::invert()
+{
+ 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;
+ t[0][0] = d * det00;
+ t[1][0] = d * det01;
+ t[2][0] = d * det02;
+ t[0][1] = d * (matrix[2][1]*matrix[0][2] - matrix[0][1]*matrix[2][2]);
+ t[1][1] = d * (matrix[0][0]*matrix[2][2] - matrix[2][0]*matrix[0][2]);
+ t[2][1] = d * (matrix[2][0]*matrix[0][1] - matrix[0][0]*matrix[2][1]);
+ t[0][2] = d * (matrix[0][1]*matrix[1][2] - matrix[1][1]*matrix[0][2]);
+ t[1][2] = d * (matrix[1][0]*matrix[0][2] - matrix[0][0]*matrix[1][2]);
+ t[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 tgOpenVG
diff --git a/src/vg/Math.h b/src/vg/Math.h
new file mode 100644
index 0000000..7cbcdce
--- /dev/null
+++ b/src/vg/Math.h
@@ -0,0 +1,380 @@
+#ifndef __MATH_H
+#define __MATH_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 Math functions, Vector and Matrix classes.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "Defs.h"
+
+#include <math.h>
+
+namespace tgOpenVG
+{
+
+/*-------------------------------------------------------------------*//*!
+* \brief
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+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;
+};
+
+inline RIfloat operator+(const RIfloat &a, const RIfloat &b) { return RIfloat(a.v+b.v); }
+inline RIfloat operator+(float a, const RIfloat &b) { return RIfloat(a+b.v); }
+inline RIfloat operator+(const RIfloat &a, float b) { return RIfloat(a.v+b); }
+inline RIfloat operator-(const RIfloat &a, const RIfloat &b) { return RIfloat(a.v-b.v); }
+inline RIfloat operator-(float a, const RIfloat &b) { return RIfloat(a-b.v); }
+inline RIfloat operator-(const RIfloat &a, float b) { return RIfloat(a.v-b); }
+inline RIfloat operator*(const RIfloat &a, const RIfloat &b) { return RIfloat(a.v*b.v); }
+inline RIfloat operator*(float a, const RIfloat &b) { return RIfloat(a*b.v); }
+inline RIfloat operator*(const RIfloat &a, float b) { return RIfloat(a.v*b); }
+inline RIfloat operator/(const RIfloat &a, const RIfloat &b) { return RIfloat(a.v/b.v); }
+inline RIfloat operator/(float a, const RIfloat &b) { return RIfloat(a/b.v); }
+inline RIfloat operator/(const RIfloat &a, float b) { return RIfloat(a.v/b); }
+
+inline bool operator<(const RIfloat &a, const RIfloat &b) { return a.v < b.v ? true : false; }
+inline bool operator<(float a, const RIfloat &b) { return a < b.v ? true : false; }
+inline bool operator<(const RIfloat &a, float b) { return a.v < b ? true : false; }
+inline bool operator>(const RIfloat &a, const RIfloat &b) { return a.v > b.v ? true : false; }
+inline bool operator>(float a, const RIfloat &b) { return a > b.v ? true : false; }
+inline bool operator>(const RIfloat &a, float b) { return a.v > b ? true : false; }
+inline bool operator<=(const RIfloat &a, const RIfloat &b) { return a.v <= b.v ? true : false; }
+inline bool operator<=(float a, const RIfloat &b) { return a <= b.v ? true : false; }
+inline bool operator<=(const RIfloat &a, float b) { return a.v <= b ? true : false; }
+inline bool operator>=(const RIfloat &a, const RIfloat &b) { return a.v >= b.v ? true : false; }
+inline bool operator>=(float a, const RIfloat &b) { return a >= b.v ? true : false; }
+inline bool operator>=(const RIfloat &a, float b) { return a.v >= b ? true : false; }
+inline bool operator==(const RIfloat &a, const RIfloat &b) { return a.v == b.v ? true : false; }
+inline bool operator==(float a, const RIfloat &b) { return a == b.v ? true : false; }
+inline bool operator==(const RIfloat &a, float b) { return a.v == b ? true : false; }
+inline bool operator!=(const RIfloat &a, const RIfloat &b) { return a.v != b.v ? true : false; }
+inline bool operator!=(float a, const RIfloat &b) { return a != b.v ? true : false; }
+inline bool operator!=(const RIfloat &a, float b) { return a.v != b ? true : false; }
+
+#else
+typedef float RIfloat;
+#endif
+
+#define PI 3.141592654f
+
+inline RIfloat RI_MAX(RIfloat a, RIfloat b) { return (a > b) ? a : b; }
+inline RIfloat RI_MIN(RIfloat a, RIfloat b) { return (a < b) ? a : b; }
+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; }
+inline void RI_SWAP(RIfloat &a, RIfloat &b) { RIfloat tmp = a; a = b; b = tmp; }
+inline RIfloat RI_ABS(RIfloat a) { return (a < 0.0f) ? -a : a; }
+inline RIfloat RI_SQR(RIfloat a) { return a * a; }
+inline RIfloat RI_DEG_TO_RAD(RIfloat a) { return a * PI / 180.0f; }
+inline RIfloat RI_RAD_TO_DEG(RIfloat a) { return a * 180.0f/ PI; }
+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; }
+
+inline int RI_INT_MAX(int a, int b) { return (a > b) ? a : b; }
+inline int RI_INT_MIN(int a, int b) { return (a < b) ? a : b; }
+inline void RI_INT_SWAP(int &a, int &b) { int tmp = a; a = b; b = tmp; }
+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; }
+inline int RI_INT_ADDSATURATE(int a, int b) { RI_ASSERT(b >= 0); int r = a + b; return (r >= a) ? r : RI_INT32_MAX; }
+
+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:
+ inline Matrix3x3 (); //initialized to identity
+ inline Matrix3x3 ( const Matrix3x3& m );
+ inline Matrix3x3 ( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 );
+ inline ~Matrix3x3 ();
+ inline Matrix3x3& operator= ( const Matrix3x3& m );
+ inline Vector3& operator[] ( int i ); //returns a row vector
+ inline const Vector3& operator[] ( int i ) const;
+ inline void set ( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 );
+ inline const Vector3 getRow ( int i ) const;
+ inline const Vector3 getColumn ( int i ) const;
+ inline void setRow ( int i, const Vector3& v );
+ inline void setColumn ( int i, const Vector3& v );
+ inline void operator*= ( const Matrix3x3& m );
+ inline void operator*= ( RIfloat f );
+ inline void operator+= ( const Matrix3x3& m );
+ inline void operator-= ( const Matrix3x3& m );
+ inline const Matrix3x3 operator- () const;
+ inline void identity ();
+ inline void transpose ();
+ bool invert (); //if the matrix is singular, returns false and leaves it unmodified
+ inline RIfloat det () const;
+ inline bool isAffine () const;
+
+private:
+ RIfloat matrix[3][3];
+};
+
+//==============================================================================================
+
+class Vector2
+{
+public:
+ inline Vector2 () : x(0.0f), y(0.0f) {}
+ inline Vector2 ( const Vector2& v ) : x(v.x), y(v.y) {}
+ inline Vector2 ( RIfloat fx, RIfloat fy ) : x(fx), y(fy) {}
+ inline ~Vector2 () {}
+ inline Vector2& operator= ( const Vector2& v ) { x = v.x; y = v.y; return *this; }
+ inline RIfloat& operator[] ( int i ) { RI_ASSERT(i>=0&&i<2); return (&x)[i]; }
+ inline const RIfloat& operator[] ( int i ) const { RI_ASSERT(i>=0&&i<2); return (&x)[i]; }
+ inline void set ( RIfloat fx, RIfloat fy ) { x = fx; y = fy; }
+ inline void operator*= ( RIfloat f ) { x *= f; y *= f; }
+ inline void operator+= ( const Vector2& v ) { x += v.x; y += v.y; }
+ inline void operator-= ( const Vector2& v ) { x -= v.x; y -= v.y; }
+ inline const Vector2 operator- () const { return Vector2(-x,-y); }
+ //if the vector is zero, returns false and leaves it unmodified
+ 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; }
+ inline RIfloat length () const { return (RIfloat)sqrt((double)x*(double)x+(double)y*(double)y); }
+ inline void scale ( const Vector2& v ) { x *= v.x; y *= v.y; } //component-wise scale
+ inline void negate () { x = -x; y = -y; }
+
+ RIfloat x,y;
+};
+
+//==============================================================================================
+
+class Vector3
+{
+public:
+ inline Vector3 () : x(0.0f), y(0.0f), z(0.0f) {}
+ inline Vector3 ( const Vector3& v ) : x(v.x), y(v.y), z(v.z) {}
+ inline Vector3 ( RIfloat fx, RIfloat fy, RIfloat fz ) : x(fx), y(fy), z(fz) {}
+ inline ~Vector3 () {}
+ inline Vector3& operator= ( const Vector3& v ) { x = v.x; y = v.y; z = v.z; return *this; }
+ inline RIfloat& operator[] ( int i ) { RI_ASSERT(i>=0&&i<3); return (&x)[i]; }
+ inline const RIfloat& operator[] ( int i ) const { RI_ASSERT(i>=0&&i<3); return (&x)[i]; }
+ inline void set ( RIfloat fx, RIfloat fy, RIfloat fz ){ x = fx; y = fy; z = fz; }
+ inline void operator*= ( RIfloat f ) { x *= f; y *= f; z *= f; }
+ inline void operator+= ( const Vector3& v ) { x += v.x; y += v.y; z += v.z; }
+ inline void operator-= ( const Vector3& v ) { x -= v.x; y -= v.y; z -= v.z; }
+ inline const Vector3 operator- () const { return Vector3(-x,-y,-z); }
+ //if the vector is zero, returns false and leaves it unmodified
+ 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; }
+ inline RIfloat length () const { return (RIfloat)sqrt((double)x*(double)x+(double)y*(double)y+(double)z*(double)z); }
+ inline void scale ( const Vector3& v ) { x *= v.x; y *= v.y; z *= v.z; } //component-wise scale
+ inline void negate () { x = -x; y = -y; z = -z; }
+
+ RIfloat x,y,z;
+};
+
+//==============================================================================================
+
+//Vector2 global functions
+inline bool operator== ( const Vector2& v1, const Vector2& v2 ) { return (v1.x == v2.x) && (v1.y == v2.y); }
+inline bool operator!= ( const Vector2& v1, const Vector2& v2 ) { return (v1.x != v2.x) || (v1.y != v2.y); }
+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; }
+inline bool isZero ( const Vector2& v ) { return (v.x == 0.0f) && (v.y == 0.0f); }
+inline const Vector2 operator* ( RIfloat f, const Vector2& v ) { return Vector2(v.x*f,v.y*f); }
+inline const Vector2 operator* ( const Vector2& v, RIfloat f ) { return Vector2(v.x*f,v.y*f); }
+inline const Vector2 operator+ ( const Vector2& v1, const Vector2& v2 ) { return Vector2(v1.x+v2.x, v1.y+v2.y); }
+inline const Vector2 operator- ( const Vector2& v1, const Vector2& v2 ) { return Vector2(v1.x-v2.x, v1.y-v2.y); }
+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
+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
+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; }
+inline const Vector2 lerp ( const Vector2& v1, const Vector2& v2, RIfloat ratio ) { return v1 + ratio * (v2 - v1); }
+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)
+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)
+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]); }
+inline const Vector2 perpendicularCW(const Vector2& v) { return Vector2(v.y, -v.x); }
+inline const Vector2 perpendicularCCW(const Vector2& v) { return Vector2(-v.y, v.x); }
+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
+inline bool operator== ( const Vector3& v1, const Vector3& v2 ) { return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); }
+inline bool operator!= ( const Vector3& v1, const Vector3& v2 ) { return (v1.x != v2.x) || (v1.y != v2.y) || (v1.z != v2.z); }
+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; }
+inline const Vector3 operator* ( RIfloat f, const Vector3& v ) { return Vector3(v.x*f,v.y*f,v.z*f); }
+inline const Vector3 operator* ( const Vector3& v, RIfloat f ) { return Vector3(v.x*f,v.y*f,v.z*f); }
+inline const Vector3 operator+ ( const Vector3& v1, const Vector3& v2 ) { return Vector3(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z); }
+inline const Vector3 operator- ( const Vector3& v1, const Vector3& v2 ) { return Vector3(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z); }
+inline RIfloat dot ( const Vector3& v1, const Vector3& v2 ) { return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z; }
+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
+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)); }
+inline const Vector3 lerp ( const Vector3& v1, const Vector3& v2, RIfloat ratio ) { return v1 + ratio * (v2 - v1); }
+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
+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
+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; }
+inline bool operator!= ( const Matrix3x3& m1, const Matrix3x3& m2 ) { return !(m1 == m2); }
+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; }
+inline const Matrix3x3 operator* ( RIfloat f, const Matrix3x3& m ) { Matrix3x3 t(m); t *= f; return t; }
+inline const Matrix3x3 operator* ( const Matrix3x3& m, RIfloat f ) { Matrix3x3 t(m); t *= f; return t; }
+inline const Matrix3x3 operator+ ( const Matrix3x3& m1, const Matrix3x3& m2 ) { Matrix3x3 t(m1); t += m2; return t; }
+inline const Matrix3x3 operator- ( const Matrix3x3& m1, const Matrix3x3& m2 ) { Matrix3x3 t(m1); t -= m2; return t; }
+inline const Matrix3x3 transpose ( const Matrix3x3& m ) { Matrix3x3 t(m); t.transpose(); return t; }
+// if the matrix is singular, returns it unmodified
+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)
+inline Matrix3x3::Matrix3x3 () { identity(); }
+inline Matrix3x3::Matrix3x3 ( const Matrix3x3& m ) { *this = m; }
+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); }
+inline Matrix3x3::~Matrix3x3 () {}
+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; }
+inline Vector3& Matrix3x3::operator[] ( int i ) { RI_ASSERT(i>=0&&i<3); return (Vector3&)matrix[i][0]; }
+inline const Vector3& Matrix3x3::operator[] ( int i ) const { RI_ASSERT(i>=0&&i<3); return (const Vector3&)matrix[i][0]; }
+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; }
+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]); }
+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]); }
+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; }
+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; }
+inline void Matrix3x3::operator*= ( const Matrix3x3& m ) { *this = *this * m; }
+inline void Matrix3x3::operator*= ( RIfloat f ) { for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] *= f; }
+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]; }
+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]; }
+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]); }
+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; }
+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]); }
+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]); }
+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; }
+
+//==============================================================================================
+
+} //namespace tgOpenVG
+
+#endif /* __MATH_H */
diff --git a/src/vg/Path.cpp b/src/vg/Path.cpp
new file mode 100644
index 0000000..71469f5
--- /dev/null
+++ b/src/vg/Path.cpp
@@ -0,0 +1,2579 @@
+/*------------------------------------------------------------------------
+ *
+ * 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 Path functions.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "Path.h"
+
+//==============================================================================================
+
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+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(scale != 0.0f);
+
+ c -= bias;
+ c /= scale;
+
+ 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())
+ memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+ memcpy(&newSegments[0] + m_segments.size(), segments, numSegments);
+
+ //copy old data and append new ones
+ if(newData.size())
+ {
+ if(m_data.size())
+ 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
+ {
+ 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())
+ memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+ if(srcPath->m_segments.size())
+ 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())
+ 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);
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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
+ {
+ 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())
+ memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+
+ //copy old data
+ if(m_data.size())
+ 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;
+ 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*PI - rot;
+ }
+ if(swapped)
+ rot += 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())
+ memcpy(&newSegments[0], &m_segments[0], m_segments.size());
+
+ //copy old data
+ if(m_data.size())
+ 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 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 pccw = affineTransform(pathToSurface, v0.ccw);
+ Vector2 pcw = affineTransform(pathToSurface, v0.cw);
+ Vector2 p = affineTransform(pathToSurface, v0.p);
+ Vector2 endccw = affineTransform(pathToSurface, v1.ccw);
+ Vector2 endcw = affineTransform(pathToSurface, v1.cw);
+ Vector2 endp = affineTransform(pathToSurface, v1.p);
+
+ 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);
+
+ for(int j=0;j<samples-1;j++)
+ {
+ RIfloat t = (RIfloat)(j+1) / (RIfloat)samples;
+ Vector2 position = v0.p * (1.0f - t) + v1.p * t;
+ Vector2 tangent = circularLerp(v0.t, v1.t, t);
+ Vector2 normal = normalize(perpendicularCCW(tangent)) * strokeWidth * 0.5f;
+
+ Vector2 nccw = affineTransform(pathToSurface, position + normal);
+ Vector2 ncw = affineTransform(pathToSurface, position - normal);
+ Vector2 n = affineTransform(pathToSurface, position);
+
+ rasterizer.clear();
+ rasterizer.addEdge(p, pccw); //throws bad_alloc
+ rasterizer.addEdge(pccw, nccw); //throws bad_alloc
+ rasterizer.addEdge(nccw, n); //throws bad_alloc
+ rasterizer.addEdge(n, ncw); //throws bad_alloc
+ rasterizer.addEdge(ncw, pcw); //throws bad_alloc
+ rasterizer.addEdge(pcw, p); //throws bad_alloc
+ rasterizer.fill();
+
+ pccw = nccw;
+ pcw = ncw;
+ p = n;
+ }
+
+ //connect the last segment to the end coordinates
+ rasterizer.clear();
+ rasterizer.addEdge(p, pccw); //throws bad_alloc
+ rasterizer.addEdge(pccw, endccw); //throws bad_alloc
+ rasterizer.addEdge(endccw, endp); //throws bad_alloc
+ rasterizer.addEdge(endp, endcw); //throws bad_alloc
+ rasterizer.addEdge(endcw, pcw); //throws bad_alloc
+ rasterizer.addEdge(pcw, p); //throws bad_alloc
+ rasterizer.fill();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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
+{
+ Vector2 ccwt = affineTransform(pathToSurface, v.ccw);
+ Vector2 cwt = affineTransform(pathToSurface, v.cw);
+ Vector2 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 = normalize(v.ccw - v.p);
+ Vector2 u1 = normalize(v.cw - v.p);
+ Vector2 prev = ccwt;
+ rasterizer.addEdge(p, ccwt); //throws bad_alloc
+ for(int j=1;j<samples;j++)
+ {
+ Vector2 next = v.p + circularLerp(u0, u1, t, true) * strokeWidth * 0.5f;
+ next = affineTransform(pathToSurface, next);
+
+ rasterizer.addEdge(prev, next); //throws bad_alloc
+ prev = next;
+ t += step;
+ }
+ rasterizer.addEdge(prev, cwt); //throws bad_alloc
+ rasterizer.addEdge(cwt, p); //throws bad_alloc
+ break;
+ }
+
+ default:
+ {
+ RI_ASSERT(capStyle == VG_CAP_SQUARE);
+ Vector2 t = v.t;
+ t.normalize();
+ Vector2 ccws = affineTransform(pathToSurface, v.ccw + t * strokeWidth * 0.5f);
+ Vector2 cws = affineTransform(pathToSurface, v.cw + t * strokeWidth * 0.5f);
+ rasterizer.addEdge(p, ccwt); //throws bad_alloc
+ rasterizer.addEdge(ccwt, ccws); //throws bad_alloc
+ rasterizer.addEdge(ccws, cws); //throws bad_alloc
+ rasterizer.addEdge(cws, cwt); //throws bad_alloc
+ rasterizer.addEdge(cwt, 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
+{
+ Vector2 ccw0t = affineTransform(pathToSurface, v0.ccw);
+ Vector2 cw0t = affineTransform(pathToSurface, v0.cw);
+ Vector2 m0t = affineTransform(pathToSurface, v0.p);
+ Vector2 ccw1t = affineTransform(pathToSurface, v1.ccw);
+ Vector2 cw1t = affineTransform(pathToSurface, v1.cw);
+ Vector2 m1t = affineTransform(pathToSurface, v1.p);
+
+ Vector2 tccw = v1.ccw - v0.ccw;
+ Vector2 s, e, m, st, et;
+ bool cw;
+
+ rasterizer.clear();
+
+ if( dot(tccw, v0.t) > 0.0f )
+ { //draw ccw miter (draw from point 0 to 1)
+ s = ccw0t;
+ e = ccw1t;
+ st = v0.t;
+ et = v1.t;
+ m = v0.ccw;
+ cw = false;
+ rasterizer.addEdge(m0t, ccw0t); //throws bad_alloc
+ rasterizer.addEdge(ccw1t, m1t); //throws bad_alloc
+ rasterizer.addEdge(m1t, m0t); //throws bad_alloc
+ }
+ else
+ { //draw cw miter (draw from point 1 to 0)
+ s = cw1t;
+ e = cw0t;
+ st = v1.t;
+ et = v0.t;
+ m = v0.cw;
+ cw = true;
+ rasterizer.addEdge(cw0t, m0t); //throws bad_alloc
+ rasterizer.addEdge(m1t, cw1t); //throws bad_alloc
+ rasterizer.addEdge(m0t, m1t); //throws bad_alloc
+ }
+
+ switch(joinStyle)
+ {
+ 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
+ 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); //throws bad_alloc
+ rasterizer.addEdge(c, e); //throws bad_alloc
+ }
+ else
+ { //bevel
+ rasterizer.addEdge(s, e); //throws bad_alloc
+ }
+ break;
+ }
+
+ case VG_JOIN_ROUND:
+ {
+ const RIfloat tessellationAngle = 5.0f;
+
+ 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 = v0.p * (1.0f - t) + v1.p * t;
+ Vector2 tangent = circularLerp(st, et, t, true);
+
+ Vector2 next = position + normalize(perpendicular(tangent, cw)) * 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
+ break;
+ }
+
+ default:
+ RI_ASSERT(joinStyle == VG_JOIN_BEVEL);
+ if(!cw)
+ rasterizer.addEdge(ccw0t, ccw1t); //throws bad_alloc
+ else
+ rasterizer.addEdge(cw1t, cw0t); //throws bad_alloc
+ break;
+ }
+ rasterizer.fill();
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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
+
+ 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;
+ 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;
+ 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
+
+ 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;
+ 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 tgOpenVG
+
+//==============================================================================================
diff --git a/src/vg/Path.h b/src/vg/Path.h
new file mode 100644
index 0000000..d92cb17
--- /dev/null
+++ b/src/vg/Path.h
@@ -0,0 +1,177 @@
+#ifndef __PATH_H
+#define __PATH_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 Path class.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "VG/openvg.h"
+#include "Math.h"
+#include "Array.h"
+#include "Rasterizer.h"
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+/*-------------------------------------------------------------------*//*!
+* \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
+
+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;
+};
+
+//==============================================================================================
+
+} //namespace tgOpenVG
+
+//==============================================================================================
+
+#endif /* __PATH_H */
diff --git a/src/vg/PixelPipe.cpp b/src/vg/PixelPipe.cpp
new file mode 100644
index 0000000..9357ca3
--- /dev/null
+++ b/src/vg/PixelPipe.cpp
@@ -0,0 +1,894 @@
+/*------------------------------------------------------------------------
+ *
+ * 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 Paint and pixel pipe functionality.
+ * \note
+ *//*-------------------------------------------------------------------*/
+
+#include "PixelPipe.h"
+
+//==============================================================================================
+
+namespace tgOpenVG
+{
+
+/*-------------------------------------------------------------------*//*!
+* \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_linearGradientPoint0(0,0),
+ m_inputLinearGradientPoint1(1,0),
+ m_linearGradientPoint1(1,0),
+ m_inputRadialGradientCenter(0,0),
+ m_radialGradientCenter(0,0),
+ m_inputRadialGradientFocalPoint(0,0),
+ m_radialGradientFocalPoint(0,0),
+ m_inputRadialGradientRadius(1.0f),
+ m_radialGradientRadius(1.0f),
+ m_patternTilingMode(VG_TILE_FILL),
+ m_pattern(NULL),
+ m_referenceCount(0)
+{
+ 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);
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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_surfaceToPaintMatrix(),
+ m_surfaceToImageMatrix()
+{
+ for(int i=0;i<8;i++)
+ m_colorTransformValues[i] = (i < 4) ? 1.0f : 0.0f;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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(const Paint* paint)
+{
+ 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);
+ }
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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 Returns the average color within an offset range in the color ramp.
+* \param
+* \return
+* \note
+*//*-------------------------------------------------------------------*/
+
+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;
+}
+
+Color PixelPipe::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_paint->m_colorRampStops.size() >= 2); //there are at least two stops
+
+ Color c(0,0,0,0,m_paint->m_colorRampPremultiplied ? Color::sRGBA_PRE : Color::sRGBA);
+ if(gmin == 1.0f || gmax == 0.0f)
+ return c;
+
+ int i=0;
+ for(;i<m_paint->m_colorRampStops.size()-1;i++)
+ {
+ if(gmin >= m_paint->m_colorRampStops[i].offset && gmin < 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 = (gmin - s) / (e - s);
+
+ 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);
+ Color rc = (1.0f-g) * sc + g * ec;
+
+ //subtract the average color from the start of the stop to gmin
+ c -= 0.5f*(gmin - s)*(sc + rc);
+ break;
+ }
+ }
+
+ for(;i<m_paint->m_colorRampStops.size()-1;i++)
+ {
+ RIfloat s = m_paint->m_colorRampStops[i].offset;
+ RIfloat e = m_paint->m_colorRampStops[i+1].offset;
+ RI_ASSERT(s <= e);
+
+ 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);
+
+ //average of the stop
+ c += 0.5f*(e-s)*(sc + ec);
+
+ if(gmax >= m_paint->m_colorRampStops[i].offset && gmax < m_paint->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
+ c -= 0.5f*(e - gmax)*(rc + ec);
+ break;
+ }
+ }
+ return c;
+}
+
+/*-------------------------------------------------------------------*//*!
+* \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 += integrateColorRamp(gmin, gmax);
+ c *= 1.0f/rho;
+ c.clamp(); //clamp needed due to numerical inaccuracies
+ return c;
+ }
+
+ case VG_COLOR_RAMP_SPREAD_REFLECT:
+ {
+ avg = 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 -= integrateColorRamp(RI_CLAMP(1.0f - (gmin - gmini), 0.0f, 1.0f), 1.0f);
+ else
+ c -= integrateColorRamp(0.0f, RI_CLAMP(gmin - gmini, 0.0f, 1.0f));
+
+ //subtract end
+ if(((int)gmaxi) & 1)
+ c -= integrateColorRamp(0.0f, RI_CLAMP(1.0f - (gmax - gmaxi), 0.0f, 1.0f));
+ else
+ c -= 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 = integrateColorRamp(0.0f, 1.0f);
+ RIfloat gmini = (RIfloat)floor(gmin);
+ RIfloat gmaxi = (RIfloat)floor(gmax);
+ c = (gmaxi + 1.0f - gmini) * avg; //full ramps
+ c -= integrateColorRamp(0.0f, RI_CLAMP(gmin - gmini, 0.0f, 1.0f)); //subtract beginning
+ c -= 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;