# HG changeset patch # User Matt Plumtree # Date 1286384457 -3600 # Node ID 067180f57b120dea10ed60db376c99b0487d309b # Parent c2ef9095503a15174b2adb6c2ece523edb2dc430 Remove copies of code made accidentally to the wrong location. diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/linux/riEGLOS.cpp --- a/hostsupport/hostopenvg/src/src/linux/riEGLOS.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,258 +0,0 @@ -/*------------------------------------------------------------------------ - * - * EGL 1.3 - * ------- - * - * Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Linux specific EGL functionality, modified from macosx source file - * \note - *//*-------------------------------------------------------------------*/ - -#include "riEGLOS.h" - -#include -#include -#include -#include - -#if defined(None) -# undef None -#endif - -#include "sfCompiler.h" - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void* OSGetCurrentThreadID(void) -{ - return (void*)pthread_self(); //TODO this is not safe -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static pthread_mutex_t mutex; -static int mutexRefCount = 0; -static bool mutexInitialized = false; -//acquired mutex cannot be deinited -void OSDeinitMutex(void) -{ - RI_ASSERT(mutexInitialized); - RI_ASSERT(mutexRefCount == 0); - int ret = pthread_mutex_destroy(&mutex); - RI_ASSERT(ret != EINVAL); //assert that the mutex has been initialized - RI_ASSERT(ret != EAGAIN); //assert that the maximum number of recursive locks hasn't been exceeded - RI_ASSERT(!ret); //check that there aren't other errors - RI_UNREF(ret); -} -void OSAcquireMutex(void) -{ - if(!mutexInitialized) - { - int ret; - pthread_mutexattr_t attr; - ret = pthread_mutexattr_init(&attr); //initially not locked - RI_ASSERT(!ret); //check that there aren't any errors - ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); //count the number of recursive locks - RI_ASSERT(!ret); //check that there aren't any errors - ret = pthread_mutex_init(&mutex, &attr); - pthread_mutexattr_destroy(&attr); - RI_ASSERT(!ret); //check that there aren't more errors - RI_UNREF(ret); - mutexInitialized = true; - } - int ret = pthread_mutex_lock(&mutex); - RI_ASSERT(ret != EINVAL); //assert that the mutex has been initialized - RI_ASSERT(ret != EAGAIN); //assert that the maximum number of recursive locks hasn't been exceeded - RI_ASSERT(ret != EDEADLK); //recursive mutexes shouldn't return this - RI_ASSERT(!ret); //check that there aren't other errors - RI_UNREF(ret); - mutexRefCount++; -} -void OSReleaseMutex(void) -{ - RI_ASSERT(mutexInitialized); - mutexRefCount--; - RI_ASSERT(mutexRefCount >= 0); - int ret = pthread_mutex_unlock(&mutex); - RI_ASSERT(ret != EPERM); //assert that the current thread owns the mutex - RI_ASSERT(!ret); //check that there aren't more errors - RI_UNREF(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static bool isBigEndian() -{ - static const RIuint32 v = 0x12345678u; - const RIuint8* p = (const RIuint8*)&v; - RI_ASSERT (*p == (RIuint8)0x12u || *p == (RIuint8)0x78u); - return (*p == (RIuint8)(0x12)) ? true : false; -} - - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window) -{ - try - { - OSWindowContext* ctx = RI_NEW(OSWindowContext, ()); - ctx->window = (int)window; - ctx->tmp = NULL; - ctx->tmpWidth = 0; - ctx->tmpHeight = 0; - return ctx; - } - catch(std::bad_alloc) - { - return NULL; - } -} - -void OSDestroyWindowContext(OSWindowContext* ctx) -{ - if(ctx) - { - RI_DELETE_ARRAY(ctx->tmp); - RI_DELETE(ctx); - } -} - -bool OSIsWindow(const OSWindowContext* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - //TODO implement - return true; - } - return false; -} - -void OSGetWindowSize(const OSWindowContext* ctx, int& width, int& height) -{ - if(ctx) - { - int currWin = glutGetWindow(); - glutSetWindow((int)ctx->window); - width = glutGet(GLUT_WINDOW_WIDTH); - height = glutGet(GLUT_WINDOW_HEIGHT); - glutSetWindow(currWin); - } - else - { - width = 0; - height = 0; - } -} - -void OSBlitToWindow(OSWindowContext* ctx, const Drawable* drawable) -{ - if(ctx) - { - int w = drawable->getWidth(); - int h = drawable->getHeight(); - - int currWin = glutGetWindow(); - glutSetWindow((int)ctx->window); - - if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h) - { - RI_DELETE_ARRAY(ctx->tmp); - ctx->tmp = NULL; - try - { - ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h); //throws bad_alloc - ctx->tmpWidth = w; - ctx->tmpHeight = h; - } - catch(std::bad_alloc) - { - //do nothing - } - } - - if(ctx->tmp) - { - glViewport(0, 0, w, h); - glDisable(GL_DEPTH_TEST); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - //NOTE: we assume here that the display is always in sRGB color space - VGImageFormat f = VG_sABGR_8888_PRE; - if(isBigEndian()) - f = VG_sRGBA_8888_PRE; - static bool flip = false; - if (!flip) - { - vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h); - //flip = true; - } - else - { - void* ptr = (void*)((RIuint8*)ctx->tmp + (w*sizeof(unsigned int)*(h-1))); - vgReadPixels(ptr, -w*sizeof(unsigned int), f, 0, 0, w, h); - flip = false; - } - glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp); - } - - glutSwapBuffers(); //shows the OpenGL frame buffer - glutSetWindow(currWin); //restore the current window - } -} - -EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id) -{ - RI_UNREF(display_id); - return (EGLDisplay)1; //support only a single display -} - -} //namespace OpenVGRI diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/macosx/riEGLOS.cpp --- a/hostsupport/hostopenvg/src/src/macosx/riEGLOS.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,409 +0,0 @@ -/*------------------------------------------------------------------------ - * - * EGL 1.3 - * ------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Mac OS X specific EGL functionality - * \note - *//*-------------------------------------------------------------------*/ - -#include "egl.h" -#include "riImage.h" -#include -#include - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void* OSGetCurrentThreadID(void) -{ - return (void*)pthread_self(); //TODO this is not safe -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static pthread_mutex_t mutex; -static int mutexRefCount = 0; -static bool mutexInitialized = false; -//acquired mutex cannot be deinited -void OSDeinitMutex(void) -{ - RI_ASSERT(mutexInitialized); - RI_ASSERT(mutexRefCount == 0); - int ret = pthread_mutex_destroy(&mutex); - RI_ASSERT(ret != EINVAL); //assert that the mutex has been initialized - RI_ASSERT(ret != EAGAIN); //assert that the maximum number of recursive locks hasn't been exceeded - RI_ASSERT(!ret); //check that there aren't other errors - RI_UNREF(ret); -} -void OSAcquireMutex(void) -{ - if(!mutexInitialized) - { - int ret; - pthread_mutexattr_t attr; - ret = pthread_mutexattr_init(&attr); //initially not locked - RI_ASSERT(!ret); //check that there aren't any errors - ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); //count the number of recursive locks - RI_ASSERT(!ret); //check that there aren't any errors - ret = pthread_mutex_init(&mutex, &attr); - pthread_mutexattr_destroy(&attr); - RI_ASSERT(!ret); //check that there aren't more errors - RI_UNREF(ret); - mutexInitialized = true; - } - int ret = pthread_mutex_lock(&mutex); - RI_ASSERT(ret != EINVAL); //assert that the mutex has been initialized - RI_ASSERT(ret != EAGAIN); //assert that the maximum number of recursive locks hasn't been exceeded - RI_ASSERT(ret != EDEADLK); //recursive mutexes shouldn't return this - RI_ASSERT(!ret); //check that there aren't other errors - RI_UNREF(ret); - mutexRefCount++; -} -void OSReleaseMutex(void) -{ - RI_ASSERT(mutexInitialized); - mutexRefCount--; - RI_ASSERT(mutexRefCount >= 0); - int ret = pthread_mutex_unlock(&mutex); - RI_ASSERT(ret != EPERM); //assert that the current thread owns the mutex - RI_ASSERT(!ret); //check that there aren't more errors - RI_UNREF(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static bool isBigEndian() -{ - static const RIuint32 v = 0x12345678u; - const RIuint8* p = (const RIuint8*)&v; - RI_ASSERT (*p == (RIuint8)0x12u || *p == (RIuint8)0x78u); - return (*p == (RIuint8)(0x12)) ? true : false; -} - - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -#ifdef RI_USE_GLUT -# include -# include - -struct OSWindowContext -{ - int window; - unsigned int* tmp; - int tmpWidth; - int tmpHeight; -}; - -OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window) -{ - try - { - OSWindowContext* ctx = RI_NEW(OSWindowContext, ()); - ctx->window = window; - ctx->tmp = NULL; - ctx->tmpWidth = 0; - ctx->tmpHeight = 0; - return ctx; - } - catch(std::bad_alloc) - { - return NULL; - } -} - -void OSDestroyWindowContext(OSWindowContext* ctx) -{ - if(ctx) - { - RI_DELETE_ARRAY(ctx->tmp); - RI_DELETE(ctx); - } -} - -bool OSIsWindow(const void* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - //TODO implement - return true; - } - return false; -} - -void OSGetWindowSize(const OSWindowContext* ctx, int& width, int& height) -{ - if(ctx) - { - int currWin = glutGetWindow(); - glutSetWindow((int)ctx->window); - width = glutGet(GLUT_WINDOW_WIDTH); - height = glutGet(GLUT_WINDOW_HEIGHT); - glutSetWindow(currWin); - } - else - { - width = 0; - height = 0; - } -} - -void OSBlitToWindow(OSWindowContext* ctx, const Drawable* drawable) -{ - if(ctx) - { - int w = drawable->getWidth(); - int h = drawable->getHeight(); - - int currWin = glutGetWindow(); - glutSetWindow((int)ctx->window); - - if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h) - { - RI_DELETE_ARRAY(ctx->tmp); - ctx->tmp = NULL; - try - { - ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h); //throws bad_alloc - ctx->tmpWidth = w; - ctx->tmpHeight = h; - } - catch(std::bad_alloc) - { - //do nothing - } - } - - if(ctx->tmp) - { - glViewport(0, 0, w, h); - glDisable(GL_DEPTH_TEST); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - //NOTE: we assume here that the display is always in sRGB color space - VGImageFormat f = VG_sXBGR_8888; - if(isBigEndian()) - f = VG_sRGBX_8888; - vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h); - glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp); - } - - glutSwapBuffers(); //shows the OpenGL frame buffer - glutSetWindow(currWin); //restore the current window - } -} - -#else - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -//Mac OS X native -#include -#include - -struct OSWindowContext -{ - AGLPixelFormat aglPixFmt; - AGLContext aglContext; - WindowPtr window; - unsigned int* tmp; - int tmpWidth; - int tmpHeight; -}; - -void* OSCreateWindowContext(EGLNativeWindowType window) -{ - OSWindowContext* ctx = NULL; - try - { - ctx = RI_NEW(OSWindowContext, ()); - } - catch(std::bad_alloc) - { - return NULL; - } - - GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_DEPTH_SIZE, 32, AGL_NONE }; - ctx->aglPixFmt = aglChoosePixelFormat(NULL, 0, attrib); - if(!ctx->aglPixFmt) - { - RI_DELETE(ctx); - return NULL; - } - - ctx->aglContext = aglCreateContext(ctx->aglPixFmt, NULL); - if(!ctx->aglContext) - { - aglDestroyPixelFormat(ctx->aglPixFmt); - RI_DELETE(ctx); - return NULL; - } - - GLint opaque = 1; - GLint sync = 1; - aglSetInteger(ctx->aglContext, AGL_SURFACE_OPACITY, &opaque); - aglSetInteger(ctx->aglContext, AGL_SWAP_INTERVAL, &sync); - - ctx->window = (WindowPtr)window; - ctx->tmp = NULL; - ctx->tmpWidth = 0; - ctx->tmpHeight = 0; - return ctx; -} - -void OSDestroyWindowContext(void* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - aglSetDrawable(ctx->aglContext, NULL); - aglSetCurrentContext(NULL); - aglDestroyContext(ctx->aglContext); - aglDestroyPixelFormat(ctx->aglPixFmt); - RI_DELETE_ARRAY(ctx->tmp); - RI_DELETE(ctx); - } -} - -bool OSIsWindow(const void* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - if(IsValidWindowPtr(ctx->window)) - return true; - } - return false; -} - -void OSGetWindowSize(const void* context, int& width, int& height) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - Rect rectPort; - GetWindowPortBounds(ctx->window, &rectPort); - width = rectPort.right - rectPort.left; - height = rectPort.bottom - rectPort.top; - } - else - { - width = 0; - height = 0; - } -} - -void OSBlitToWindow(void* context, const Drawable* drawable) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - int w = drawable->getWidth(); - int h = drawable->getHeight(); - - GrafPtr portSave = NULL; - GetPort(&portSave); - SetPort((GrafPtr)GetWindowPort(ctx->window)); - aglSetDrawable(ctx->aglContext, GetWindowPort(ctx->window)); - aglSetCurrentContext(ctx->aglContext); - - if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h) - { - RI_DELETE_ARRAY(ctx->tmp); - ctx->tmp = NULL; - try - { - ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h); //throws bad_alloc - ctx->tmpWidth = w; - ctx->tmpHeight = h; - } - catch(std::bad_alloc) - { - //do nothing - } - } - - if(ctx->tmp) - { - glViewport(0, 0, w, h); - glDisable(GL_DEPTH_TEST); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - //NOTE: we assume here that the display is always in sRGB color space - VGImageFormat f = VG_sXBGR_8888; - if(isBigEndian()) - f = VG_sRGBX_8888; - vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h); - glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp); - } - - aglSwapBuffers(ctx->aglContext); - SetPort(portSave); - } -} - -#endif - -EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id) -{ - RI_UNREF(display_id); - return (EGLDisplay)1; //support only a single display -} - -} //namespace OpenVGRI diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/null/riEGLOS.cpp --- a/hostsupport/hostopenvg/src/src/null/riEGLOS.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,160 +0,0 @@ -/*------------------------------------------------------------------------ - * - * EGL 1.3 - * ------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Generic OS EGL functionality (not thread safe, no window rendering) - * \note - *//*-------------------------------------------------------------------*/ - -#include "egl.h" -#include "riImage.h" - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void* OSGetCurrentThreadID(void) -{ - return NULL; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static int mutexRefCount = 0; -static bool mutexInitialized = false; -//acquired mutex cannot be deinited -void OSDeinitMutex(void) -{ - RI_ASSERT(mutexInitialized); - RI_ASSERT(mutexRefCount == 0); -} -void OSAcquireMutex(void) -{ - if(!mutexInitialized) - { - mutexInitialized = true; - } - mutexRefCount++; -} -void OSReleaseMutex(void) -{ - RI_ASSERT(mutexInitialized); - mutexRefCount--; - RI_ASSERT(mutexRefCount >= 0); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -struct OSWindowContext -{ - int tmpWidth; - int tmpHeight; -}; - -void* OSCreateWindowContext(EGLNativeWindowType window) -{ - OSWindowContext* ctx = NULL; - try - { - ctx = RI_NEW(OSWindowContext, ()); - } - catch(std::bad_alloc) - { - return NULL; - } - ctx->tmpWidth = 0; - ctx->tmpHeight = 0; - return ctx; -} - -void OSDestroyWindowContext(void* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - RI_DELETE(ctx); - } -} - -bool OSIsWindow(const void* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - return true; - } - return false; -} - -void OSGetWindowSize(const void* context, int& width, int& height) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - width = ctx->tmpWidth; - height = ctx->tmpHeight; - } - else - { - width = 0; - height = 0; - } -} - -void OSBlitToWindow(void* context, const Drawable* drawable) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - ctx->tmpWidth = drawable->getWidth(); - ctx->tmpHeight = drawable->getHeight(); - } -} - -EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id) -{ - RI_UNREF(display_id); - return (EGLDisplay)1; //support only a single display -} - -} //namespace OpenVGRI diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riApi.cpp --- a/hostsupport/hostopenvg/src/src/riApi.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,3839 +0,0 @@ -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementations of OpenVG API functions. - * \note The actual processing is done in Path, Image, Rasterizer and PixelPipe classes. - *//*-------------------------------------------------------------------*/ - -#include "openvg.h" -#include "vgext.h" -#include "riContext.h" -#include "riRasterizer.h" -#include "riPixelPipe.h" -#include "riPath.h" -#include - -//============================================================================================== - -namespace OpenVGRI -{ - -/* EGL&OS functions for use in an OpenVG implementation */ -// \note To ensure that different EGLs work in parallel, these functions must be implemented. -// They may be wrappers if the underlying EGL is more complicated that miniEGL. -void* eglvgGetCurrentVGContext(void); -bool eglvgIsInUse(void* image); -bool eglvgLockSurface(bool read, bool write); -bool eglvgUnlockSurface(); -void OSAcquireMutex(void); -void OSReleaseMutex(void); -void eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride ); -void* eglvgGetImageData( void* image ); - -#define RI_NO_RETVAL - -//this must be the first line in an API function -#define RI_GET_CONTEXT(RETVAL) \ - OSAcquireMutex(); \ - VGContext* context = (VGContext*)eglvgGetCurrentVGContext(); \ - if(!context) \ - { \ - OSReleaseMutex(); \ - return RETVAL;\ - } - -#define RI_IF_ERROR(COND, ERRORCODE, RETVAL) \ - if(COND) { context->setError(ERRORCODE); OSReleaseMutex(); return RETVAL; } - -//all API functions must call this as their last operation (also functions that don't return values) -//NOTE: don't evaluate anything or read state in RETVAL (it'll be executed after the mutex has been released) -#define RI_RETURN(RETVAL) \ - { OSReleaseMutex(); \ - return RETVAL; } - -static bool isAligned(const void* ptr, int alignment) -{ - RI_ASSERT(alignment == 1 || alignment == 2 || alignment == 4); - if(((RIuintptr)ptr) & (alignment-1)) - return false; - return true; -} - -static bool isAligned(const void* ptr, VGImageFormat format) -{ - RI_ASSERT(isValidImageFormat(format)); - int alignment = Color::formatToDescriptor(format).bitsPerPixel >> 3; - if(alignment <= 1) - return true; //one bit or byte per pixel - return isAligned(ptr, alignment); -} - -bool isValidImageFormat(int f) -{ - if(f < VG_sRGBX_8888 || f > VG_lABGR_8888_PRE) - return false; - return true; -} - -} //namespace OpenVGRI - -using namespace OpenVGRI; - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgFlush(void) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - //the RI doesn't cache anything, so this is a no-op - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgFinish(void) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - //the RI doesn't cache anything, so this is a no-op - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGErrorCode RI_APIENTRY vgGetError(void) -{ - RI_GET_CONTEXT(VG_NO_CONTEXT_ERROR); - VGErrorCode error = context->m_error; - context->m_error = VG_NO_ERROR; - RI_RETURN(error); -} - -VGErrorCode RI_APIENTRY vgPlatsimGetError(void) -{ - RI_GET_CONTEXT(VG_NO_CONTEXT_ERROR); - VGErrorCode error = context->m_error; - RI_RETURN(error); -} - - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -namespace OpenVGRI -{ - -RIfloat inputFloat(VGfloat f) -{ - //this function is used for all floating point input values - if(RI_ISNAN(f)) return 0.0f; //convert NaN to zero - return RI_CLAMP(f, -RI_FLOAT_MAX, RI_FLOAT_MAX); //clamp +-inf to +-RIfloat max -} - -Vector2 inputVector2(const Vector2& v) -{ - return Vector2(inputFloat(v.x), inputFloat(v.y)); -} - -Color inputColor(const Color& c) -{ - Color r = c; - r.r = inputFloat(r.r); - r.g = inputFloat(r.g); - r.b = inputFloat(r.b); - r.a = inputFloat(r.a); - return r; -} - -static int inputFloatToInt(VGfloat value) -{ - double v = (double)floor(value); - v = v > (double)RI_INT32_MAX ? (double)RI_INT32_MAX : v; - v = v < (double)RI_INT32_MIN ? (double)RI_INT32_MIN : v; - return (int)v; -} - -static int paramToInt(const void* values, bool floats, int count, int i) -{ - RI_ASSERT(i >= 0); - if(i >= count || !values) - return 0; - if(floats) - return inputFloatToInt(((const VGfloat*)values)[i]); - return (int)((const VGint*)values)[i]; -} - -static RIfloat paramToFloat(const void* values, bool floats, int count, int i) -{ - RI_ASSERT(i >= 0); - if(i >= count || !values) - return 0.0f; - if(floats) - return ((const VGfloat*)values)[i]; - return (RIfloat)((const VGint*)values)[i]; -} - -static void floatToParam(void* output, bool outputFloats, int count, int i, VGfloat value) -{ - RI_ASSERT(i >= 0); - RI_ASSERT(output); - if(i >= count) - return; - if(outputFloats) - ((VGfloat*)output)[i] = value; - else - ((VGint*)output)[i] = (VGint)inputFloatToInt(value); -} - -static void intToParam(void* output, bool outputFloats, int count, int i, VGint value) -{ - RI_ASSERT(i >= 0); - RI_ASSERT(output); - if(i >= count) - return; - if(outputFloats) - ((VGfloat*)output)[i] = (VGfloat)value; - else - ((VGint*)output)[i] = value; -} - -} //namespace OpenVGRI - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static void setifv(VGContext* context, VGParamType type, VGint count, const void* values, bool floats) -{ - RI_ASSERT(context); - RI_ASSERT(!count || (count && values)); - - int ivalue = paramToInt(values, floats, count, 0); - RIfloat fvalue = paramToFloat(values, floats, count, 0); - - switch(type) - { - case VG_MATRIX_MODE: - if(count != 1 || ivalue < VG_MATRIX_PATH_USER_TO_SURFACE || ivalue > VG_MATRIX_GLYPH_USER_TO_SURFACE) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - context->m_matrixMode = (VGMatrixMode)ivalue; - break; - - case VG_FILL_RULE: - if(count != 1 || ivalue < VG_EVEN_ODD || ivalue > VG_NON_ZERO) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - context->m_fillRule = (VGFillRule)ivalue; - break; - - case VG_IMAGE_QUALITY: - if(count != 1 || !(ivalue == VG_IMAGE_QUALITY_NONANTIALIASED || ivalue == VG_IMAGE_QUALITY_FASTER || ivalue == VG_IMAGE_QUALITY_BETTER)) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - context->m_imageQuality = (VGImageQuality)ivalue; - break; - - case VG_RENDERING_QUALITY: - if(count != 1 || !(ivalue == VG_RENDERING_QUALITY_NONANTIALIASED || ivalue == VG_RENDERING_QUALITY_FASTER || ivalue == VG_RENDERING_QUALITY_BETTER)) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - context->m_renderingQuality = (VGRenderingQuality)ivalue; - break; - - case VG_BLEND_MODE: - if(count != 1 || ivalue < VG_BLEND_SRC || ivalue > VG_BLEND_ADDITIVE) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - context->m_blendMode = (VGBlendMode)ivalue; - break; - - case VG_IMAGE_MODE: - if(count != 1 || ivalue < VG_DRAW_IMAGE_NORMAL || ivalue > VG_DRAW_IMAGE_STENCIL) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - context->m_imageMode = (VGImageMode)ivalue; - break; - - case VG_SCISSOR_RECTS: - { - if(count & 3) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } //count must be a multiple of four - try - { - Array scissor; - for(int i=0;im_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 inputStrokeDashPattern; - Array strokeDashPattern; - for(int i=0;im_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;im_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;im_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;im_inputStrokeDashPattern.size();i++) - floatToParam(values, floats, count, i, context->m_inputStrokeDashPattern[i]); - break; - } - - case VG_STROKE_DASH_PHASE: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, context->m_inputStrokeDashPhase); - break; - - case VG_STROKE_DASH_PHASE_RESET: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, context->m_strokeDashPhaseReset); - break; - - case VG_TILE_FILL_COLOR: - if(count > 4) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, context->m_inputTileFillColor.r); - floatToParam(values, floats, count, 1, context->m_inputTileFillColor.g); - floatToParam(values, floats, count, 2, context->m_inputTileFillColor.b); - floatToParam(values, floats, count, 3, context->m_inputTileFillColor.a); - break; - - case VG_CLEAR_COLOR: - if(count > 4) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, context->m_inputClearColor.r); - floatToParam(values, floats, count, 1, context->m_inputClearColor.g); - floatToParam(values, floats, count, 2, context->m_inputClearColor.b); - floatToParam(values, floats, count, 3, context->m_inputClearColor.a); - break; - - case VG_GLYPH_ORIGIN: - if(count > 2) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, context->m_inputGlyphOrigin.x); - floatToParam(values, floats, count, 1, context->m_inputGlyphOrigin.y); - break; - - case VG_MASKING: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, context->m_masking); - break; - - case VG_SCISSORING: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, context->m_scissoring); - break; - - case VG_PIXEL_LAYOUT: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, context->m_pixelLayout); - break; - - case VG_SCREEN_LAYOUT: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, VG_PIXEL_LAYOUT_UNKNOWN); - break; - - case VG_FILTER_FORMAT_LINEAR: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, context->m_filterFormatLinear); - break; - - case VG_FILTER_FORMAT_PREMULTIPLIED: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, context->m_filterFormatPremultiplied); - break; - - case VG_FILTER_CHANNEL_MASK: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, context->m_filterChannelMask); - break; - - case VG_MAX_SCISSOR_RECTS: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_SCISSOR_RECTANGLES); - break; - - case VG_MAX_DASH_COUNT: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_DASH_COUNT); - break; - - case VG_MAX_KERNEL_SIZE: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_KERNEL_SIZE); - break; - - case VG_MAX_SEPARABLE_KERNEL_SIZE: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_SEPARABLE_KERNEL_SIZE); - break; - - case VG_MAX_COLOR_RAMP_STOPS: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_COLOR_RAMP_STOPS); - break; - - case VG_MAX_IMAGE_WIDTH: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_IMAGE_WIDTH); - break; - - case VG_MAX_IMAGE_HEIGHT: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_IMAGE_HEIGHT); - break; - - case VG_MAX_IMAGE_PIXELS: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_IMAGE_PIXELS); - break; - - case VG_MAX_IMAGE_BYTES: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, RI_MAX_IMAGE_BYTES); - break; - - case VG_MAX_FLOAT: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, RI_FLOAT_MAX); - break; - - case VG_MAX_GAUSSIAN_STD_DEVIATION: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, RI_MAX_GAUSSIAN_STD_DEVIATION); - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - break; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGfloat RI_APIENTRY vgGetf(VGParamType type) -{ - RI_GET_CONTEXT(0.0f); - RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR || - type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, 0.0f); //vector type value - RIfloat ret = 0.0f; - getifv(context, type, 1, &ret, true); - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGint RI_APIENTRY vgGeti(VGParamType type) -{ - RI_GET_CONTEXT(0); - RI_IF_ERROR(type == VG_SCISSOR_RECTS || type == VG_STROKE_DASH_PATTERN || type == VG_TILE_FILL_COLOR || - type == VG_CLEAR_COLOR, VG_ILLEGAL_ARGUMENT_ERROR, 0); //vector type value - VGint ret = 0; - getifv(context, type, 1, &ret, false); - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgGetiv(VGParamType type, VGint count, VGint * values) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(count <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - getifv(context, type, count, values, false); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgGetfv(VGParamType type, VGint count, VGfloat * values) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(count <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - getifv(context, type, count, values, true); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGint RI_APIENTRY vgGetVectorSize(VGParamType type) -{ - RI_GET_CONTEXT(0); - VGint ret = 0; - switch(type) - { - case VG_MATRIX_MODE: - case VG_FILL_RULE: - case VG_IMAGE_QUALITY: - case VG_RENDERING_QUALITY: - case VG_BLEND_MODE: - case VG_IMAGE_MODE: - ret = 1; - break; - - case VG_SCISSOR_RECTS: - ret = 4*context->m_scissor.size(); - break; - - case VG_COLOR_TRANSFORM: - ret = 1; - break; - - case VG_COLOR_TRANSFORM_VALUES: - ret = 8; - break; - - case VG_STROKE_LINE_WIDTH: - case VG_STROKE_CAP_STYLE: - case VG_STROKE_JOIN_STYLE: - case VG_STROKE_MITER_LIMIT: - ret = 1; - break; - - case VG_STROKE_DASH_PATTERN: - ret = context->m_inputStrokeDashPattern.size(); - break; - - case VG_STROKE_DASH_PHASE: - case VG_STROKE_DASH_PHASE_RESET: - ret = 1; - break; - - case VG_TILE_FILL_COLOR: - case VG_CLEAR_COLOR: - ret = 4; - break; - - case VG_GLYPH_ORIGIN: - ret = 2; - break; - - case VG_MASKING: - case VG_SCISSORING: - case VG_PIXEL_LAYOUT: - case VG_SCREEN_LAYOUT: - case VG_FILTER_FORMAT_LINEAR: - case VG_FILTER_FORMAT_PREMULTIPLIED: - case VG_FILTER_CHANNEL_MASK: - case VG_MAX_SCISSOR_RECTS: - case VG_MAX_DASH_COUNT: - case VG_MAX_KERNEL_SIZE: - case VG_MAX_SEPARABLE_KERNEL_SIZE: - case VG_MAX_COLOR_RAMP_STOPS: - case VG_MAX_IMAGE_WIDTH: - case VG_MAX_IMAGE_HEIGHT: - case VG_MAX_IMAGE_PIXELS: - case VG_MAX_IMAGE_BYTES: - case VG_MAX_FLOAT: - case VG_MAX_GAUSSIAN_STD_DEVIATION: - ret = 1; - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - break; - } - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static void setPaintParameterifv(VGContext* context, Paint* paint, VGPaintParamType paramType, VGint count, const void* values, bool floats) -{ - RI_ASSERT(context); - RI_ASSERT(paint); - - int ivalue = paramToInt(values, floats, count, 0); - - switch(paramType) - { - case VG_PAINT_TYPE: - if(count != 1 || ivalue < VG_PAINT_TYPE_COLOR || ivalue > VG_PAINT_TYPE_PATTERN) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - paint->m_paintType = (VGPaintType)ivalue; - break; - - case VG_PAINT_COLOR: - RI_TRACE("\n***** Setting solid color to paint.\n"); - RI_TRACE("** ptr: %x\n", (int)paint); - if(count != 4) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - paint->m_inputPaintColor.set(paramToFloat(values, floats, count, 0), - paramToFloat(values, floats, count, 1), - paramToFloat(values, floats, count, 2), - paramToFloat(values, floats, count, 3), - Color::sRGBA); - RI_TRACE("** input solid color: [%.3f %.3f %.3f %.4f]\n", paint->m_inputPaintColor.r, paint->m_inputPaintColor.g, paint->m_inputPaintColor.b, paint->m_inputPaintColor.a); - paint->setColor(inputColor(paint->m_inputPaintColor)); - RI_TRACE("** -> [%.3f %.3f %.3f %.3f]\n", paint->m_paintColor.r, paint->m_paintColor.g, paint->m_paintColor.b, paint->m_paintColor.a); - break; - - case VG_PAINT_COLOR_RAMP_SPREAD_MODE: - if(count != 1 || ivalue < VG_COLOR_RAMP_SPREAD_PAD || ivalue > VG_COLOR_RAMP_SPREAD_REFLECT) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - paint->m_colorRampSpreadMode = (VGColorRampSpreadMode)ivalue; - break; - - case VG_PAINT_COLOR_RAMP_STOPS: - { - int numStops = count/5; - if(count != numStops*5) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } //count must be a multiple of five - try - { - Array colorRampStops; - Array inputColorRampStops; - RIfloat prevOffset = -RI_FLOAT_MAX; - bool valid = true; - for(int i=0;i= 0.0f && gs.offset <= 1.0f) - { - gs.color.clamp(); - - if(!colorRampStops.size() && gs.offset > 0.0f) - { //the first valid stop is not at 0, replicate the first one - RIfloat tmp = gs.offset; - gs.offset = 0.0f; - colorRampStops.push_back(gs); //throws bad_alloc - gs.offset = tmp; - } - colorRampStops.push_back(gs); //throws bad_alloc - } - prevOffset = gs.offset; - } - if(valid && colorRampStops.size() && colorRampStops[colorRampStops.size()-1].offset < 1.0f) - { //there is at least one stop, but the last one is not at 1, replicate the last one - Paint::GradientStop gs = colorRampStops[colorRampStops.size()-1]; - gs.offset = 1.0f; - colorRampStops.push_back(gs); //throws bad_alloc - } - if(!valid || !colorRampStops.size()) - { //there are no valid stops, add implicit stops - colorRampStops.clear(); - Paint::GradientStop gs; - gs.offset = 0.0f; - gs.color.set(0,0,0,1,Color::sRGBA); - colorRampStops.push_back(gs); //throws bad_alloc - gs.offset = 1.0f; - gs.color.set(1,1,1,1,Color::sRGBA); - colorRampStops.push_back(gs); //throws bad_alloc - } - RI_ASSERT(colorRampStops.size() >= 2 && colorRampStops.size() <= RI_MAX_COLOR_RAMP_STOPS); - //paint->m_colorRampStops.swap(colorRampStops); //set paint array - //paint->m_inputColorRampStops.swap(inputColorRampStops); //set paint array - paint->setGradientStops(inputColorRampStops, colorRampStops); - //paint->generateLUT(); - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - break; - } - - case VG_PAINT_COLOR_RAMP_PREMULTIPLIED: - if(count != 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - paint->m_colorRampPremultiplied = ivalue ? VG_TRUE : VG_FALSE; - break; - - case VG_PAINT_LINEAR_GRADIENT: - if(count != 4) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - paint->m_inputLinearGradientPoint0.set(paramToFloat(values, floats, count, 0), - paramToFloat(values, floats, count, 1)); - paint->m_inputLinearGradientPoint1.set(paramToFloat(values, floats, count, 2), - paramToFloat(values, floats, count, 3)); - paint->setLinearGradient( - inputVector2(paint->m_inputLinearGradientPoint0), - inputVector2(paint->m_inputLinearGradientPoint1)); - - break; - - case VG_PAINT_RADIAL_GRADIENT: - if(count != 5) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - paint->m_inputRadialGradientCenter.set(paramToFloat(values, floats, count, 0), - paramToFloat(values, floats, count, 1)); - paint->m_inputRadialGradientFocalPoint.set(paramToFloat(values, floats, count, 2), - paramToFloat(values, floats, count, 3)); - paint->m_inputRadialGradientRadius = paramToFloat(values, floats, count, 4); - paint->setRadialGradient( - inputVector2(paint->m_inputRadialGradientCenter), - inputVector2(paint->m_inputRadialGradientFocalPoint), - inputFloat(paint->m_inputRadialGradientRadius)); - //paint->m_radialGradientCenter = inputVector2(paint->m_inputRadialGradientCenter); - //paint->m_radialGradientFocalPoint = inputVector2(paint->m_inputRadialGradientFocalPoint); - //paint->m_radialGradientRadius = inputFloat(paint->m_inputRadialGradientRadius); - break; - - case VG_PAINT_PATTERN_TILING_MODE: - if(count != 1 || ivalue < VG_TILE_FILL || ivalue > VG_TILE_REFLECT) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - paint->m_patternTilingMode = (VGTilingMode)ivalue; - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - break; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetParameterf(VGHandle object, VGint paramType, VGfloat value) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isMaskLayer = context->isValidMaskLayer(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle - RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT || - paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //vector valued parameter - VGfloat values[1] = {value}; - if(isImage) - { //read only, the function does nothing - RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont); - if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else if(isPath) - { //read only, the function does nothing - RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont); - if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont); - setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, values, true); - } - else if(isMaskLayer) - { - RI_ASSERT(!isImage && !isPath && !isPaint && !isFont); - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else - { //read only, the function does nothing - RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont); - if (paramType != VG_FONT_NUM_GLYPHS) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetParameteri(VGHandle object, VGint paramType, VGint value) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isMaskLayer = context->isValidMaskLayer(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle - RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT || - paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //vector valued parameter - VGint values[1] = {value}; - if(isImage) - { //read only, the function does nothing - RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont); - if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else if(isPath) - { //read only, the function does nothing - RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont); - if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont); - setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, values, false); - } - else if(isMaskLayer) - { - RI_ASSERT(!isImage && !isPath && !isPaint && !isFont); - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else - { //read only, the function does nothing - RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont); - if (paramType != VG_FONT_NUM_GLYPHS) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetParameterfv(VGHandle object, VGint paramType, VGint count, const VGfloat * values) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(count < 0 || (!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isMaskLayer = context->isValidMaskLayer(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle - if(isImage) - { //read only, the function does nothing - RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont); - if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else if(isPath) - { //read only, the function does nothing - RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont); - if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont); - setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, true); - } - else if(isMaskLayer) - { - RI_ASSERT(!isImage && !isPath && !isPaint && !isFont); - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else - { //read only, the function does nothing - RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont); - if (paramType != VG_FONT_NUM_GLYPHS) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetParameteriv(VGHandle object, VGint paramType, VGint count, const VGint * values) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(count < 0 || (!values && count > 0) || (values && !isAligned(values,4)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isMaskLayer = context->isValidMaskLayer(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isMaskLayer && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle - if(isImage) - { //read only, the function does nothing - RI_ASSERT(!isPath && !isPaint && !isMaskLayer && !isFont); - if(paramType < VG_IMAGE_FORMAT || paramType > VG_IMAGE_HEIGHT) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else if(isPath) - { //read only, the function does nothing - RI_ASSERT(!isImage && !isPaint && !isMaskLayer && !isFont); - if(paramType < VG_PATH_FORMAT || paramType > VG_PATH_NUM_COORDS) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isMaskLayer && !isFont); - setPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, false); - } - else if(isMaskLayer) - { - RI_ASSERT(!isImage && !isPath && !isPaint && !isFont); - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - else - { //read only, the function does nothing - RI_ASSERT(!isImage && !isPath && !isPaint && !isMaskLayer && isFont); - if (paramType != VG_FONT_NUM_GLYPHS) - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static void getPaintParameterifv(VGContext* context, Paint* paint, VGPaintParamType type, VGint count, void* values, bool floats) -{ - switch(type) - { - case VG_PAINT_TYPE: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, paint->m_paintType); - break; - - case VG_PAINT_COLOR: - if(count > 4) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, paint->m_inputPaintColor.r); - floatToParam(values, floats, count, 1, paint->m_inputPaintColor.g); - floatToParam(values, floats, count, 2, paint->m_inputPaintColor.b); - floatToParam(values, floats, count, 3, paint->m_inputPaintColor.a); - break; - - case VG_PAINT_COLOR_RAMP_SPREAD_MODE: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, paint->m_colorRampSpreadMode); - break; - - case VG_PAINT_COLOR_RAMP_STOPS: - { - if(count > paint->m_inputColorRampStops.size()*5) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - int j = 0; - for(int i=0;im_inputColorRampStops.size();i++) - { - floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].offset); - floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.r); - floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.g); - floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.b); - floatToParam(values, floats, count, j++, paint->m_inputColorRampStops[i].color.a); - } - break; - } - - case VG_PAINT_COLOR_RAMP_PREMULTIPLIED: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, paint->m_colorRampPremultiplied); - break; - - case VG_PAINT_LINEAR_GRADIENT: - if(count > 4) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, paint->m_inputLinearGradientPoint0.x); - floatToParam(values, floats, count, 1, paint->m_inputLinearGradientPoint0.y); - floatToParam(values, floats, count, 2, paint->m_inputLinearGradientPoint1.x); - floatToParam(values, floats, count, 3, paint->m_inputLinearGradientPoint1.y); - break; - - case VG_PAINT_RADIAL_GRADIENT: - if(count > 5) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, paint->m_inputRadialGradientCenter.x); - floatToParam(values, floats, count, 1, paint->m_inputRadialGradientCenter.y); - floatToParam(values, floats, count, 2, paint->m_inputRadialGradientFocalPoint.x); - floatToParam(values, floats, count, 3, paint->m_inputRadialGradientFocalPoint.y); - floatToParam(values, floats, count, 4, paint->m_inputRadialGradientRadius); - break; - - case VG_PAINT_PATTERN_TILING_MODE: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, paint->m_patternTilingMode); - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - break; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static void getPathParameterifv(VGContext* context, Path* path, VGPathParamType type, VGint count, void* values, bool floats) -{ - switch(type) - { - case VG_PATH_FORMAT: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, path->getFormat()); - break; - - case VG_PATH_DATATYPE: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, path->getDatatype()); - break; - - case VG_PATH_SCALE: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, path->getScale()); - break; - - case VG_PATH_BIAS: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - floatToParam(values, floats, count, 0, path->getBias()); - break; - - case VG_PATH_NUM_SEGMENTS: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, path->getNumSegments()); - break; - - case VG_PATH_NUM_COORDS: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, path->getNumCoordinates()); - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - break; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static void getImageParameterifv(VGContext* context, Image* image, VGImageParamType type, VGint count, void* values, bool floats) -{ - switch(type) - { - case VG_IMAGE_FORMAT: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - RI_ASSERT(isValidImageFormat(image->getDescriptor().vgFormat)); - intToParam(values, floats, count, 0, image->getDescriptor().vgFormat); - break; - - case VG_IMAGE_WIDTH: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, image->getWidth()); - break; - - case VG_IMAGE_HEIGHT: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, image->getHeight()); - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - break; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static void getFontParameterifv(VGContext* context, Font* font, VGFontParamType type, VGint count, void* values, bool floats) -{ - switch(type) - { - case VG_FONT_NUM_GLYPHS: - if(count > 1) { context->setError(VG_ILLEGAL_ARGUMENT_ERROR); return; } - intToParam(values, floats, count, 0, font->getNumGlyphs()); - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid VGParamType - break; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGfloat RI_APIENTRY vgGetParameterf(VGHandle object, VGint paramType) -{ - RI_GET_CONTEXT(0.0f); - RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT || - paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, 0.0f); //vector valued parameter - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0.0f); //invalid object handle - VGfloat ret = 0.0f; - if(isImage) - { - RI_ASSERT(!isPath && !isPaint && !isFont); - getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, 1, &ret, true); - } - else if(isPath) - { - RI_ASSERT(!isImage && !isPaint && !isFont); - getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, 1, &ret, true); - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isFont); - getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, &ret, true); - } - else - { - RI_ASSERT(!isImage && !isPath && !isPaint && isFont); - getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, 1, &ret, true); - } - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGint RI_APIENTRY vgGetParameteri(VGHandle object, VGint paramType) -{ - RI_GET_CONTEXT(0); - RI_IF_ERROR(paramType == VG_PAINT_COLOR || paramType == VG_PAINT_COLOR_RAMP_STOPS || paramType == VG_PAINT_LINEAR_GRADIENT || - paramType == VG_PAINT_RADIAL_GRADIENT, VG_ILLEGAL_ARGUMENT_ERROR, 0); //vector valued parameter - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0); //invalid object handle - VGint ret = 0; - if(isImage) - { - RI_ASSERT(!isPath && !isPaint && !isFont); - getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, 1, &ret, false); - } - else if(isPath) - { - RI_ASSERT(!isImage && !isPaint && !isFont); - getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, 1, &ret, false); - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isFont); - getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, 1, &ret, false); - } - else - { - RI_ASSERT(!isImage && !isPath && !isPaint && isFont); - getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, 1, &ret, false); - } - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgGetParameterfv(VGHandle object, VGint paramType, VGint count, VGfloat * values) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(count <= 0 || !values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle - if(isImage) - { - RI_ASSERT(!isPath && !isPaint && !isFont); - getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, count, values, true); - } - else if(isPath) - { - RI_ASSERT(!isImage && !isPaint && !isFont); - getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, count, values, true); - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isFont); - getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, true); - } - else - { - RI_ASSERT(!isImage && !isPath && !isPaint && isFont); - getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, count, values, true); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgGetParameteriv(VGHandle object, VGint paramType, VGint count, VGint * values) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(count <= 0 || !values || !isAligned(values,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid object handle - if(isImage) - { - RI_ASSERT(!isPath && !isPaint && !isFont); - getImageParameterifv(context, (Image*)object, (VGImageParamType)paramType, count, values, false); - } - else if(isPath) - { - RI_ASSERT(!isImage && !isPaint && !isFont); - getPathParameterifv(context, (Path*)object, (VGPathParamType)paramType, count, values, false); - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isFont); - getPaintParameterifv(context, (Paint*)object, (VGPaintParamType)paramType, count, values, false); - } - else - { - RI_ASSERT(!isImage && !isPath && !isPaint && isFont); - getFontParameterifv(context, (Font*)object, (VGFontParamType)paramType, count, values, false); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGint RI_APIENTRY vgGetParameterVectorSize(VGHandle object, VGint paramType) -{ - RI_GET_CONTEXT(0); - bool isImage = context->isValidImage(object); - bool isPath = context->isValidPath(object); - bool isPaint = context->isValidPaint(object); - bool isFont = context->isValidFont(object); - RI_IF_ERROR(!isImage && !isPath && !isPaint && !isFont, VG_BAD_HANDLE_ERROR, 0); //invalid object handle - int ret = 0; - if(isImage) - { - RI_ASSERT(!isPath && !isPaint && !isFont); - switch(paramType) - { - case VG_IMAGE_FORMAT: - case VG_IMAGE_WIDTH: - case VG_IMAGE_HEIGHT: - ret = 1; - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid paramType - break; - } - } - else if(isPath) - { - RI_ASSERT(!isImage && !isPaint && !isFont); - switch(paramType) - { - case VG_PATH_FORMAT: - case VG_PATH_DATATYPE: - case VG_PATH_SCALE: - case VG_PATH_BIAS: - case VG_PATH_NUM_SEGMENTS: - case VG_PATH_NUM_COORDS: - ret = 1; - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid paramType - break; - } - } - else if(isPaint) - { - RI_ASSERT(!isImage && !isPath && !isFont); - switch(paramType) - { - case VG_PAINT_TYPE: - case VG_PAINT_COLOR_RAMP_SPREAD_MODE: - case VG_PAINT_PATTERN_TILING_MODE: - ret = 1; - break; - - case VG_PAINT_COLOR: - case VG_PAINT_LINEAR_GRADIENT: - ret = 4; - break; - - case VG_PAINT_COLOR_RAMP_STOPS: - ret = ((Paint*)object)->m_inputColorRampStops.size() * 5; - break; - - case VG_PAINT_COLOR_RAMP_PREMULTIPLIED: - ret = 1; - break; - - case VG_PAINT_RADIAL_GRADIENT: - ret = 5; - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid paramType - break; - } - } - else - { - RI_ASSERT(!isImage && !isPath && !isPaint && isFont); - switch(paramType) - { - case VG_FONT_NUM_GLYPHS: - ret = 1; - break; - - default: - context->setError(VG_ILLEGAL_ARGUMENT_ERROR); //invalid paramType - break; - } - } - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static Matrix3x3* getCurrentMatrix(VGContext* context) -{ - RI_ASSERT(context); - switch(context->m_matrixMode) - { - case VG_MATRIX_PATH_USER_TO_SURFACE: - return &context->m_pathUserToSurface; - - case VG_MATRIX_IMAGE_USER_TO_SURFACE: - return &context->m_imageUserToSurface; - - case VG_MATRIX_FILL_PAINT_TO_USER: - return &context->m_fillPaintToUser; - - case VG_MATRIX_STROKE_PAINT_TO_USER: - return &context->m_strokePaintToUser; - - default: - RI_ASSERT(context->m_matrixMode == VG_MATRIX_GLYPH_USER_TO_SURFACE); - return &context->m_glyphUserToSurface; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgLoadIdentity(void) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - Matrix3x3* d = getCurrentMatrix(context); - d->identity(); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgLoadMatrix(const VGfloat * m) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Matrix3x3* d = getCurrentMatrix(context); - d->set(inputFloat(m[0]), inputFloat(m[3]), inputFloat(m[6]), - inputFloat(m[1]), inputFloat(m[4]), inputFloat(m[7]), - inputFloat(m[2]), inputFloat(m[5]), inputFloat(m[8])); - if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE) - { - (*d)[2].set(0,0,1); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgGetMatrix(VGfloat * m) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Matrix3x3* d = getCurrentMatrix(context); - m[0] = (*d)[0][0]; - m[1] = (*d)[1][0]; - m[2] = (*d)[2][0]; - m[3] = (*d)[0][1]; - m[4] = (*d)[1][1]; - m[5] = (*d)[2][1]; - m[6] = (*d)[0][2]; - m[7] = (*d)[1][2]; - m[8] = (*d)[2][2]; - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgMultMatrix(const VGfloat * m) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!m || !isAligned(m,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Matrix3x3 n(inputFloat(m[0]), inputFloat(m[3]), inputFloat(m[6]), - inputFloat(m[1]), inputFloat(m[4]), inputFloat(m[7]), - inputFloat(m[2]), inputFloat(m[5]), inputFloat(m[8])); - if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE) - n[2].set(0,0,1); - - Matrix3x3* d = getCurrentMatrix(context); - *d *= n; - - d->validate(); - //d->assertValid(); - - if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE) - { - (*d)[2].set(0,0,1); //force affinity - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgTranslate(VGfloat tx, VGfloat ty) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - Matrix3x3 n(1, 0, inputFloat(tx), - 0, 1, inputFloat(ty), - 0, 0, 1 ); - Matrix3x3* d = getCurrentMatrix(context); - *d *= n; - - d->validate(); - //d->assertValid(); - - if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE) - { - (*d)[2].set(0,0,1); //force affinity - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgScale(VGfloat sx, VGfloat sy) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - Matrix3x3 n(inputFloat(sx), 0, 0, - 0, inputFloat(sy), 0, - 0, 0, 1 ); - Matrix3x3* d = getCurrentMatrix(context); - *d *= n; - - d->validate(); - //d->assertValid(); - - if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE) - { - (*d)[2].set(0,0,1); //force affinity - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgShear(VGfloat shx, VGfloat shy) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - Matrix3x3 n(1, inputFloat(shx), 0, - inputFloat(shy), 1, 0, - 0, 0, 1); - Matrix3x3* d = getCurrentMatrix(context); - *d *= n; - - d->validate(); - //d->assertValid(); - - if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE) - { - (*d)[2].set(0,0,1); //force affinity - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgRotate(VGfloat angle) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RIfloat a = RI_DEG_TO_RAD(inputFloat(angle)); - Matrix3x3 n((RIfloat)cos(a), -(RIfloat)sin(a), 0, - (RIfloat)sin(a), (RIfloat)cos(a), 0, - 0, 0, 1 ); - Matrix3x3* d = getCurrentMatrix(context); - *d *= n; - - d->validate(); - //d->assertValid(); - - if(context->m_matrixMode != VG_MATRIX_IMAGE_USER_TO_SURFACE) - { - (*d)[2].set(0,0,1); //force affinity - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgMask(VGHandle mask, VGMaskOperation operation, VGint x, VGint y, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - const bool isImage = context->isValidImage(mask); - const bool isMaskLayer = context->isValidMaskLayer(mask); - const bool needInput = (operation != VG_CLEAR_MASK) && (operation != VG_FILL_MASK); - RI_IF_ERROR(operation != VG_CLEAR_MASK && operation != VG_FILL_MASK && !isImage && !isMaskLayer, VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(operation != VG_CLEAR_MASK && operation != VG_FILL_MASK && isImage && eglvgIsInUse((Image*)mask), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(operation < VG_CLEAR_MASK || operation > VG_SUBTRACT_MASK, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Drawable* drawable = context->getCurrentDrawable(); - RI_IF_ERROR(isMaskLayer && drawable->getNumSamples() != ((Surface*)mask)->getNumSamples(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - if(!drawable || !drawable->getMaskBuffer()) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment or context has no mask buffer - } - - if(isImage) - drawable->getMaskBuffer()->mask(context->getBlitter(), (Image*)mask, operation, x, y, width, height); - else - { - RI_ASSERT(!isMaskLayer ? !needInput : true); - drawable->getMaskBuffer()->mask(context->getBlitter(), (!mask || !needInput) ? NULL : ((Surface*)mask)->getImage(), operation, x, y, width, height); - } - - RI_RETURN(RI_NO_RETVAL); -} - -void RI_APIENTRY vgRenderToMask(VGPath path, VGbitfield paintModes, VGMaskOperation operation) -{ - Path* iPath = (Path*)path; - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - RI_IF_ERROR(!paintModes || (paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //invalid paint mode - RI_IF_ERROR(operation < VG_CLEAR_MASK || operation > VG_SUBTRACT_MASK, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Drawable* curr = context->getCurrentDrawable(); - const Surface* mask = curr->getMaskBuffer(); - if(!curr || !curr->getMaskBuffer()) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment or context has no mask buffer - } - - if(operation == VG_CLEAR_MASK || operation == VG_FILL_MASK) - { - //RI_ASSERT(false); // should call fill! - Image* dummy = NULL; - curr->getMaskBuffer()->mask(context->getBlitter(), dummy, operation, 0, 0, curr->getWidth(), curr->getHeight()); - RI_RETURN(RI_NO_RETVAL); - } - - try - { - // Create a temporary image to render the path on for some mask operations. - // \todo tero: There are optimizations that can do all the mask operations in one pass, but it - // takes too much time to implement them now. - Drawable *tmpDrawable = NULL; - - try - { - if (operation == VG_INTERSECT_MASK) - { - tmpDrawable = RI_NEW(Drawable, (Color::formatToDescriptor(VG_A_8), curr->getWidth(), curr->getHeight(), 1, 0)); - } - } catch (std::bad_alloc e) - { - throw e; - } - - //Drawable drawable(Color::formatToDescriptor(VG_A_8), curr->getWidth(), curr->getHeight(), curr->getNumSamples(), 1); //TODO 0 mask bits (mask buffer is not used) - - Rasterizer& rasterizer = context->m_rasterizer; - rasterizer.clear(); - - rasterizer.setScissoring(context->m_scissoring ? true : false); - if(context->m_scissoring) - rasterizer.setScissor(context->m_scissor); //throws bad_alloc - - PixelPipe& pixelPipe = context->m_pixelPipe; - - // \hack If the mask operation is intersect, we render normally to tempbuffer! - if (!tmpDrawable) - pixelPipe.setRenderToMask(true); - else - pixelPipe.setRenderToMask(false); - - bool skipFill = false; - - if (operation == VG_SET_MASK) - { - Surface *maskSurface = curr->getMaskBuffer(); - maskSurface->clear(Color(), 0, 0, maskSurface->getWidth(), maskSurface->getHeight()); - skipFill = true; - } - - skipFill = skipFill && (paintModes & VG_STROKE_PATH); - - pixelPipe.setMaskOperation(operation); - pixelPipe.setDrawable(tmpDrawable ? tmpDrawable : curr); - pixelPipe.setImage(NULL, VG_DRAW_IMAGE_NORMAL); - pixelPipe.setMask(false); - pixelPipe.setPaint(NULL); //use default paint (solid color alpha = 1) - pixelPipe.setBlendMode(VG_BLEND_SRC_OVER); //write solid color * coverage to dest - bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true; - rasterizer.setAntiAliasing(aa); - - Matrix3x3 userToSurface = context->m_pathUserToSurface; - userToSurface[2].set(0,0,1); //force affinity - - if((paintModes & VG_FILL_PATH) && (!skipFill)) - { - rasterizer.clear(); - rasterizer.setup(0, 0, mask->getWidth(), mask->getHeight(), context->m_fillRule, &pixelPipe); - pixelPipe.prepareSpanUniforms(aa); - iPath->fill(userToSurface, rasterizer); //throws bad_alloc - rasterizer.fill(); //throws bad_alloc - //curr->getMaskBuffer()->mask(drawable.getColorBuffer(), operation, 0, 0, drawable.getWidth(), drawable.getHeight()); - if (tmpDrawable) - { - RI_ASSERT(operation == VG_INTERSECT_MASK); - curr->getMaskBuffer()->mask(context->getBlitter(), tmpDrawable->getColorBuffer()->getImage(), operation, 0, 0, tmpDrawable->getWidth(), tmpDrawable->getHeight()); - - if (paintModes & VG_STROKE_PATH) - { - Surface* tmpSurf = tmpDrawable->getColorBuffer(); - tmpSurf->clear(Color(), 0, 0, - tmpSurf->getWidth(), tmpSurf->getHeight()); - } - else - { - RI_DELETE(tmpDrawable); - tmpDrawable = NULL; - } - } - - } - - if((paintModes & VG_STROKE_PATH) && context->m_strokeLineWidth > 0.0f) - { - pixelPipe.prepareSpanUniforms(aa); - rasterizer.clear(); - rasterizer.setup(0, 0, mask->getWidth(), mask->getHeight(), VG_NON_ZERO, &pixelPipe); - - iPath->stroke(userToSurface, rasterizer, context->m_strokeDashPattern, context->m_strokeDashPhase, context->m_strokeDashPhaseReset ? true : false, - context->m_strokeLineWidth, context->m_strokeCapStyle, context->m_strokeJoinStyle, RI_MAX(context->m_strokeMiterLimit, 1.0f)); //throws bad_alloc - rasterizer.fill(); //throws bad_alloc - //curr->getMaskBuffer()->mask(drawable.getColorBuffer(), operation, 0, 0, drawable.getWidth(), drawable.getHeight()); - - if (tmpDrawable) - { - RI_ASSERT(operation == VG_INTERSECT_MASK); - curr->getMaskBuffer()->mask(context->getBlitter(), tmpDrawable->getColorBuffer()->getImage(), operation, 0, 0, tmpDrawable->getWidth(), tmpDrawable->getHeight()); - RI_DELETE(tmpDrawable); - tmpDrawable = NULL; - } - } - RI_ASSERT(!tmpDrawable); - - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGMaskLayer RI_APIENTRY vgCreateMaskLayer(VGint width, VGint height) -{ - RI_GET_CONTEXT(VG_INVALID_HANDLE); - RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); - RI_IF_ERROR(width > RI_MAX_IMAGE_WIDTH || height > RI_MAX_IMAGE_HEIGHT || width*height > RI_MAX_IMAGE_PIXELS || - width*height > RI_MAX_IMAGE_BYTES, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); - Drawable* curr = context->getCurrentDrawable(); - if(!curr || !curr->getMaskBuffer()) - RI_RETURN(VG_INVALID_HANDLE); //no current drawing surface - - Surface* layer = NULL; - try - { - layer = RI_NEW(Surface, (Color::formatToDescriptor(VG_A_8), width, height, curr->getNumSamples())); //throws bad_alloc - RI_ASSERT(layer); - context->m_maskLayerManager->addResource(layer, context); //throws bad_alloc - layer->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height); - RI_RETURN((VGMaskLayer)layer); - } - catch(std::bad_alloc) - { - RI_DELETE(layer); - context->setError(VG_OUT_OF_MEMORY_ERROR); - RI_RETURN(VG_INVALID_HANDLE); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgDestroyMaskLayer(VGMaskLayer maskLayer) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid handle - - context->m_maskLayerManager->removeResource((Surface*)maskLayer); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgFillMaskLayer(VGMaskLayer maskLayer, VGint x, VGint y, VGint width, VGint height, VGfloat value) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid handle - RI_IF_ERROR(value < 0.0f || value > 1.0f, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Surface* layer = (Surface*)maskLayer; - RI_IF_ERROR(width <= 0 || height <= 0 || x < 0 || y < 0 || x > layer->getWidth()-width || y > layer->getHeight()-height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - layer->clear(Color(1,1,1,value,Color::sRGBA), x, y, width, height); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgCopyMask(VGMaskLayer maskLayer, VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidMaskLayer(maskLayer), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid handle - Drawable* drawable = context->getCurrentDrawable(); - if(!drawable || !drawable->getMaskBuffer()) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment or context has no mask buffer - } - Surface* layer = (Surface*)maskLayer; - RI_IF_ERROR(width <= 0 || height <= 0 || drawable->getNumSamples() != layer->getNumSamples(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - try - { //copy drawing surface mask to mask layer - // \note Removed support for msaa - layer->m_image->blit(context, drawable->getMaskBuffer()->getImage(), sx, sy, dx, dy, width, height); - //layer->blit(drawable->getMaskBuffer(), sx, sy, dx, dy, width, height); //throws bad_alloc - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgClear(VGint x, VGint y, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Drawable* drawable = context->getCurrentDrawable(); - if(!drawable) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment - } - - try - { - if(context->m_scissoring) - drawable->getColorBuffer()->clear(context->m_clearColor, x, y, width, height, &context->m_scissor); //throws bad_alloc - else - drawable->getColorBuffer()->clear(context->m_clearColor, x, y, width, height); - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGPath RI_APIENTRY vgCreatePath(VGint pathFormat, VGPathDatatype datatype, VGfloat scale, VGfloat bias, VGint segmentCapacityHint, VGint coordCapacityHint, VGbitfield capabilities) -{ - RI_GET_CONTEXT(VG_INVALID_HANDLE); - RI_IF_ERROR(pathFormat != VG_PATH_FORMAT_STANDARD, VG_UNSUPPORTED_PATH_FORMAT_ERROR, VG_INVALID_HANDLE); - RI_IF_ERROR(datatype < VG_PATH_DATATYPE_S_8 || datatype > VG_PATH_DATATYPE_F, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); - RIfloat s = inputFloat(scale); - RIfloat b = inputFloat(bias); - RI_IF_ERROR(s == 0.0f, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); - capabilities &= VG_PATH_CAPABILITY_ALL; //undefined bits are ignored - - Path* path = NULL; - try - { - path = RI_NEW(Path, (pathFormat, datatype, s, b, segmentCapacityHint, coordCapacityHint, capabilities)); //throws bad_alloc - RI_ASSERT(path); - context->m_pathManager->addResource(path, context); //throws bad_alloc - RI_RETURN((VGPath)path); - } - catch(std::bad_alloc) - { - RI_DELETE(path); - context->setError(VG_OUT_OF_MEMORY_ERROR); - RI_RETURN(VG_INVALID_HANDLE); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgClearPath(VGPath path, VGbitfield capabilities) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - capabilities &= VG_PATH_CAPABILITY_ALL; //undefined bits are ignored - ((Path*)path)->clear(capabilities); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgDestroyPath(VGPath path) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - - context->m_pathManager->removeResource((Path*)path); - - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgRemovePathCapabilities(VGPath path, VGbitfield capabilities) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - capabilities &= VG_PATH_CAPABILITY_ALL; //undefined bits are ignored - - VGbitfield caps = ((Path*)path)->getCapabilities(); - caps &= ~capabilities; - ((Path*)path)->setCapabilities(caps); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGbitfield RI_APIENTRY vgGetPathCapabilities(VGPath path) -{ - RI_GET_CONTEXT(0); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, 0); //invalid path handle - VGbitfield ret = ((Path*)path)->getCapabilities(); - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgAppendPathData(VGPath dstPath, VGint numSegments, const VGubyte * pathSegments, const void * pathData) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(dstPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - Path* p = (Path*)dstPath; - RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_APPEND_TO), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL); //no append cap - RI_IF_ERROR(numSegments <= 0 || !pathSegments || !pathData, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //no segments or data - RI_IF_ERROR((p->getDatatype() == VG_PATH_DATATYPE_S_16 && !isAligned(pathData,2)) || - ((p->getDatatype() == VG_PATH_DATATYPE_S_32 || p->getDatatype() == VG_PATH_DATATYPE_F) && !isAligned(pathData,4)), - VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //invalid alignment - for(int i=0;i VG_LCWARC_TO, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //invalid segment - RI_IF_ERROR(c & ~0x1f, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //reserved bits are nonzero - } - - try - { - p->appendData((const RIuint8*)pathSegments, numSegments, (const RIuint8*)pathData); //throws bad_alloc - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgModifyPathCoords(VGPath dstPath, VGint startIndex, VGint numSegments, const void * pathData) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(dstPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - Path* p = (Path*)dstPath; - RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_MODIFY), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL); //no modify cap - RI_IF_ERROR(!pathData || startIndex < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startIndex, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //no segments - RI_IF_ERROR((p->getDatatype() == VG_PATH_DATATYPE_S_16 && !isAligned(pathData,2)) || - ((p->getDatatype() == VG_PATH_DATATYPE_S_32 || p->getDatatype() == VG_PATH_DATATYPE_F) && !isAligned(pathData,4)), - VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //invalid alignment - p->modifyCoords(startIndex, numSegments, (const RIuint8*)pathData); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgAppendPath(VGPath dstPath, VGPath srcPath) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(srcPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_APPEND_TO) || - !(((Path*)srcPath)->getCapabilities() & VG_PATH_CAPABILITY_APPEND_FROM), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL); //invalid caps - - try - { - ((Path*)dstPath)->append((Path*)srcPath); //throws bad_alloc - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgTransformPath(VGPath dstPath, VGPath srcPath) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(srcPath), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_TRANSFORM_TO) || - !(((Path*)srcPath)->getCapabilities() & VG_PATH_CAPABILITY_TRANSFORM_FROM), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL); //invalid caps - try - { - ((Path*)dstPath)->transform((Path*)srcPath, context->m_pathUserToSurface); //throws bad_alloc - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static bool drawPath(VGContext* context, VGPath path, const Matrix3x3& userToSurfaceMatrix, VGbitfield paintModes) -{ - Path* iPath = (Path*)path; - //set up rendering surface and mask buffer - Drawable* drawable = context->getCurrentDrawable(); - if(!drawable) - return false; //no EGL surface is current at the moment - - Rasterizer& rasterizer = context->m_rasterizer; - rasterizer.clear(); - - if(context->m_scissoring) - { - rasterizer.setScissor(context->m_scissor); //throws bad_alloc - } - rasterizer.setScissoring(context->m_scissoring ? true : false); - - PixelPipe& pixelPipe = context->m_pixelPipe; - pixelPipe.setRenderToMask(false); - pixelPipe.setDrawable(drawable); - pixelPipe.setImage(NULL, VG_DRAW_IMAGE_NORMAL); - pixelPipe.setMask(context->m_masking ? true : false); - pixelPipe.setBlendMode(context->m_blendMode); - pixelPipe.setTileFillColor(context->m_tileFillColor); - pixelPipe.setImageQuality(context->m_imageQuality); - pixelPipe.setColorTransform(context->m_colorTransform ? true : false, context->m_colorTransformValues); - bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true; - rasterizer.setAntiAliasing(aa); - - Matrix3x3 userToSurface = userToSurfaceMatrix; - userToSurface[2].set(0,0,1); //force affinity - - if(paintModes & VG_FILL_PATH) - { - // \todo Reorganize so that pipe.setpaint handles/requires the matrix setup? - pixelPipe.setPaint((Paint*)context->m_fillPaint); - - Matrix3x3 paintToSurfaceMatrix = userToSurface * context->m_fillPaintToUser; - Matrix3x3 surfaceToPaintMatrix = paintToSurfaceMatrix; - if(surfaceToPaintMatrix.invert()) - { - surfaceToPaintMatrix[2].set(0,0,1); //force affinity - pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix); - pixelPipe.prepareSpanUniforms(aa); - - rasterizer.clear(); - rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), context->m_fillRule, &pixelPipe); - iPath->fill(userToSurface, rasterizer); //throws bad_alloc - rasterizer.fill(); //throws bad_alloc - } - } - - if(paintModes & VG_STROKE_PATH && context->m_strokeLineWidth > 0.0f) - { - pixelPipe.setPaint((Paint*)context->m_strokePaint); - - Matrix3x3 paintToSurfaceMatrix = userToSurface * context->m_strokePaintToUser; - Matrix3x3 surfaceToPaintMatrix = paintToSurfaceMatrix; - if(surfaceToPaintMatrix.invert()) - { - surfaceToPaintMatrix[2].set(0,0,1); //force affinity - pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix); - pixelPipe.prepareSpanUniforms(aa); - - rasterizer.clear(); - rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_NON_ZERO, &pixelPipe); - iPath->stroke(userToSurface, rasterizer, context->m_strokeDashPattern, context->m_strokeDashPhase, context->m_strokeDashPhaseReset ? true : false, - context->m_strokeLineWidth, context->m_strokeCapStyle, context->m_strokeJoinStyle, RI_MAX(context->m_strokeMiterLimit, 1.0f)); //throws bad_alloc - rasterizer.fill(); //throws bad_alloc - - } - } - return true; -} - -void RI_APIENTRY vgDrawPath(VGPath path, VGbitfield paintModes) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - RI_IF_ERROR(!paintModes || (paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //invalid paint mode - - try - { - eglvgLockSurface(0, 1); - if(!drawPath(context, path, context->m_pathUserToSurface, paintModes)) - { - eglvgUnlockSurface(); - RI_RETURN(RI_NO_RETVAL); - } - eglvgUnlockSurface(); - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGfloat RI_APIENTRY vgPathLength(VGPath path, VGint startSegment, VGint numSegments) -{ - RI_GET_CONTEXT(-1.0f); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, -1.0f); //invalid path handle - Path* p = (Path*)path; - RI_IF_ERROR(!(p->getCapabilities() & VG_PATH_CAPABILITY_PATH_LENGTH), VG_PATH_CAPABILITY_ERROR, -1.0f); //invalid caps - RI_IF_ERROR(startSegment < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startSegment, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, -1.0f); - RIfloat pathLength = -1.0f; - try - { - pathLength = p->getPathLength(startSegment, numSegments); //throws bad_alloc - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(pathLength); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgPointAlongPath(VGPath path, VGint startSegment, VGint numSegments, VGfloat distance, VGfloat * x, VGfloat * y, VGfloat * tangentX, VGfloat * tangentY) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - Path* p = (Path*)path; - RI_IF_ERROR((x && y && !(p->getCapabilities() & VG_PATH_CAPABILITY_POINT_ALONG_PATH)) || - (tangentX && tangentY && !(p->getCapabilities() & VG_PATH_CAPABILITY_TANGENT_ALONG_PATH)), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL); //invalid caps - RI_IF_ERROR(startSegment < 0 || numSegments <= 0 || RI_INT_ADDSATURATE(startSegment, numSegments) > p->getNumSegments(), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!isAligned(x,4) || !isAligned(y,4) || !isAligned(tangentX,4) || !isAligned(tangentY,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - try - { - Vector2 point, tangent; - p->getPointAlong(startSegment, numSegments, distance, point, tangent); //throws bad_alloc - if(x && y) - { - *x = point.x; - *y = point.y; - } - if(tangentX && tangentY) - { - tangent.normalize(); - *tangentX = tangent.x; - *tangentY = tangent.y; - } - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgPathBounds(VGPath path, VGfloat * minx, VGfloat * miny, VGfloat * width, VGfloat * height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - RI_IF_ERROR(!(((Path*)path)->getCapabilities() & VG_PATH_CAPABILITY_PATH_BOUNDS), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL); //invalid caps - RI_IF_ERROR(!minx || !miny || !width || !height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!isAligned(minx,4) || !isAligned(miny,4) || !isAligned(width,4) || !isAligned(height,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - try - { - RIfloat pminx,pminy,pmaxx,pmaxy; - ((Path*)path)->getPathBounds(pminx, pminy, pmaxx, pmaxy); //throws bad_alloc - *minx = pminx; - *miny = pminy; - *width = pmaxx - pminx; - *height = pmaxy - pminy; - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgPathTransformedBounds(VGPath path, VGfloat * minx, VGfloat * miny, VGfloat * width, VGfloat * height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - RI_IF_ERROR(!(((Path*)path)->getCapabilities() & VG_PATH_CAPABILITY_PATH_TRANSFORMED_BOUNDS), VG_PATH_CAPABILITY_ERROR, RI_NO_RETVAL); //invalid caps - RI_IF_ERROR(!minx || !miny || !width || !height, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!isAligned(minx,4) || !isAligned(miny,4) || !isAligned(width,4) || !isAligned(height,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - try - { - RIfloat pminx, pminy, pmaxx, pmaxy; - ((Path*)path)->getPathTransformedBounds(context->m_pathUserToSurface, pminx, pminy, pmaxx, pmaxy); //throws bad_alloc - *minx = pminx; - *miny = pminy; - *width = pmaxx - pminx; - *height = pmaxy - pminy; - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGboolean RI_APIENTRY vgInterpolatePath(VGPath dstPath, VGPath startPath, VGPath endPath, VGfloat amount) -{ - RI_GET_CONTEXT(VG_FALSE); - RI_IF_ERROR(!context->isValidPath(dstPath) || !context->isValidPath(startPath) || !context->isValidPath(endPath), VG_BAD_HANDLE_ERROR, VG_FALSE); //invalid path handle - RI_IF_ERROR(!(((Path*)dstPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_TO) || - !(((Path*)startPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_FROM) || - !(((Path*)endPath)->getCapabilities() & VG_PATH_CAPABILITY_INTERPOLATE_FROM), VG_PATH_CAPABILITY_ERROR, VG_FALSE); //invalid caps - VGboolean ret = VG_FALSE; - try - { - if(((Path*)dstPath)->interpolate((const Path*)startPath, (const Path*)endPath, inputFloat(amount))) //throws bad_alloc - ret = VG_TRUE; - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGPaint RI_APIENTRY vgCreatePaint(void) -{ - RI_GET_CONTEXT(VG_INVALID_HANDLE); - Paint* paint = NULL; - RI_TRACE("\n***** vgCreatePaint\n"); - try - { - paint = RI_NEW(Paint, ()); //throws bad_alloc - RI_ASSERT(paint); - context->m_paintManager->addResource(paint, context); //throws bad_alloc - RI_TRACE("===== vgCreatePaint: Created paint obj: %x\n", (int)paint); - RI_RETURN((VGPaint)paint); - } - catch(std::bad_alloc) - { - RI_DELETE(paint); - context->setError(VG_OUT_OF_MEMORY_ERROR); - RI_RETURN(VG_INVALID_HANDLE); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgDestroyPaint(VGPaint paint) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid paint handle - - context->m_paintManager->removeResource((Paint*)paint); - - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetPaint(VGPaint paint, VGbitfield paintModes) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_TRACE("\n***** vgSetPaint: %x mode: %d\n", (int)paint, (int)paintModes); - RI_IF_ERROR(paint && !context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid paint handle - RI_IF_ERROR(!paintModes || paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //invalid paint mode - - context->releasePaint(paintModes); - - if(paintModes & VG_FILL_PATH) - { - if(paint) - ((Paint*)paint)->addReference(); - context->m_fillPaint = paint; - } - if(paintModes & VG_STROKE_PATH) - { - if(paint) - ((Paint*)paint)->addReference(); - context->m_strokePaint = paint; - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetColor(VGPaint paint, VGuint rgba) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_TRACE("\n***** vgSetColor: %x, rgba: %x\n", paint, rgba); - RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid paint handle - Paint* p = (Paint*)paint; - p->m_inputPaintColor.unpack(rgba, Color::formatToDescriptor(VG_sRGBA_8888)); - p->setColor(inputColor(p->m_inputPaintColor)); - RI_TRACE("** -> [%.3f %.3f %.3f %.3f]\n", p->m_paintColor.r, p->m_paintColor.g, p->m_paintColor.b, p->m_paintColor.a); -// p->m_paintColor = inputColor(p->m_inputPaintColor); -// p->m_paintColor.clamp(); -// p->m_paintColor.premultiply(); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGuint RI_APIENTRY vgGetColor(VGPaint paint) -{ - RI_GET_CONTEXT(0); - RI_IF_ERROR(!context->isValidPaint(paint), VG_BAD_HANDLE_ERROR, 0); //invalid paint handle - Color tempColor = ((Paint*)paint)->m_inputPaintColor; - tempColor.clamp(); - unsigned int ret = tempColor.pack(Color::formatToDescriptor(VG_sRGBA_8888)); - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGPaint RI_APIENTRY vgGetPaint(VGPaintMode paintMode) -{ - RI_GET_CONTEXT(VG_INVALID_HANDLE); - RI_IF_ERROR(paintMode != VG_FILL_PATH && paintMode != VG_STROKE_PATH, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); //invalid paint mode - - if(paintMode == VG_FILL_PATH) - { - RI_RETURN(context->m_fillPaint); - } - RI_RETURN(context->m_strokePaint); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgPaintPattern(VGPaint paint, VGImage image) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidPaint(paint) || (image != VG_INVALID_HANDLE && !context->isValidImage(image)), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid handle - Image* img = (Image*)image; - Paint* pnt = (Paint*)paint; - RI_IF_ERROR(image != VG_INVALID_HANDLE && eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - Image* pattern = pnt->m_pattern; - if(pattern) - { - pattern->removeInUse(); - if(!pattern->removeReference()) - RI_DELETE(pattern); - } - pnt->m_pattern = img; - - if(img) - { - img->addReference(); - img->addInUse(); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGImage RI_APIENTRY vgCreateImage(VGImageFormat format, VGint width, VGint height, VGbitfield allowedQuality) -{ - RI_GET_CONTEXT(VG_INVALID_HANDLE); - RI_IF_ERROR(!isValidImageFormat(format), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, VG_INVALID_HANDLE); - RI_IF_ERROR(width <= 0 || height <= 0 || !allowedQuality || - (allowedQuality & ~(VG_IMAGE_QUALITY_NONANTIALIASED | VG_IMAGE_QUALITY_FASTER | VG_IMAGE_QUALITY_BETTER)), VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); - RI_IF_ERROR(width > RI_MAX_IMAGE_WIDTH || height > RI_MAX_IMAGE_HEIGHT || width*height > RI_MAX_IMAGE_PIXELS || - ((width*Color::formatToDescriptor(format).bitsPerPixel+7)/8)*height > RI_MAX_IMAGE_BYTES, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); - - Image* image = NULL; - try - { - image = RI_NEW(Image, (Color::formatToDescriptor(format), width, height, allowedQuality)); //throws bad_alloc - RI_ASSERT(image); - context->m_imageManager->addResource(image, context); //throws bad_alloc - RI_RETURN((VGImage)image); - } - catch(std::bad_alloc) - { - RI_DELETE(image); - context->setError(VG_OUT_OF_MEMORY_ERROR); - RI_RETURN(VG_INVALID_HANDLE); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgDestroyImage(VGImage image) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid image handle - - context->m_imageManager->removeResource((Image*)image); - - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgClearImage(VGImage image, VGint x, VGint y, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* img = (Image*)image; - RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - eglvgLockSurface(0, 1); - img->clear(context->m_clearColor, x, y, width, height); - eglvgUnlockSurface(); - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgImageSubData(VGImage image, const void * data, VGint dataStride, VGImageFormat dataFormat, VGint x, VGint y, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* img = (Image*)image; - RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - { - Image input(Color::formatToDescriptor(dataFormat), width, height, dataStride, const_cast((const RIuint8*)data)); - input.addReference(); - try - { - img->blit(context, &input, 0, 0, x, y, width, height); //throws bad_alloc - } - catch(std::bad_alloc) - { - } - input.removeReference(); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgGetImageSubData(VGImage image, void * data, VGint dataStride, VGImageFormat dataFormat, VGint x, VGint y, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* img = (Image*)image; - RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - { - Image output(Color::formatToDescriptor(dataFormat), width, height, dataStride, (RIuint8*)data); - output.addReference(); - try - { - output.blit(context, img, x, y, 0, 0, width, height); //throws bad_alloc - } - catch(std::bad_alloc) - { - } - output.removeReference(); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGImage RI_APIENTRY vgChildImage(VGImage parent, VGint x, VGint y, VGint width, VGint height) -{ - RI_GET_CONTEXT(VG_INVALID_HANDLE); - RI_IF_ERROR(!context->isValidImage(parent), VG_BAD_HANDLE_ERROR, VG_INVALID_HANDLE); - Image* p = (Image*)parent; - RI_IF_ERROR(eglvgIsInUse((Image*)parent), VG_IMAGE_IN_USE_ERROR, VG_INVALID_HANDLE); - RI_IF_ERROR(x < 0 || x >= p->getWidth() || y < 0 || y >= p->getHeight() || - width <= 0 || height <= 0 || RI_INT_ADDSATURATE(x, width) > p->getWidth() || RI_INT_ADDSATURATE(y, height) > p->getHeight(), VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); - - Image* child = NULL; - try - { - child = RI_NEW(Image, (p, x, y, width, height)); //throws bad_alloc - RI_ASSERT(child); - context->m_imageManager->addResource(child, context); //throws bad_alloc - RI_RETURN((VGImage)child); - } - catch(std::bad_alloc) - { - RI_DELETE(child); - context->setError(VG_OUT_OF_MEMORY_ERROR); - RI_RETURN(VG_INVALID_HANDLE); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGImage RI_APIENTRY vgGetParent(VGImage image) -{ - RI_GET_CONTEXT(VG_INVALID_HANDLE); - RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, VG_INVALID_HANDLE); - VGImage ret = image; //if image has no ancestors, image is returned. - - //The vgGetParent function returns the closest valid ancestor (i.e., one that has not been the target of a vgDestroyImage call) - // of the given image. - Image* im = ((Image*)image)->getParent(); - for(;im;im = im->getParent()) - { - if(context->isValidImage((VGImage)im)) - { //the parent is valid and alive - ret = (VGImage)im; - break; - } - } - RI_RETURN(ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgCopyImage(VGImage dst, VGint dx, VGint dy, VGImage src, VGint sx, VGint sy, VGint width, VGint height, VGboolean dither) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(eglvgIsInUse((Image*)dst) || eglvgIsInUse((Image*)src), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - try - { - ((Image*)dst)->blit(context, (Image*)src, sx, sy, dx, dy, width, height, NULL, dither ? true : false); //throws bad_alloc - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static bool drawImage(VGContext* context, VGImage image, const Matrix3x3& userToSurfaceMatrix) -{ - Drawable* drawable = context->getCurrentDrawable(); - if(!drawable) - return false; //no EGL surface is current at the moment - - Image* img = (Image*)image; - //transform image corners into the surface space - Vector3 p0(0, 0, 1); - Vector3 p1(0, (RIfloat)img->getHeight(), 1); - Vector3 p2((RIfloat)img->getWidth(), (RIfloat)img->getHeight(), 1); - Vector3 p3((RIfloat)img->getWidth(), 0, 1); - p0 = userToSurfaceMatrix * p0; - p1 = userToSurfaceMatrix * p1; - p2 = userToSurfaceMatrix * p2; - p3 = userToSurfaceMatrix * p3; - if(p0.z <= 0.0f || p1.z <= 0.0f || p2.z <= 0.0f || p3.z <= 0.0f) - return false; - - //projection - p0 *= 1.0f/p0.z; - p1 *= 1.0f/p1.z; - p2 *= 1.0f/p2.z; - p3 *= 1.0f/p3.z; - - Rasterizer& rasterizer = context->m_rasterizer; - rasterizer.clear(); - - rasterizer.setScissoring(context->m_scissoring ? true : false); - if(context->m_scissoring) - rasterizer.setScissor(context->m_scissor); //throws bad_alloc - - PixelPipe& pixelPipe = context->m_pixelPipe; - pixelPipe.setTileFillColor(context->m_tileFillColor); - pixelPipe.setPaint((Paint*)context->m_fillPaint); - pixelPipe.setImageQuality(context->m_imageQuality); - pixelPipe.setBlendMode(context->m_blendMode); - pixelPipe.setRenderToMask(false); - pixelPipe.setDrawable(drawable); - pixelPipe.setMask(context->m_masking ? true : false); - pixelPipe.setColorTransform(context->m_colorTransform ? true : false, context->m_colorTransformValues); - const bool aa = context->m_renderingQuality == VG_RENDERING_QUALITY_NONANTIALIASED ? false : true; - rasterizer.setAntiAliasing(aa); - - Matrix3x3 surfaceToImageMatrix = userToSurfaceMatrix; - Matrix3x3 surfaceToPaintMatrix = userToSurfaceMatrix * context->m_fillPaintToUser; - if(surfaceToImageMatrix.invert() && surfaceToPaintMatrix.invert()) - { - VGImageMode imode = context->m_imageMode; - if(!surfaceToPaintMatrix.isAffine()) - imode = VG_DRAW_IMAGE_NORMAL; //if paint matrix is not affine, always use normal image mode - surfaceToPaintMatrix[2].set(0,0,1); //force affine - - pixelPipe.setImage(img, imode); - pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix); - pixelPipe.setSurfaceToImageMatrix(surfaceToImageMatrix); - pixelPipe.prepareSpanUniforms(aa); - rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_EVEN_ODD, &pixelPipe); - - rasterizer.addEdge(Vector2(p0.x,p0.y), Vector2(p1.x,p1.y)); //throws bad_alloc - rasterizer.addEdge(Vector2(p1.x,p1.y), Vector2(p2.x,p2.y)); //throws bad_alloc - rasterizer.addEdge(Vector2(p2.x,p2.y), Vector2(p3.x,p3.y)); //throws bad_alloc - rasterizer.addEdge(Vector2(p3.x,p3.y), Vector2(p0.x,p0.y)); //throws bad_alloc - - rasterizer.fill(); //throws bad_alloc - } - return true; -} - -void RI_APIENTRY vgDrawImage(VGImage image) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* img = (Image*)image; - RI_IF_ERROR(eglvgIsInUse(img), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - - try - { - if(!drawImage(context, image, context->m_imageUserToSurface)) - { - RI_RETURN(RI_NO_RETVAL); - } - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetPixels(VGint dx, VGint dy, VGImage src, VGint sx, VGint sy, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(eglvgIsInUse((Image*)src), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - - Drawable* drawable = context->getCurrentDrawable(); - Array* scissors = !context->m_scissoring ? NULL : &context->m_scissor; - if(!drawable) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment - } - try - { - drawable->getColorBuffer()->m_image->blit(context, (Image*)src, sx, sy, dx, dy, width, height, scissors, false); //throws bad_alloc - //drawable->getColorBuffer()->blit(*(Image*)src, sx, sy, dx, dy, width, height); //throws bad_alloc - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgWritePixels(const void * data, VGint dataStride, VGImageFormat dataFormat, VGint dx, VGint dy, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Drawable* drawable = context->getCurrentDrawable(); - if(!drawable) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment - } - { - Array* scissors = !context->m_scissoring ? NULL : &context->m_scissor; - Image input(Color::formatToDescriptor(dataFormat), width, height, dataStride, const_cast((const RIuint8*)data)); - input.addReference(); - try - { - drawable->getColorBuffer()->m_image->blit(context, &input, 0, 0, dx, dy, width, height, scissors, false); //throws bad_alloc - } - catch(std::bad_alloc) - { - // TEROP: out-of-mem? - } - input.removeReference(); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgGetPixels(VGImage dst, VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(dst), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(eglvgIsInUse((Image*)dst), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Drawable* drawable = context->getCurrentDrawable(); - if(!drawable) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment - } - try - { - ((Image*)dst)->blit(context, drawable->getColorBuffer()->m_image, sx, sy, dx, dy, width, height); //throws bad_alloc - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgReadPixels(void* data, VGint dataStride, VGImageFormat dataFormat, VGint sx, VGint sy, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!isValidImageFormat(dataFormat), VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!data || !isAligned(data, dataFormat) || width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Drawable* drawable = context->getCurrentDrawable(); - if(!drawable) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment - } - { - Image output(Color::formatToDescriptor(dataFormat), width, height, dataStride, (RIuint8*)data); - output.addReference(); - try - { - output.blit(context, drawable->getColorBuffer()->m_image, sx, sy, 0, 0, width, height); //throws bad_alloc - } - catch(std::bad_alloc) - { - } - output.removeReference(); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgCopyPixels(VGint dx, VGint dy, VGint sx, VGint sy, VGint width, VGint height) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(width <= 0 || height <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Drawable* drawable = context->getCurrentDrawable(); - Array* scissors = !context->m_scissoring ? NULL : &context->m_scissor; - if(!drawable) - { - RI_RETURN(RI_NO_RETVAL); //no EGL surface is current at the moment - } - try - { - drawable->getColorBuffer()->m_image->blit(context, drawable->getColorBuffer()->m_image, sx, sy, dx, dy, width, height, scissors, false); //throws bad_alloc - //drawable->getColorBuffer()->blit(drawable->getColorBuffer(), sx, sy, dx, dy, width, height); //throws bad_alloc - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgColorMatrix(VGImage dst, VGImage src, const VGfloat * matrix) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* d = (Image*)dst; - Image* s = (Image*)src; - RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!matrix || !isAligned(matrix,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA); //undefined bits are ignored - - RIfloat m[20]; - for(int i=0;i<20;i++) - { - m[i] = inputFloat(matrix[i]); - } - try - { - d->colorMatrix(*s, m, context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask); - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgConvolve(VGImage dst, VGImage src, VGint kernelWidth, VGint kernelHeight, VGint shiftX, VGint shiftY, const VGshort * kernel, VGfloat scale, VGfloat bias, VGTilingMode tilingMode) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* d = (Image*)dst; - Image* s = (Image*)src; - RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!kernel || !isAligned(kernel,2) || kernelWidth <= 0 || kernelHeight <= 0 || kernelWidth > RI_MAX_KERNEL_SIZE || kernelHeight > RI_MAX_KERNEL_SIZE, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA); //undefined bits are ignored - try - { - d->convolve(*s, kernelWidth, kernelHeight, shiftX, shiftY, (const RIint16*)kernel, inputFloat(scale), inputFloat(bias), tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask); - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSeparableConvolve(VGImage dst, VGImage src, VGint kernelWidth, VGint kernelHeight, VGint shiftX, VGint shiftY, const VGshort * kernelX, const VGshort * kernelY, VGfloat scale, VGfloat bias, VGTilingMode tilingMode) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* d = (Image*)dst; - Image* s = (Image*)src; - RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!kernelX || !kernelY || !isAligned(kernelX,2) || !isAligned(kernelY,2) || kernelWidth <= 0 || kernelHeight <= 0 || kernelWidth > RI_MAX_SEPARABLE_KERNEL_SIZE || kernelHeight > RI_MAX_SEPARABLE_KERNEL_SIZE, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA); //undefined bits are ignored - try - { - d->separableConvolve(*s, kernelWidth, kernelHeight, shiftX, shiftY, (const RIint16*)kernelX, (const RIint16*)kernelY, - inputFloat(scale), inputFloat(bias), tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false, - context->m_filterFormatPremultiplied ? true : false, channelMask); - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgGaussianBlur(VGImage dst, VGImage src, VGfloat stdDeviationX, VGfloat stdDeviationY, VGTilingMode tilingMode) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* d = (Image*)dst; - Image* s = (Image*)src; - RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RIfloat sx = inputFloat(stdDeviationX); - RIfloat sy = inputFloat(stdDeviationY); - RI_IF_ERROR(sx <= 0.0f || sy <= 0.0f || sx > (RIfloat)RI_MAX_GAUSSIAN_STD_DEVIATION || sy > (RIfloat)RI_MAX_GAUSSIAN_STD_DEVIATION, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(tilingMode < VG_TILE_FILL || tilingMode > VG_TILE_REFLECT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA); //undefined bits are ignored - try - { - d->gaussianBlur(*s, sx, sy, tilingMode, context->m_tileFillColor, context->m_filterFormatLinear ? true : false, - context->m_filterFormatPremultiplied ? true : false, channelMask); - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgLookup(VGImage dst, VGImage src, const VGubyte * redLUT, const VGubyte * greenLUT, const VGubyte * blueLUT, const VGubyte * alphaLUT, VGboolean outputLinear, VGboolean outputPremultiplied) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* d = (Image*)dst; - Image* s = (Image*)src; - RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!redLUT || !greenLUT || !blueLUT || !alphaLUT, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA); //undefined bits are ignored - try - { - d->lookup(*s, (const RIuint8*)redLUT, (const RIuint8*)greenLUT, (const RIuint8*)blueLUT, (const RIuint8*)alphaLUT, - outputLinear ? true : false, outputPremultiplied ? true : false, context->m_filterFormatLinear ? true : false, - context->m_filterFormatPremultiplied ? true : false, channelMask); - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgLookupSingle(VGImage dst, VGImage src, const VGuint * lookupTable, VGImageChannel sourceChannel, VGboolean outputLinear, VGboolean outputPremultiplied) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidImage(dst) || !context->isValidImage(src), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); - Image* d = (Image*)dst; - Image* s = (Image*)src; - RI_IF_ERROR(eglvgIsInUse(d) || eglvgIsInUse(s), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(d->overlaps(s), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(!lookupTable || !isAligned(lookupTable,4), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - const Color::Descriptor& desc = s->getDescriptor(); - RI_ASSERT(Color::isValidDescriptor(desc)); - //give an error if src is in rgb format and the source channel is not valid - RI_IF_ERROR((!desc.isLuminance() && !desc.isAlphaOnly()) && (sourceChannel != VG_RED && sourceChannel != VG_GREEN && sourceChannel != VG_BLUE && sourceChannel != VG_ALPHA), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - unsigned int channelMask = context->m_filterChannelMask & (VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA); //undefined bits are ignored - try - { - d->lookupSingle(*s, (const RIuint32*)lookupTable, sourceChannel, outputLinear ? true : false, outputPremultiplied ? true : false, - context->m_filterFormatLinear ? true : false, context->m_filterFormatPremultiplied ? true : false, channelMask); - } - catch(std::bad_alloc) - { - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGHardwareQueryResult RI_APIENTRY vgHardwareQuery(VGHardwareQueryType key, VGint setting) -{ - RI_GET_CONTEXT(VG_HARDWARE_UNACCELERATED); - RI_IF_ERROR(key != VG_IMAGE_FORMAT_QUERY && key != VG_PATH_DATATYPE_QUERY, VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED); - RI_IF_ERROR(key == VG_IMAGE_FORMAT_QUERY && !isValidImageFormat(setting), VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED); - RI_IF_ERROR(key == VG_PATH_DATATYPE_QUERY && (setting < VG_PATH_DATATYPE_S_8 || setting > VG_PATH_DATATYPE_F), VG_ILLEGAL_ARGUMENT_ERROR, VG_HARDWARE_UNACCELERATED); - RI_RETURN(VG_HARDWARE_UNACCELERATED); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -const VGubyte * RI_APIENTRY vgGetString(VGStringID name) -{ - static const VGubyte vendor[] = "Nokia"; - static const VGubyte renderer[] = {"OpenVG 1.1 Faster Reference Implementation May 13 2008"}; - static const VGubyte version[] = "1.1"; - static const VGubyte extensions[] = ""; - const VGubyte* r = NULL; - RI_GET_CONTEXT(NULL); - switch(name) - { - case VG_VENDOR: - r = vendor; - break; - case VG_RENDERER: - r = renderer; - break; - case VG_VERSION: - r = version; - break; - case VG_EXTENSIONS: - r = extensions; - break; - default: - break; - } - RI_RETURN(r); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGFont RI_APIENTRY vgCreateFont(VGint glyphCapacityHint) -{ - RI_GET_CONTEXT(VG_INVALID_HANDLE); - RI_IF_ERROR(glyphCapacityHint < 0, VG_ILLEGAL_ARGUMENT_ERROR, VG_INVALID_HANDLE); - - Font* font = NULL; - try - { - font = RI_NEW(Font, (glyphCapacityHint)); //throws bad_alloc - RI_ASSERT(font); - context->m_fontManager->addResource(font, context); //throws bad_alloc - RI_RETURN((VGFont)font); - } - catch(std::bad_alloc) - { - RI_DELETE(font); - context->setError(VG_OUT_OF_MEMORY_ERROR); - RI_RETURN(VG_INVALID_HANDLE); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgDestroyFont(VGFont font) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid font handle - - context->m_fontManager->removeResource((Font*)font); - - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetGlyphToPath(VGFont font, VGuint glyphIndex, VGPath path, VGboolean isHinted, const VGfloat glyphOrigin[2], const VGfloat escapement[2]) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid font handle - RI_IF_ERROR(path != VG_INVALID_HANDLE && !context->isValidPath(path), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid path handle - RI_IF_ERROR(!glyphOrigin || !escapement || !isAligned(glyphOrigin,sizeof(VGfloat)) || !isAligned(escapement,sizeof(VGfloat)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Font* f = (Font*)font; - - try - { - f->setGlyphToPath(glyphIndex, path, isHinted ? true : false, Vector2(inputFloat(glyphOrigin[0]), inputFloat(glyphOrigin[1])), Vector2(inputFloat(escapement[0]), inputFloat(escapement[1]))); - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgSetGlyphToImage(VGFont font, VGuint glyphIndex, VGImage image, const VGfloat glyphOrigin[2], const VGfloat escapement[2]) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid font handle - if(image != VG_INVALID_HANDLE) - { - RI_IF_ERROR(!context->isValidImage(image), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid image handle - RI_IF_ERROR(eglvgIsInUse((Image*)image), VG_IMAGE_IN_USE_ERROR, RI_NO_RETVAL); //image in use - } - RI_IF_ERROR(!glyphOrigin || !escapement || !isAligned(glyphOrigin,sizeof(VGfloat)) || !isAligned(escapement,sizeof(VGfloat)), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - Font* f = (Font*)font; - - try - { - f->setGlyphToImage(glyphIndex, image, Vector2(inputFloat(glyphOrigin[0]), inputFloat(glyphOrigin[1])), Vector2(inputFloat(escapement[0]), inputFloat(escapement[1]))); - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgClearGlyph(VGFont font, VGuint glyphIndex) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid font handle - Font* f = (Font*)font; - Font::Glyph* g = f->findGlyph(glyphIndex); - RI_IF_ERROR(!g, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //glyphIndex not defined - - f->clearGlyph(g); - - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgDrawGlyph(VGFont font, VGuint glyphIndex, VGbitfield paintModes, VGboolean allowAutoHinting) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid font handle - RI_IF_ERROR(paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //invalid paint mode - Font* f = (Font*)font; - Font::Glyph* g = f->findGlyph(glyphIndex); - RI_IF_ERROR(!g, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //glyphIndex not defined - RI_UNREF(allowAutoHinting); //RI doesn't implement autohinting - - try - { - if(paintModes) - { - Matrix3x3 userToSurfaceMatrix = context->m_glyphUserToSurface; - Vector2 t = context->m_glyphOrigin - g->m_origin; - Matrix3x3 n(1, 0, t.x, - 0, 1, t.y, - 0, 0, 1 ); - userToSurfaceMatrix *= n; - userToSurfaceMatrix[2].set(0,0,1); //force affinity - - bool ret = true; - eglvgLockSurface(0, 1); - if(g->m_image != VG_INVALID_HANDLE) - ret = drawImage(context, g->m_image, userToSurfaceMatrix); - else if(g->m_path != VG_INVALID_HANDLE) - ret = drawPath(context, g->m_path, userToSurfaceMatrix, paintModes); - eglvgUnlockSurface(); - if(!ret) - { - RI_RETURN(RI_NO_RETVAL); - } - } - - context->m_glyphOrigin += g->m_escapement; - context->m_inputGlyphOrigin = context->m_glyphOrigin; - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - - RI_RETURN(RI_NO_RETVAL); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void RI_APIENTRY vgDrawGlyphs(VGFont font, VGint glyphCount, const VGuint *glyphIndices, const VGfloat *adjustments_x, const VGfloat *adjustments_y, VGbitfield paintModes, VGboolean allowAutoHinting) -{ - RI_GET_CONTEXT(RI_NO_RETVAL); - RI_IF_ERROR(!context->isValidFont(font), VG_BAD_HANDLE_ERROR, RI_NO_RETVAL); //invalid font handle - RI_IF_ERROR(!glyphIndices || !isAligned(glyphIndices, sizeof(VGuint)) || glyphCount <= 0, VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR((adjustments_x && !isAligned(adjustments_x, sizeof(VGfloat))) || (adjustments_y && !isAligned(adjustments_y, sizeof(VGfloat))), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); - RI_IF_ERROR(paintModes & ~(VG_FILL_PATH | VG_STROKE_PATH), VG_ILLEGAL_ARGUMENT_ERROR, RI_NO_RETVAL); //invalid paint mode - Font* f = (Font*)font; - for(int i=0;ifindGlyph(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;ifindGlyph(glyphIndices[i]); - - if(paintModes) - { - Matrix3x3 userToSurfaceMatrix = context->m_glyphUserToSurface; - Vector2 t = context->m_glyphOrigin - g->m_origin; - Matrix3x3 n(1, 0, t.x, - 0, 1, t.y, - 0, 0, 1 ); - userToSurfaceMatrix *= n; - userToSurfaceMatrix[2].set(0,0,1); //force affinity - - bool ret = true; - if(g->m_image != VG_INVALID_HANDLE) - ret = drawImage(context, g->m_image, userToSurfaceMatrix); - else if(g->m_path != VG_INVALID_HANDLE) - ret = drawPath(context, g->m_path, userToSurfaceMatrix, paintModes); - if(!ret) - { - RI_RETURN(RI_NO_RETVAL); - } - } - - context->m_glyphOrigin += g->m_escapement; - if(adjustments_x) - context->m_glyphOrigin.x += inputFloat(adjustments_x[i]); - if(adjustments_y) - context->m_glyphOrigin.y += inputFloat(adjustments_y[i]); - context->m_inputGlyphOrigin = context->m_glyphOrigin; - } - } - catch(std::bad_alloc) - { - context->setError(VG_OUT_OF_MEMORY_ERROR); - } - RI_RETURN(RI_NO_RETVAL); -} - -VGint vgePathCoordsSizeInBytes(VGPath path, VGint startIndex, VGint numSegments) -{ - RI_GET_CONTEXT( 0 ); - RI_IF_ERROR(!context->isValidPath(path), VG_BAD_HANDLE_ERROR, 0); - VGint ret = ((OpenVGRI::Path*)path)->coordsSizeInBytes( startIndex, numSegments ); - RI_RETURN(ret); -} - - -VGImage vgCreateEGLImageTargetKHR(VGeglImageKHR image) -{ -#if defined(USE_FULL_EGL) - RI_GET_CONTEXT( 0 ); - VGImage ret; - OpenVGRI::Color::Descriptor desc; - OpenVGRI::RIuint8* data; - // Get data for VGImage - int width; - int height; - int stride; - - eglvgGetImageDescriptor( image, desc, width, height, stride ); - // There is some error. - // EGLImage is null or EGLImage target is EGL_VG_PARENT_IMAGE_KHR. - RI_IF_ERROR(!width || !height || !stride, VG_ILLEGAL_ARGUMENT_ERROR, NULL); - // Data is created in EGLImage class. - data = (OpenVGRI::RIuint8*)eglvgGetImageData( image ); - // Create VGImage - // allowedQuality = VG_IMAGE_QUALITY_NONANTIALIASED | VG_IMAGE_QUALITY_FASTER | VG_IMAGE_QUALITY_BETTER - ret = vgCreateImage( desc.vgFormat, width, height, VG_IMAGE_QUALITY_NONANTIALIASED ); - // If VGImage is not created raise error and return null - RI_IF_ERROR(!ret, VG_UNSUPPORTED_IMAGE_FORMAT_ERROR, NULL); - // Set data for VGImage. - // This will copy that data-object. - vgImageSubData( ret, - data, - stride, - desc.vgFormat, - 0, - 0, - width, - height); - // Return VGImage - RI_RETURN(ret); -#else - (void)image; - return VG_INVALID_HANDLE; -#endif //USE_FULL_EGL -} diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riArray.h --- a/hostsupport/hostopenvg/src/src/riArray.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,242 +0,0 @@ -#ifndef __RIARRAY_H -#define __RIARRAY_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Array class. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef __RIDEFS_H -#include "riDefs.h" -#endif - -#include //for memcpy - -namespace OpenVGRI -{ - -//======================================================================= - -/*-------------------------------------------------------------------*//*! -* \brief An array class similar to std::vector. -* \param -* \return -* \note Follows std::vector's naming convention (except resizeAndReallocate). -*//*-------------------------------------------------------------------*/ - -template class Array -{ -public: - friend class Rasterizer; - - Array() : m_array(NULL), m_size(0), m_allocated(0) {} //throws bad_alloc - ~Array() - { - RI_DELETE_ARRAY(m_array); - } - - void swap(Array& s) - { - Item* tarray = m_array; - m_array = s.m_array; - s.m_array = tarray; - - int tsize = m_size; - m_size = s.m_size; - s.m_size = tsize; - - int tallocated = m_allocated; - m_allocated = s.m_allocated; - s.m_allocated = tallocated; - } - - //if more room is needed, reallocate, otherwise return - void reserve( int items ) //throws bad_alloc - { - RI_ASSERT( items >= 0 ); - if( items <= m_allocated ) - return; //if there is room already, return - - RI_ASSERT( items > m_allocated ); - - Item* newa = RI_NEW_ARRAY(Item, items); //throws bad_alloc if runs out of memory - for(int i=0;i= 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 for decreasing.) - void sort() - { - if(m_size <= 1) - return; - quicksort(0, m_size - 1); - } - - void sort(int first, int last) - { - RI_ASSERT(first <= last); - RI_ASSERT((first >= 0) && (last < m_size)); - - if (m_size <= 1) - return; - - if ((last - first) < 1) - return; - - quicksort(first, last); -#if defined(RI_DEBUG) - for (int i = first+1; i <= last; i++) - { - RI_ASSERT(m_array[i-1] <= m_array[i]); - } -#endif - } - - int findIndex(const Item& item) - { - for(int i = 0; i < m_size; i++) - if (m_array[i] == item) - return i; - return -1; - } - - //remove the first occurrence of an item from the array - bool remove(const Item& item) - { - int i=0; - for(;i= m_size) - return false; //not found - for(;i= m_allocated ) - reserve( (!m_allocated) ? 8 : m_allocated * 2 ); //by default, reserve 8. throws bad_alloc if runs out of memory - m_array[m_size++] = item; - } - RI_INLINE int size() const { return m_size; } - RI_INLINE Item& operator[](int i) { RI_ASSERT(i >= 0 && i < m_size); return m_array[i]; } - RI_INLINE const Item& operator[](int i) const { RI_ASSERT(i >= 0 && i < m_size); return m_array[i]; } - -private: - Array(const Array& s); //!< Not allowed. - void operator=(const Array& s); //!< Not allowed. - - void quicksort(int left, int right) - { - int i = left, j = right; - Item x = m_array[(left+right)>>1]; - - do - { - while (m_array[i] < x) - i++; - while (x < m_array[j]) - j--; - if (i<=j) - { - Item tmp = m_array[i]; - m_array[i] = m_array[j]; - m_array[j] = tmp; - i++; - j--; - } - } while (i<=j); - - if(left < j) quicksort(left, j); - if(i < right) quicksort(i, right); - } - - - Item* m_array; - int m_size; - int m_allocated; -}; - -//======================================================================= - -} //namespace OpenVGRI - -#endif /* __RIARRAY_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riContext.cpp --- a/hostsupport/hostopenvg/src/src/riContext.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,332 +0,0 @@ -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementation of VGContext functions. - * \note - *//*-------------------------------------------------------------------*/ - -#include "riContext.h" - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief VGContext constructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGContext::VGContext(VGContext* shareContext) : - // Mode settings - m_matrixMode(VG_MATRIX_PATH_USER_TO_SURFACE), - m_fillRule(VG_EVEN_ODD), - m_imageQuality(VG_IMAGE_QUALITY_FASTER), - m_renderingQuality(VG_RENDERING_QUALITY_BETTER), - m_blendMode(VG_BLEND_SRC_OVER), - m_imageMode(VG_DRAW_IMAGE_NORMAL), - - // Scissor rectangles - m_scissor(), - - // Stroke parameters - m_strokeLineWidth(1.0f), - m_inputStrokeLineWidth(1.0f), - m_strokeCapStyle(VG_CAP_BUTT), - m_strokeJoinStyle(VG_JOIN_MITER), - m_strokeMiterLimit(4.0f), - m_inputStrokeMiterLimit(4.0f), - m_strokeDashPattern(), - m_inputStrokeDashPattern(), - m_strokeDashPhase(0.0f), - m_inputStrokeDashPhase(0.0f), - m_strokeDashPhaseReset(VG_FALSE), - - // Edge fill color for vgConvolve and pattern paint - m_tileFillColor(0,0,0,0, Color::sRGBA), - m_inputTileFillColor(0,0,0,0, Color::sRGBA), - - // Color for vgClear - m_clearColor(0,0,0,0, Color::sRGBA), - m_inputClearColor(0,0,0,0, Color::sRGBA), - - m_glyphOrigin(0.0f, 0.0f), - m_inputGlyphOrigin(0.0f, 0.0f), - - m_masking(VG_FALSE), - m_scissoring(VG_FALSE), - - m_pixelLayout(VG_PIXEL_LAYOUT_UNKNOWN), - - m_filterFormatLinear(VG_FALSE), - m_filterFormatPremultiplied(VG_FALSE), - m_filterChannelMask(VG_RED|VG_GREEN|VG_BLUE|VG_ALPHA), - - // Matrices - m_pathUserToSurface(), - m_imageUserToSurface(), - m_glyphUserToSurface(), - m_fillPaintToUser(), - m_strokePaintToUser(), - - m_fillPaint(VG_INVALID_HANDLE), - m_strokePaint(VG_INVALID_HANDLE), - - m_colorTransform(VG_FALSE), - m_colorTransformValues(), - m_inputColorTransformValues(), - - m_error(VG_NO_ERROR), - - m_imageManager(NULL), - m_pathManager(NULL), - m_paintManager(NULL), - m_fontManager(NULL), - m_maskLayerManager(NULL), - - m_eglDrawable(NULL) -{ - if(shareContext) - { - m_imageManager = shareContext->m_imageManager; - m_pathManager = shareContext->m_pathManager; - m_paintManager = shareContext->m_paintManager; - m_fontManager = shareContext->m_fontManager; - m_maskLayerManager = shareContext->m_maskLayerManager; - } - else - { - try - { - m_imageManager = RI_NEW(OpenVGRI::ResourceManager, ()); //throws bad_alloc - m_pathManager = RI_NEW(OpenVGRI::ResourceManager, ()); //throws bad_alloc - m_paintManager = RI_NEW(OpenVGRI::ResourceManager, ()); //throws bad_alloc - m_fontManager = RI_NEW(OpenVGRI::ResourceManager, ()); //throws bad_alloc - m_maskLayerManager = RI_NEW(OpenVGRI::ResourceManager, ()); //throws bad_alloc - } - catch(std::bad_alloc) - { - RI_DELETE(m_imageManager); - RI_DELETE(m_pathManager); - RI_DELETE(m_paintManager); - RI_DELETE(m_fontManager); - RI_DELETE(m_maskLayerManager); - - throw; - } - } - RI_ASSERT(m_imageManager); - RI_ASSERT(m_pathManager); - RI_ASSERT(m_paintManager); - RI_ASSERT(m_fontManager); - RI_ASSERT(m_maskLayerManager); - - m_imageManager->addReference(); - m_pathManager->addReference(); - m_paintManager->addReference(); - m_fontManager->addReference(); - m_maskLayerManager->addReference(); - - m_inputColorTransformValues[0] = 1.0f; - m_inputColorTransformValues[1] = 1.0f; - m_inputColorTransformValues[2] = 1.0f; - m_inputColorTransformValues[3] = 1.0f; - m_inputColorTransformValues[4] = 0.0f; - m_inputColorTransformValues[5] = 0.0f; - m_inputColorTransformValues[6] = 0.0f; - m_inputColorTransformValues[7] = 0.0f; - m_colorTransformValues[0] = 1.0f; - m_colorTransformValues[1] = 1.0f; - m_colorTransformValues[2] = 1.0f; - m_colorTransformValues[3] = 1.0f; - m_colorTransformValues[4] = 0.0f; - m_colorTransformValues[5] = 0.0f; - m_colorTransformValues[6] = 0.0f; - m_colorTransformValues[7] = 0.0f; - -} - -/*-------------------------------------------------------------------*//*! -* \brief VGContext destructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGContext::~VGContext() -{ - releasePaint(VG_FILL_PATH | VG_STROKE_PATH); - setDefaultDrawable(NULL); - - //destroy own images, paths and paints - while(Image* i = m_imageManager->getFirstResource(this)) - m_imageManager->removeResource(i); - while(Path* p = m_pathManager->getFirstResource(this)) - m_pathManager->removeResource(p); - while(Paint* t = m_paintManager->getFirstResource(this)) - m_paintManager->removeResource(t); - while(Font* t = m_fontManager->getFirstResource(this)) - m_fontManager->removeResource(t); - while(Surface* t = m_maskLayerManager->getFirstResource(this)) - m_maskLayerManager->removeResource(t); - - //decrease the reference count of resource managers - if(!m_imageManager->removeReference()) - RI_DELETE(m_imageManager); - if(!m_pathManager->removeReference()) - RI_DELETE(m_pathManager); - if(!m_paintManager->removeReference()) - RI_DELETE(m_paintManager); - if(!m_fontManager->removeReference()) - RI_DELETE(m_fontManager); - if(!m_maskLayerManager->removeReference()) - RI_DELETE(m_maskLayerManager); -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets new default drawable. -* \param drawable New drawable or NULL when context is unbound -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void VGContext::setDefaultDrawable(Drawable* drawable) -{ - if(m_eglDrawable) - { - if(!m_eglDrawable->removeReference()) - RI_DELETE(m_eglDrawable); - } - m_eglDrawable = drawable; - if(m_eglDrawable) - { - m_eglDrawable->addReference(); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns true if the given image is generated through any -* context that is shared with this one. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool VGContext::isValidImage(VGImage image) -{ - return m_imageManager->isValid((Image*)image); -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns true if the given path is generated through any -* context that is shared with this one. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool VGContext::isValidPath(VGPath path) -{ - return m_pathManager->isValid((Path*)path); -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns true if the given paint is generated through any -* context that is shared with this one. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool VGContext::isValidPaint(VGPaint paint) -{ - return m_paintManager->isValid((Paint*)paint); -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns true if the given font is generated through any -* context that is shared with this one. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool VGContext::isValidFont(VGFont font) -{ - return m_fontManager->isValid((Font*)font); -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns true if the given mask layer is generated through any -* context that is shared with this one. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool VGContext::isValidMaskLayer(VGMaskLayer layer) -{ - return m_maskLayerManager->isValid((Surface*)layer); -} - -/*-------------------------------------------------------------------*//*! -* \brief Releases the given paint objects of the context. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void VGContext::releasePaint(VGbitfield paintModes) -{ - if(paintModes & VG_FILL_PATH) - { - //release previous paint - Paint* prev = (Paint*)m_fillPaint; - if(prev) - { - if(!prev->removeReference()) - RI_DELETE(prev); - } - m_fillPaint = VG_INVALID_HANDLE; - } - if(paintModes & VG_STROKE_PATH) - { - //release previous paint - Paint* prev = (Paint*)m_strokePaint; - if(prev) - { - if(!prev->removeReference()) - RI_DELETE(prev); - } - m_strokePaint = VG_INVALID_HANDLE; - } -} - -//============================================================================================== - -} //namespace OpenVGRI diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riContext.h --- a/hostsupport/hostopenvg/src/src/riContext.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,290 +0,0 @@ -#ifndef __RICONTEXT_H -#define __RICONTEXT_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief VGContext class. Used for storing OpenVG state. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef OPENVG_H -#include "openvg.h" -#endif - -#ifndef __RIDEFS_H -#include "riDefs.h" -#endif - -#ifndef __RIMATH_H -#include "riMath.h" -#endif - -#ifndef __RIIMAGE_H -#include "riImage.h" -#endif - -#ifndef __RIPATH_H -#include "riPath.h" -#endif - -#ifndef __RIFONT_H -#include "riFont.h" -#endif - -#ifndef __RIARRAY_H -#include "riArray.h" -#endif - -#ifndef __SFDYNAMICBLITTER_H -# include "sfDynamicBlitter.h" -#endif - -//============================================================================================== - -namespace OpenVGRI -{ - -class VGContext; - -/*-------------------------------------------------------------------*//*! -* \brief A list of resources (Images, Paths, or Paints) shared by a -* set of contexts. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -template class 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; -}; - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class VGContext -{ -public: - VGContext(VGContext* shareContext); //throws bad_alloc - ~VGContext(); - - void setDefaultDrawable(Drawable* drawable); //called from EGL - Drawable* getCurrentDrawable() { return m_eglDrawable; } - DynamicBlitter& getBlitter() { return m_blitter; } - - bool isValidImage(VGImage image); - bool isValidPath(VGPath path); - bool isValidPaint(VGPaint paint); - bool isValidFont(VGFont font); - bool isValidMaskLayer(VGMaskLayer layer); - - void releasePaint(VGbitfield paintModes); - - void setError(VGErrorCode error) { if(m_error == VG_NO_ERROR) m_error = error; } - - // Mode settings - VGMatrixMode m_matrixMode; - VGFillRule m_fillRule; - VGImageQuality m_imageQuality; - VGRenderingQuality m_renderingQuality; - VGBlendMode m_blendMode; - VGImageMode m_imageMode; - - // Scissor rectangles - Array m_scissor; - - // Stroke parameters - RIfloat m_strokeLineWidth; - RIfloat m_inputStrokeLineWidth; - VGCapStyle m_strokeCapStyle; - VGJoinStyle m_strokeJoinStyle; - RIfloat m_strokeMiterLimit; - RIfloat m_inputStrokeMiterLimit; - Array m_strokeDashPattern; - Array m_inputStrokeDashPattern; - RIfloat m_strokeDashPhase; - RIfloat m_inputStrokeDashPhase; - VGboolean m_strokeDashPhaseReset; - - // Edge fill color for vgConvolve and pattern paint - Color m_tileFillColor; - Color m_inputTileFillColor; - - // Color for vgClear - Color m_clearColor; - Color m_inputClearColor; - - Vector2 m_glyphOrigin; - Vector2 m_inputGlyphOrigin; - - VGboolean m_masking; - VGboolean m_scissoring; - - VGPixelLayout m_pixelLayout; - - VGboolean m_filterFormatLinear; - VGboolean m_filterFormatPremultiplied; - VGbitfield m_filterChannelMask; - - // Matrices - Matrix3x3 m_pathUserToSurface; - Matrix3x3 m_imageUserToSurface; - Matrix3x3 m_glyphUserToSurface; - Matrix3x3 m_fillPaintToUser; - Matrix3x3 m_strokePaintToUser; - - VGPaint m_fillPaint; - VGPaint m_strokePaint; - - VGboolean m_colorTransform; - RIfloat m_colorTransformValues[8]; - RIuint32 m_iColorTransformValues[8]; - RIfloat m_inputColorTransformValues[8]; - - VGErrorCode m_error; - - ResourceManager* m_imageManager; - ResourceManager* m_pathManager; - ResourceManager* m_paintManager; - ResourceManager* m_fontManager; - ResourceManager* m_maskLayerManager; - - Rasterizer m_rasterizer; - - PixelPipe m_pixelPipe; - DynamicBlitter m_blitter; - -private: - Drawable* m_eglDrawable; - - VGContext(const VGContext&); //!< Not allowed. - void operator=(const VGContext&); //!< Not allowed. -}; - -//============================================================================================== - -} //namespace OpenVGRI - -//============================================================================================== - -#endif /* __RICONTEXT_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riDefs.h --- a/hostsupport/hostopenvg/src/src/riDefs.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,206 +0,0 @@ -#ifndef __RIDEFS_H -#define __RIDEFS_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Platform- and compiler-dependent type and macro definitions. - * \note - *//*-------------------------------------------------------------------*/ - -#include -#include -#include -#include //for bad_alloc - -#if defined(_WIN32) && defined(_DEBUG) -# define WIN32_LEAN_AND_MEAN -# include -#endif - -//make for-clause scope c++ standard compliant on msvc -#if defined (_MSC_VER) -# if !defined (for) - __forceinline bool getFalse (void) { return false; } -# define for if(getFalse()); else for -# endif // for - -#pragma warning(disable:4710) //disable function not inlined warning -#pragma warning(disable:4714) //disable function not __forceinlined warning -#endif // _MSC_VER - -namespace OpenVGRI -{ - -//======================================================================= - -typedef long long RIint64; -typedef unsigned long long RIuint64; -typedef int RIint32; -typedef unsigned int RIuint32; -typedef short RIint16; -typedef unsigned short RIuint16; -typedef signed char RIint8; -typedef unsigned char RIuint8; -typedef float RIfloat32; -//TODO add compile-time assertions to guarantee the sizes - -#if defined (_MSC_VER) // MSVC WIN32 -# define RI_INLINE __forceinline -#elif defined __APPLE__ || defined (__GNUC__) || defined (__GCC32__) -# define RI_INLINE inline -#endif - -/*!< Unsigned int that can hold a pointer to any type */ -/*!< Signed int that can hold a pointer to any type */ -#if defined (_MSC_VER) && (_MSC_VER >= 1300) -typedef uintptr_t RIuintptr; -typedef intptr_t RIintptr; -#else -typedef unsigned long RIuintptr; -typedef signed long RIintptr; -#endif - -#define RI_UINT32_MAX (0xffffffffu) -#define RI_INT32_MAX (0x7fffffff) -#define RI_INT32_MIN (-0x7fffffff-1) - -/* maximum mantissa is 23 */ -#define RI_MANTISSA_BITS 23 - -/* maximum exponent is 8 */ -#define RI_EXPONENT_BITS 8 - -typedef union -{ - RIfloat32 f; - RIuint32 i; -} RIfloatInt; - -RI_INLINE float getFloatMax() -{ - RIfloatInt v; - v.i = (((1<<(RI_EXPONENT_BITS-1))-1+127) << 23) | (((1< 0); - RI_ASSERT((n & 0x3) == 0); - - RIuint32 *ptr = (RIuint32*)dst; - for(size_t i = 0; i < (n>>2); i++) - { - *ptr++ = 0; - } -} - -//======================================================================= - -} //namespace OpenVGRI - -#endif /* __RIDEFS_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riEGLOS.h --- a/hostsupport/hostopenvg/src/src/riEGLOS.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,58 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef _RIEGLOS_H -#define _RIEGLOS_H - -#include "EGL/egl.h" -#include "riImage.h" - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - struct OSWindowContext - { - int window; - unsigned int* tmp; - int tmpWidth; - int tmpHeight; - }; - - void* OSGetCurrentThreadID(void); - void OSDeinitMutex(void); - void OSAcquireMutex(void); - void OSReleaseMutex(void); - OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window); - void OSDestroyWindowContext(OSWindowContext* ctx); - bool OSIsWindow(const OSWindowContext* context); - void OSGetWindowSize(const OSWindowContext* ctx, int& width, int& height); - void OSBlitToWindow(OSWindowContext* ctx, const Drawable* drawable); - EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id); -} //namespace OpenVGRI - -#endif diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riFont.cpp --- a/hostsupport/hostopenvg/src/src/riFont.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,203 +0,0 @@ -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementation of Font class. - * \note - *//*-------------------------------------------------------------------*/ - -#include "riFont.h" - -//============================================================================================== - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief Font constructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Font::Font(int capacityHint) : - m_referenceCount(0), - m_glyphs() -{ - RI_ASSERT(capacityHint >= 0); - m_glyphs.reserve(capacityHint); -} - -/*-------------------------------------------------------------------*//*! -* \brief Font destructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Font::~Font() -{ - //remove references to paths and images - for(int i=0;im_path != VG_INVALID_HANDLE) - { - Path* p = (Path*)g->m_path; - if(!p->removeReference()) - RI_DELETE(p); - } - if(g->m_image != VG_INVALID_HANDLE) - { - Image* p = (Image*)g->m_image; - p->removeInUse(); - if(!p->removeReference()) - RI_DELETE(p); - } - Glyph a; - *g = a; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Font::setGlyphToPath(unsigned int index, VGPath path, bool isHinted, const Vector2& origin, const Vector2& escapement) -{ - Glyph* g = findGlyph(index); - if(g) - { //glyph exists, replace - clearGlyph(g); - } - else - { //glyph doesn't exist, allocate a new one - g = newGlyph(); - } - - g->m_index = index; - g->m_state = Glyph::GLYPH_PATH; - g->m_path = path; - g->m_image = VG_INVALID_HANDLE; - g->m_isHinted = isHinted; - g->m_origin = origin; - g->m_escapement = escapement; - - if(path != VG_INVALID_HANDLE) - { - Path* p = (Path*)path; - p->addReference(); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Font::setGlyphToImage(unsigned int index, VGImage image, const Vector2& origin, const Vector2& escapement) -{ - Glyph* g = findGlyph(index); - if(g) - { //glyph exists, replace - clearGlyph(g); - } - else - { //glyph doesn't exist, allocate a new one - g = newGlyph(); - } - - g->m_index = index; - g->m_state = Glyph::GLYPH_IMAGE; - g->m_path = VG_INVALID_HANDLE; - g->m_image = image; - g->m_isHinted = false; - g->m_origin = origin; - g->m_escapement = escapement; - - if(image != VG_INVALID_HANDLE) - { - Image* p = (Image*)image; - p->addReference(); - p->addInUse(); - } -} - -//======================================================================= - -} //namespace OpenVGRI diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riFont.h --- a/hostsupport/hostopenvg/src/src/riFont.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,116 +0,0 @@ -#ifndef __RIFONT_H -#define __RIFONT_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief VGContext class. Used for storing OpenVG state. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef _OPENVG_H -#include "openvg.h" -#endif - -#ifndef __RIMATH_H -#include "riMath.h" -#endif - -#ifndef __RIARRAY_H -#include "riArray.h" -#endif - -#ifndef __RIPATH_H -#include "riPath.h" -#endif - -#ifndef __RIIMAGE_H -#include "riImage.h" -#endif - -//============================================================================================== - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief Storage and operations for VGFont. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class Font -{ -public: - struct Glyph - { - enum State - { - GLYPH_UNINITIALIZED = 0, - GLYPH_PATH = 1, - GLYPH_IMAGE = 2 - }; - Glyph() { m_state = GLYPH_UNINITIALIZED; m_path = m_image = VG_INVALID_HANDLE; m_isHinted = false; m_origin.set(0.0f, 0.0f); m_escapement.set(0.0f, 0.0f); } - unsigned int m_index; - State m_state; - VGPath m_path; - VGImage m_image; - bool m_isHinted; - Vector2 m_origin; - Vector2 m_escapement; - }; - - Font(int capacityHint); //throws bad_alloc - ~Font(); - - int getNumGlyphs() const { int n=0; for(int i=0;i= 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 m_glyphs; -}; - -//======================================================================= - -} //namespace OpenVGRI - -//======================================================================= - -#endif /* __RIFONT_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riImage.cpp --- a/hostsupport/hostopenvg/src/src/riImage.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,2835 +0,0 @@ -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementation of Color and Image functions. - * \note - *//*-------------------------------------------------------------------*/ - -#include "riImage.h" -#include "riRasterizer.h" -#include "riContext.h" - -#ifndef __SFDYNAMICBLITTER_H -# include "sfDynamicBlitter.h" -#endif - -//============================================================================================== - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief Converts from numBits into a shifted mask -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static RI_INLINE unsigned int bitsToMask(unsigned int bits, unsigned int shift) -{ - return ((1<= 0) ? (int)x : (int)(x-1); -} - -//static const float FLOAT_0 = 0.0f; -static const float FLOAT_0_5 = 0.5f; - -/* \note Rewrite this if time. */ -static unsigned int colorToInt(RIfloat c, int maxc) -{ -#if defined RI_USE_SSE - /* - Registers mapping: - c <-> xmm0, - maxc <-> xmm1 - 0 <-> xmm2 - */ - _asm - { - xorps xmm2, xmm2 ; xmm2 = 0 - - ;--------------------------------------------- - ; Computing: xmm0 = (c * (RIfloat)maxc + 0.5f) - ;--------------------------------------------- - movss xmm0, dword ptr [c] ; xmm0 = c - cvtsi2ss xmm1, dword ptr [maxc] ; xmm1 = (float)maxc - mulss xmm0, xmm1 ; xmm0 = xmm0 * xmm1 = c * (float)maxc - addss xmm0, FLOAT_0_5 ; xmm0 = xmm0 + 0.5f = c * (float)maxc + 0.5f - - ;--------------------------------------------- - ; Computing: xmm0 = floor(xmm0) = floor(c * (RIfloat)maxc + 0.5f) - ;--------------------------------------------- - cvttss2si ebx, xmm0 ; ebx = (int)xmm0 - mov eax, ebx ; eax = ebx = (int)xmm0 - shr eax, 31 ; eax = sign(eax) = sign((int)xmm0) - sub ebx, eax ; ebx = ebx - sign((int)xmm0) = (int)xmm0 - sign((int)xmm0) = (int)floor((int)xmm0) - cvtsi2ss xmm0, ebx ; xmm0 = floor(xmm0) - - pmaxsw xmm0, xmm2; ; xmm0 = MAX(xmm0, 0) - pminsw xmm0, xmm1 ; xmm0 = MIN(xmm0, maxc) - cvttss2si eax, xmm0 ; return value = eax = (int)xmm0 - } -#else - return RI_INT_MIN(RI_INT_MAX((int)ffloor(c * (RIfloat)maxc + 0.5f), 0), maxc); -#endif -} - -/*-------------------------------------------------------------------*//*! -* \brief Converts from int to color (RIfloat) with the given maximum -* mapped to 1.0f. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static RI_INLINE RIfloat intToColor(unsigned int i, unsigned int maxi) -{ - return (RIfloat)(i & maxi) / (RIfloat)maxi; -} - -void Color::Descriptor::toSmallDescriptor(Color::SmallDescriptor& smallDesc) const -{ - switch (bitsPerPixel) - { - case 32: - smallDesc.size = SIZE_32; - break; - case 24: - smallDesc.size = SIZE_24; - break; - case 16: - smallDesc.size = SIZE_16; - break; - case 8: - smallDesc.size = SIZE_8; - break; - case 4: - smallDesc.size = SIZE_4; - break; - default: - RI_ASSERT(bitsPerPixel == 1); - smallDesc.size = SIZE_1; - break; - } - smallDesc.shape = shape; - smallDesc.internalFormat = internalFormat; -} - -Color::Descriptor Color::Descriptor::getDummyDescriptor() -{ - static const Descriptor dummy = Color::Descriptor(8,0,8,8,8,16,8,24,0,0,sRGBA,32,SHAPE_ABGR); - return dummy; -} - -/** - * \brief Determine the shape of the color format from other data. - * \todo The naming is poor because it may be interpreted as returning the member - * "shape". - */ -Color::Shape Color::Descriptor::getShape() const -{ - // \todo There should be some easier way to define the shape so that it does - // not need to be determined with so many conditions. - - if (isAlphaOnly()) - { - return SHAPE_A; - } - else if (isLuminance()) - { - if (alphaBits) - { - if (alphaShift == 0) - return SHAPE_LA; - return SHAPE_AL; - } - return SHAPE_L; - } - else if (!alphaBits) - { - if (bitsPerPixel == 32) - { - switch(redShift) - { - case 0: - return SHAPE_XBGR; - case 8: - return SHAPE_BGRX; - case 16: - return SHAPE_XRGB; - default: - RI_ASSERT(redShift == 24); - return SHAPE_RGBX; - } - } else if (bitsPerPixel == 24) - { - if (!redShift) - return SHAPE_BGR; - else - { - RI_ASSERT(redShift == 16); - return SHAPE_RGB; - } - } else - { - RI_ASSERT(redBits == 5 && greenBits == 6 && blueBits == 5); - if(redShift) - return SHAPE_RGB; - else - return SHAPE_BGR; - } - } - else - { - if (bitsPerPixel == 32) - { - switch(redShift) - { - case 0: - return SHAPE_ABGR; - case 8: - return SHAPE_BGRA; - case 16: - return SHAPE_ARGB; - default: - RI_ASSERT(redShift == 24); - return SHAPE_RGBA; - } - } else - { - RI_ASSERT(bitsPerPixel == 16); - if (redBits == 5) - { - RI_ASSERT(greenBits == 5 && blueBits == 5 && alphaBits == 1); - switch(redShift) - { - case 0: - return SHAPE_ABGR; - case 1: - return SHAPE_BGRA; - case 10: - return SHAPE_ARGB; - default: - RI_ASSERT(redShift == 11); - return SHAPE_RGBA; - } - } else - { - RI_ASSERT(redBits == 4 && greenBits == 4 && alphaBits == 4); - switch(redShift) - { - case 0: - return SHAPE_ABGR; - case 4: - return SHAPE_BGRA; - case 8: - return SHAPE_ARGB; - default: - RI_ASSERT(redShift == 12); - return SHAPE_RGBA; - } - } - } - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Converts from packed integer in a given format to a Color. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Color::unpack(unsigned int inputData, const Color::Descriptor& inputDesc) -{ - int rb = inputDesc.redBits; - int gb = inputDesc.greenBits; - int bb = inputDesc.blueBits; - int ab = inputDesc.alphaBits; - int lb = inputDesc.luminanceBits; - int rs = inputDesc.redShift; - int gs = inputDesc.greenShift; - int bs = inputDesc.blueShift; - int as = inputDesc.alphaShift; - int ls = inputDesc.luminanceShift; - - m_format = inputDesc.internalFormat; - if(lb) - { //luminance - r = g = b = intToColor(inputData >> ls, (1<> rs, (1<> gs, (1<> bs, (1<> as, (1<= 0 && baseFormat < numBaseFormats); - int swizzleBits = ((int)format >> 6) & 3; - - /* base formats - VG_sRGBX_8888 = 0, - VG_sRGBA_8888 = 1, - VG_sRGBA_8888_PRE = 2, - VG_sRGB_565 = 3, - VG_sRGBA_5551 = 4, - VG_sRGBA_4444 = 5, - VG_sL_8 = 6, - VG_lRGBX_8888 = 7, - VG_lRGBA_8888 = 8, - VG_lRGBA_8888_PRE = 9, - VG_lL_8 = 10, - VG_A_8 = 11, - VG_BW_1 = 12, - VG_A_1 = 13, - VG_A_4 = 14, - */ - - static const int redBits[numBaseFormats] = {8, 8, 8, 5, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0}; - static const int greenBits[numBaseFormats] = {8, 8, 8, 6, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0}; - static const int blueBits[numBaseFormats] = {8, 8, 8, 5, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0}; - static const int alphaBits[numBaseFormats] = {0, 8, 8, 0, 1, 4, 0, 0, 8, 8, 0, 8, 0, 1, 4}; - static const int luminanceBits[numBaseFormats] = {0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 1, 0, 0}; - - static const int redShifts[4*numBaseFormats] = {24, 24, 24, 11, 11, 12, 0, 24, 24, 24, 0, 0, 0, 0, 0, //RGBA - 16, 16, 16, 11, 10, 8, 0, 16, 16, 16, 0, 0, 0, 0, 0, //ARGB - 8, 8, 8, 0, 1, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0, //BGRA - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //ABGR - - static const int greenShifts[4*numBaseFormats] = {16, 16, 16, 5, 6, 8, 0, 16, 16, 16, 0, 0, 0, 0, 0, //RGBA - 8, 8, 8, 5, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0, //ARGB - 16, 16, 16, 5, 6, 8, 0, 16, 16, 16, 0, 0, 0, 0, 0, //BGRA - 8, 8, 8, 5, 5, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0};//ABGR - - static const int blueShifts[4*numBaseFormats] = {8, 8, 8, 0, 1, 4, 0, 8, 8, 8, 0, 0, 0, 0, 0, //RGBA - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //ARGB - 24, 24, 24, 11, 11, 12, 0, 24, 24, 24, 0, 0, 0, 0, 0, //BGRA - 16, 16, 16, 11, 10, 8, 0, 16, 16, 16, 0, 0, 0, 0, 0};//ABGR - - static const int alphaShifts[4*numBaseFormats] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //RGBA - 0, 24, 24, 0, 15, 12, 0, 0, 24, 24, 0, 0, 0, 0, 0, //ARGB - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //BGRA - 0, 24, 24, 0, 15, 12, 0, 0, 24, 24, 0, 0, 0, 0, 0};//ABGR - - static const int bpps[numBaseFormats] = {32, 32, 32, 16, 16, 16, 8, 32, 32, 32, 8, 8, 1, 1, 4}; - - static const InternalFormat internalFormats[numBaseFormats] = {sRGBA, sRGBA, sRGBA_PRE, sRGBA, sRGBA, sRGBA, sLA, lRGBA, lRGBA, lRGBA_PRE, lLA, lRGBA, lLA, lRGBA, lRGBA}; - - desc.redBits = redBits[baseFormat]; - desc.greenBits = greenBits[baseFormat]; - desc.blueBits = blueBits[baseFormat]; - desc.alphaBits = alphaBits[baseFormat]; - desc.luminanceBits = luminanceBits[baseFormat]; - - desc.redShift = redShifts[swizzleBits * numBaseFormats + baseFormat]; - desc.greenShift = greenShifts[swizzleBits * numBaseFormats + baseFormat]; - desc.blueShift = blueShifts[swizzleBits * numBaseFormats + baseFormat]; - desc.alphaShift = alphaShifts[swizzleBits * numBaseFormats + baseFormat]; - desc.luminanceShift = 0; //always zero - - desc.vgFormat = format; - desc.bitsPerPixel = bpps[baseFormat]; - desc.bytesPerPixel = desc.bitsPerPixel / 8; - desc.internalFormat = internalFormats[baseFormat]; - desc.shape = desc.getShape(); - - if (desc.alphaBits) - { - desc.maskBits = desc.alphaBits; - desc.maskShift = desc.alphaShift; - } - else if (!desc.isLuminance()) - { - desc.maskBits = desc.redBits; - desc.maskShift = desc.redShift; - } - else - { - desc.maskBits = desc.luminanceBits; - desc.maskShift = desc.luminanceShift; - } - - return desc; -} - - -struct DescToFormatMapping -{ - Color::Descriptor desc; - VGImageFormat format; -}; - -RI_INLINE static bool isDescEqualToMapping(const Color::Descriptor& desc, const DescToFormatMapping &mapping) -{ - if ((desc.redBits == mapping.desc.redBits) && - (desc.redShift == mapping.desc.redShift) && - (desc.greenBits == mapping.desc.greenBits) && - (desc.greenShift == mapping.desc.greenShift) && - (desc.blueBits == mapping.desc.blueBits) && - (desc.blueShift == mapping.desc.blueShift) && - (desc.alphaBits == mapping.desc.alphaBits) && - (desc.alphaShift == mapping.desc.alphaShift) && - (desc.luminanceBits == mapping.desc.luminanceBits) && - (desc.luminanceShift == mapping.desc.luminanceShift) && - (desc.internalFormat == mapping.desc.internalFormat) && - (desc.bitsPerPixel == mapping.desc.bitsPerPixel)) - return true; - - return false; -} - -VGImageFormat Color::descriptorToVGImageFormat(const Descriptor& desc) -{ -//Color::Descriptor::Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp) : - // \todo These are hardcoded here only to allow constant initialization, they should be generated - // using formatToDescriptor! - static const DescToFormatMapping map[] = { - /* RGB{A,X} channel ordering */ - { formatToDescriptorConst(VG_sRGBX_8888), VG_sRGBX_8888 }, - { formatToDescriptorConst(VG_sRGBA_8888), VG_sRGBA_8888 }, - { formatToDescriptorConst(VG_sRGBA_8888_PRE), VG_sRGBA_8888_PRE }, - { formatToDescriptorConst(VG_sRGB_565), VG_sRGB_565 }, - { formatToDescriptorConst(VG_sRGBA_5551), VG_sRGBA_5551 }, - { formatToDescriptorConst(VG_sRGBA_4444), VG_sRGBA_4444 }, - { formatToDescriptorConst(VG_sL_8), VG_sL_8 }, - { formatToDescriptorConst(VG_lRGBX_8888), VG_lRGBX_8888 }, - { formatToDescriptorConst(VG_lRGBA_8888), VG_lRGBA_8888 }, - { formatToDescriptorConst(VG_lRGBA_8888_PRE), VG_lRGBA_8888_PRE }, - { formatToDescriptorConst(VG_lL_8), VG_lL_8 }, - { formatToDescriptorConst(VG_A_8), VG_A_8 }, - { formatToDescriptorConst(VG_BW_1), VG_BW_1 }, - { formatToDescriptorConst(VG_A_1), VG_A_1 }, - { formatToDescriptorConst(VG_A_4), VG_A_4 }, - - /* {A,X}RGB channel ordering */ - { formatToDescriptorConst(VG_sXRGB_8888), VG_sXRGB_8888 }, - { formatToDescriptorConst(VG_sARGB_8888), VG_sARGB_8888 }, - { formatToDescriptorConst(VG_sARGB_8888_PRE), VG_sARGB_8888_PRE }, - { formatToDescriptorConst(VG_sARGB_1555), VG_sARGB_1555 }, - { formatToDescriptorConst(VG_sARGB_4444), VG_sARGB_4444 }, - { formatToDescriptorConst(VG_lXRGB_8888), VG_lXRGB_8888 }, - { formatToDescriptorConst(VG_lARGB_8888), VG_lARGB_8888 }, - { formatToDescriptorConst(VG_lARGB_8888_PRE), VG_lARGB_8888_PRE }, - - /* BGR{A,X} channel ordering */ - { formatToDescriptorConst(VG_sBGRX_8888), VG_sBGRX_8888 }, - { formatToDescriptorConst(VG_sBGRA_8888), VG_sBGRA_8888 }, - { formatToDescriptorConst(VG_sBGRA_8888_PRE), VG_sBGRA_8888_PRE }, - { formatToDescriptorConst(VG_sBGR_565), VG_sBGR_565 }, - { formatToDescriptorConst(VG_sBGRA_5551), VG_sBGRA_5551 }, - { formatToDescriptorConst(VG_sBGRA_4444), VG_sBGRA_4444 }, - { formatToDescriptorConst(VG_lBGRX_8888), VG_lBGRX_8888 }, - { formatToDescriptorConst(VG_lBGRA_8888), VG_lBGRA_8888 }, - { formatToDescriptorConst(VG_lBGRA_8888_PRE), VG_lBGRA_8888_PRE }, - - /* {A,X}BGR channel ordering */ - { formatToDescriptorConst(VG_sXBGR_8888), VG_sXBGR_8888 }, - { formatToDescriptorConst(VG_sABGR_8888), VG_sABGR_8888 }, - { formatToDescriptorConst(VG_sABGR_8888_PRE), VG_sABGR_8888_PRE }, - { formatToDescriptorConst(VG_sABGR_1555), VG_sABGR_1555 }, - { formatToDescriptorConst(VG_sABGR_4444), VG_sABGR_4444 }, - { formatToDescriptorConst(VG_lXBGR_8888), VG_lXBGR_8888 }, - { formatToDescriptorConst(VG_lABGR_8888), VG_lABGR_8888 }, - { formatToDescriptorConst(VG_lABGR_8888_PRE), VG_lABGR_8888_PRE }, - }; - - for (size_t i = 0; i < sizeof(map)/sizeof(map[0]); i++) - { - if (isDescEqualToMapping(desc, map[i])) - return map[i].format; - } - RI_ASSERT(false); - return (VGImageFormat)-1; -} - -/*-------------------------------------------------------------------*//*! -* \brief Checks if the pixel format descriptor is valid (i.e. all the -* values are supported by the RI) -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool Color::isValidDescriptor(const Color::Descriptor& desc) -{ - //A valid descriptor has 1, 2, 4, 8, 16, or 32 bits per pixel, and either luminance or rgba channels, but not both. - //Any of the rgba channels can be missing, and not all bits need to be used. Maximum channel bit depth is 8. - int rb = desc.redBits; - int gb = desc.greenBits; - int bb = desc.blueBits; - int ab = desc.alphaBits; - int lb = desc.luminanceBits; - int rs = desc.redShift; - int gs = desc.greenShift; - int bs = desc.blueShift; - int as = desc.alphaShift; - int ls = desc.luminanceShift; - int bpp = desc.bitsPerPixel; - - int rgbaBits = rb + gb + bb + ab; - if(rb < 0 || rb > 8 || rs < 0 || rs + rb > bpp || !(rb || !rs)) - return false; //invalid channel description - if(gb < 0 || gb > 8 || gs < 0 || gs + gb > bpp || !(gb || !gs)) - return false; //invalid channel description - if(bb < 0 || bb > 8 || bs < 0 || bs + bb > bpp || !(bb || !bs)) - return false; //invalid channel description - if(ab < 0 || ab > 8 || as < 0 || as + ab > bpp || !(ab || !as)) - return false; //invalid channel description - if(lb < 0 || lb > 8 || ls < 0 || ls + lb > bpp || !(lb || !ls)) - return false; //invalid channel description - -#if 0 - if(rgbaBits && lb) - return false; //can't have both rgba and luminance -#endif - if(!rgbaBits && !lb) - return false; //must have either rgba or luminance - if(rgbaBits) - { //rgba - if(rb+gb+bb == 0) - { //alpha only - if(rs || gs || bs || as || ls) - return false; //wrong shifts (even alpha shift must be zero) - if((ab != 1 && ab != 2 && ab != 4 && ab != 8) || bpp != ab) - return false; //alpha size must be 1, 2, 4, or, 8, bpp must match - } - else - { //rgba - if(rgbaBits > bpp) - return false; //bpp must be greater than or equal to the sum of rgba bits - if(!(bpp == 32 || bpp == 16 || bpp == 8)) - return false; //only 1, 2, and 4 byte formats are supported for rgba - - unsigned int rm = bitsToMask((unsigned int)rb, (unsigned int)rs); - unsigned int gm = bitsToMask((unsigned int)gb, (unsigned int)gs); - unsigned int bm = bitsToMask((unsigned int)bb, (unsigned int)bs); - unsigned int am = bitsToMask((unsigned int)ab, (unsigned int)as); - if((rm & gm) || (rm & bm) || (rm & am) || (gm & bm) || (gm & am) || (bm & am)) - return false; //channels overlap - } - } - else - { //luminance - if(rs || gs || bs || as || ls) - return false; //wrong shifts (even luminance shift must be zero) - if(!(lb == 1 || lb == 8) || bpp != lb) - return false; //luminance size must be either 1 or 8, bpp must match - } - - if(desc.vgFormat != -1) - { - if(!isValidImageFormat(desc.vgFormat)) - return false; //invalid image format - - Descriptor d = formatToDescriptor(desc.vgFormat); - if(d.redBits != rb || d.greenBits != gb || d.blueBits != bb || d.alphaBits != ab || d.luminanceBits != lb || - d.redShift != rs || d.greenShift != gs || d.blueShift != bs || d.alphaShift != as || d.luminanceShift != ls || - d.bitsPerPixel != bpp) - return false; //if the descriptor has a VGImageFormat, it must match the bits, shifts, and bpp - } - - if((unsigned int)desc.internalFormat & ~(Color::PREMULTIPLIED | Color::NONLINEAR | Color::LUMINANCE)) - return false; //invalid internal format - - return true; -} - -//============================================================================================== - -//============================================================================================== - -IntegerColor::IntegerColor(const Color& color) -{ - r = (RIuint32)(color.r * 255.0f + 0.5f); - g = (RIuint32)(color.g * 255.0f + 0.5f); - b = (RIuint32)(color.b * 255.0f + 0.5f); - a = (RIuint32)(color.a * 255.0f + 0.5f); -} - -//============================================================================================== - -//============================================================================================== - -/*-------------------------------------------------------------------*//*! -* \brief Constructs a blank image. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Image::Image(const Color::Descriptor& desc, int width, int height, VGbitfield allowedQuality) : - m_desc(desc), - m_width(width), - m_height(height), - m_allowedQuality(allowedQuality), - m_inUse(0), - m_stride(0), - m_data(NULL), - m_referenceCount(0), - m_ownsData(true), - m_parent(NULL), - m_storageOffsetX(0), - m_storageOffsetY(0), - m_unsafeData(false) -{ - RI_ASSERT(Color::isValidDescriptor(m_desc)); - RI_ASSERT(width > 0 && height > 0); - - m_stride = (m_width*m_desc.bitsPerPixel+7)/8; - - m_data = RI_NEW_ARRAY(RIuint8, m_stride*m_height); //throws bad_alloc - memset(m_data, 0, m_stride*m_height); //clear image -} - -/*-------------------------------------------------------------------*//*! -* \brief Constructs an image that uses an external array for its data -* storage. -* \param -* \return -* \note This is meant for internal use to make blitting easier -* \note Now this is "tagged" into m_unsafeData if necessary. -* Using this constructor may then affect performance. -*//*-------------------------------------------------------------------*/ - -Image::Image(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data) : - m_desc(desc), - m_width(width), - m_height(height), - m_allowedQuality(0), - m_inUse(0), - m_stride(stride), - m_data(data), - m_referenceCount(0), - m_ownsData(false), - m_parent(NULL), - m_storageOffsetX(0), - m_storageOffsetY(0), - m_unsafeData(false) -{ - RI_ASSERT(Color::isValidDescriptor(m_desc)); - RI_ASSERT(width > 0 && height > 0); - RI_ASSERT(data); - setUnsafe(true); // External data always potentially unsafe, see note above. -} - -/*-------------------------------------------------------------------*//*! -* \brief Construcs a child image. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Image::Image(Image* parent, int x, int y, int width, int height) : - m_desc(Color::formatToDescriptor(VG_sRGBA_8888)), //dummy initialization, will be overwritten below (can't read from parent->m_desc before knowing the pointer is valid) - m_width(width), - m_height(height), - m_allowedQuality(0), - m_inUse(0), - m_stride(0), - m_data(NULL), - m_referenceCount(0), - m_ownsData(false), - m_parent(parent), - m_storageOffsetX(0), - m_storageOffsetY(0), - m_unsafeData(false) -{ - RI_ASSERT(parent); - RI_ASSERT(x >= 0 && y >= 0 && width > 0 && height > 0); - RI_ASSERT(RI_INT_ADDSATURATE(x,width) <= parent->m_width && RI_INT_ADDSATURATE(y,height) <= parent->m_height); //child image must be contained in parent - - m_desc = parent->m_desc; - RI_ASSERT(Color::isValidDescriptor(m_desc)); - m_allowedQuality = parent->m_allowedQuality; - m_stride = parent->m_stride; - m_data = parent->m_data; - m_storageOffsetX = parent->m_storageOffsetX + x; - m_storageOffsetY = parent->m_storageOffsetY + y; - - //increase the reference and use count of the parent - addInUse(); - parent->addInUse(); - parent->addReference(); - m_unsafeData = parent->m_unsafeData; -} - -/*-------------------------------------------------------------------*//*! -* \brief Image destructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Image::~Image() -{ - RI_ASSERT(m_referenceCount == 0); - - if(m_parent) - { - //decrease the reference and use count of the parent - removeInUse(); - m_parent->removeInUse(); - if(!m_parent->removeReference()) - RI_DELETE(m_parent); - } - RI_ASSERT(m_inUse == 0); - - - if(m_ownsData) - { - RI_ASSERT(!m_parent); //can't have parent if owns the data - RI_DELETE_ARRAY(m_data); //delete image data if we own it - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns true if the two images share pixels. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool Image::overlaps(const Image* src) const -{ - RI_ASSERT(src); - - if(m_data != src->m_data) - return false; //images don't share data - - //check if the image storage regions overlap - Rectangle r(m_storageOffsetX, m_storageOffsetY, m_width, m_height); - r.intersect(Rectangle(src->m_storageOffsetX, src->m_storageOffsetY, src->m_width, src->m_height)); - if(!r.width || !r.height) - return false; //intersection is empty, images don't overlap - - return true; -} - -/** - * \brief Expand log2 bpp packed pixel (single value) to 8 bits. This will - * Result in 8, 4, or 2 same pixel values to be packed into the return value. - */ -RI_INLINE static RIuint32 logExpand8(RIuint32 packedColor, int srcBits) -{ - RI_ASSERT(srcBits == 4 || srcBits == 2 || srcBits == 1); - RIuint32 ret = packedColor; - int n = srcBits; - while (n < 8) - { - ret |= ret << n; - n += n; - } - return ret; -} - -RI_INLINE void Image::fillPacked(RIuint32 packedColor) -{ - RIuint32 pc = packedColor; - int Bpp = m_desc.bitsPerPixel / 8; - int nSetsPerScanline = m_width; - - RI_ASSERT(nSetsPerScanline); - // \todo 1bpp and 4bpp mask formats must be supported. fillPackedPixels should - // automatically work, but riMemSet32 path needs a bit more logic. - // \note < 8bpp formats are always rounded to 8-bit boundaries at scanline end. - // It is assumed that the "padding bits" may be filled. - - if (m_desc.bitsPerPixel < 8) - { - pc = logExpand8(packedColor, m_desc.bitsPerPixel); - Bpp = 1; - nSetsPerScanline = (m_width * m_desc.bitsPerPixel + 7) / 8; - //nSetsPerScanline /= (8/m_desc.bitsPerPixel); - } - - RI_ASSERT(Bpp <= 4 && Bpp >= 1); - - if (m_stride == ((m_desc.bitsPerPixel*m_width+7)/8)) - { - const int nPixels = nSetsPerScanline * m_height; - riMemSet32(m_data, pc, nPixels, Bpp); - } else - { - RIuint8 *ptr = (RIuint8*)m_data; - // set per-scanline - for (int y = 0; y < m_height; y++) - { - riMemSet32(ptr, pc, nSetsPerScanline, Bpp); - ptr += m_stride; - } - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Clears a rectangular portion of an image with the given clear color. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Image::clear(const Color& clearColor, int x, int y, int w, int h) -{ - RI_ASSERT(m_data); - RI_ASSERT(m_referenceCount > 0); - - - //intersect clear region with image bounds - Rectangle r(0,0,m_width,m_height); - r.intersect(Rectangle(x,y,w,h)); - if(!r.width || !r.height) - return; //intersection is empty or one of the rectangles is invalid - - Color col = clearColor; - col.clamp(); - col.convert(getDescriptor().internalFormat); - - IntegerColor ic = IntegerColor(col); - ic.truncateColor(getDescriptor()); - const RIuint32 c = ic.getPackedColor(getDescriptor()); - - if (r.width == getWidth() && r.height == getHeight() && !m_parent) - fillPacked(c); - else - { - fillPackedRectangle(r.x, r.y, r.width, r.height, c); - } -} - -#if 0 -static RIfloat ditherChannel(RIfloat c, int bits, RIfloat m) -{ - RIfloat fc = c * (RIfloat)((1< m) ic += 1.0f; - return RI_MIN(ic / (RIfloat)((1< 0 && h > 0); - sx = RI_INT_MIN(RI_INT_MAX(sx, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2)); - sy = RI_INT_MIN(RI_INT_MAX(sy, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2)); - dx = RI_INT_MIN(RI_INT_MAX(dx, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2)); - dy = RI_INT_MIN(RI_INT_MAX(dy, (int)(RI_INT32_MIN>>2)), (int)(RI_INT32_MAX>>2)); - w = RI_INT_MIN(w, (int)(RI_INT32_MAX>>2)); - h = RI_INT_MIN(h, (int)(RI_INT32_MAX>>2)); - int srcsx = sx, srcex = sx + w, dstsx = dx, dstex = dx + w; - if(srcsx < 0) - { - dstsx -= srcsx; - srcsx = 0; - } - if(srcex > srcWidth) - { - dstex -= srcex - srcWidth; - srcex = srcWidth; - } - if(dstsx < 0) - { - srcsx -= dstsx; - dstsx = 0; - } - if(dstex > dstWidth) - { - srcex -= dstex - dstWidth; - dstex = dstWidth; - } - RI_ASSERT(srcsx >= 0 && dstsx >= 0 && srcex <= srcWidth && dstex <= dstWidth); - w = srcex - srcsx; - RI_ASSERT(w == dstex - dstsx); - - int srcsy = sy, srcey = sy + h, dstsy = dy, dstey = dy + h; - if(srcsy < 0) - { - dstsy -= srcsy; - srcsy = 0; - } - if(srcey > srcHeight) - { - dstey -= srcey - srcHeight; - srcey = srcHeight; - } - if(dstsy < 0) - { - srcsy -= dstsy; - dstsy = 0; - } - if(dstey > dstHeight) - { - srcey -= dstey - dstHeight; - dstey = dstHeight; - } - RI_ASSERT(srcsy >= 0 && dstsy >= 0 && srcey <= srcHeight && dstey <= dstHeight); - h = srcey - srcsy; - RI_ASSERT(h == dstey - dstsy); - sx = srcsx; - sy = srcsy; - dx = dstsx; - dy = dstsy; -} - -/*-------------------------------------------------------------------*//*! -* \brief Blits a source region to destination. Source and destination -* can overlap. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -// \todo Extract dithering kernel and put it into the blitter -#if 0 -void Image::blit(VGContext* context, const Image* src, int sx, int sy, int dx, int dy, int w, int h, bool dither) -{ - //img=>img: vgCopyImage - //img=>user: vgGetImageSubData - //user=>img: vgImageSubData - - // \todo Implement dither to blitter. - this->blit(context, src, sx, sy, dx, dy, w, h, NULL, dither); - RI_ASSERT(src.m_data); //source exists - RI_ASSERT(m_data); //destination exists - RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0); - - computeBlitRegion(sx, sy, dx, dy, w, h, src.m_width, src.m_height, m_width, m_height); - if(w <= 0 || h <= 0) - return; //zero area - - Array tmp; - tmp.resize(w*h); //throws bad_alloc - - //copy source region to tmp - for(int j=0;jgetCurrentDrawable(); - if(!drawable) - return false; //no EGL surface is current at the moment - - Image* img = (Image*)image; - //transform image corners into the surface space - Vector3 p0(0, 0, 1); - Vector3 p1(0, (RIfloat)img->getHeight(), 1); - Vector3 p2((RIfloat)img->getWidth(), (RIfloat)img->getHeight(), 1); - Vector3 p3((RIfloat)img->getWidth(), 0, 1); - - p0 = userToSurfaceMatrix * p0; - p1 = userToSurfaceMatrix * p1; - p2 = userToSurfaceMatrix * p2; - p3 = userToSurfaceMatrix * p3; - if(p0.z <= 0.0f || p1.z <= 0.0f || p2.z <= 0.0f || p3.z <= 0.0f) - return false; - - //projection - p0 *= 1.0f/p0.z; - p1 *= 1.0f/p1.z; - p2 *= 1.0f/p2.z; - p3 *= 1.0f/p3.z; - - Rasterizer& rasterizer = context->m_rasterizer; - rasterizer.clear(); - - if(context->m_scissoring) - rasterizer.setScissor(context->m_scissor); //throws bad_alloc - - PixelPipe& pixelPipe = context->m_pixelPipe; - pixelPipe.setTileFillColor(context->m_tileFillColor); - pixelPipe.setPaint((Paint*)context->m_fillPaint); - const bool aa = imageQuality == VG_IMAGE_QUALITY_NONANTIALIASED ? false : true; - rasterizer.setAntiAliasing(aa); - pixelPipe.setImageQuality(imageQuality); - pixelPipe.setBlendMode(blendMode); - pixelPipe.setRenderToMask(false); - pixelPipe.setDrawable(drawable); - pixelPipe.setMask(hasMasking); - pixelPipe.setColorTransform(hasColorTransform, context->m_colorTransformValues); - - Matrix3x3 surfaceToImageMatrix = userToSurfaceMatrix; - Matrix3x3 surfaceToPaintMatrix = userToSurfaceMatrix * context->m_fillPaintToUser; - if(surfaceToImageMatrix.invert() && surfaceToPaintMatrix.invert()) - { - VGImageMode imode = imageMode; - - if(!surfaceToPaintMatrix.isAffine()) - imode = VG_DRAW_IMAGE_NORMAL; //if paint matrix is not affine, always use normal image mode - - surfaceToPaintMatrix[2].set(0,0,1); //force affine - - pixelPipe.setImage(img, imode); - pixelPipe.setSurfaceToPaintMatrix(surfaceToPaintMatrix); - pixelPipe.setSurfaceToImageMatrix(surfaceToImageMatrix); - pixelPipe.prepareSpanUniforms(aa); - rasterizer.setup(0, 0, drawable->getWidth(), drawable->getHeight(), VG_EVEN_ODD, &pixelPipe); - - rasterizer.addEdge(Vector2(p0.x,p0.y), Vector2(p1.x,p1.y)); //throws bad_alloc - rasterizer.addEdge(Vector2(p1.x,p1.y), Vector2(p2.x,p2.y)); //throws bad_alloc - rasterizer.addEdge(Vector2(p2.x,p2.y), Vector2(p3.x,p3.y)); //throws bad_alloc - rasterizer.addEdge(Vector2(p3.x,p3.y), Vector2(p0.x,p0.y)); //throws bad_alloc - - rasterizer.fill(); //throws bad_alloc - } - - return true; -} - -/*-------------------------------------------------------------------*//*! -* \brief Converts from multisampled format to display format. -* \param unsafeInput Data may contain incorrect values (user data) -* \return -* \note May throw std::bad_alloc on cases where blitting within the -* same buffer and overlapping regions (this may change in the -* future). -*//*-------------------------------------------------------------------*/ - -void Image::blit(VGContext* context, const Image* src, - int sx, int sy, int dx, int dy, int w, int h, - Array* scissors, - bool dither) -{ - bool overlap = false; - (void)dither; - DynamicBlitter& blitter = context->getBlitter(); - - //RI_ASSERT(!src->isInUse(this)); - //int isx = sx, isy = sy, idx = dx, idy = dy, iw = w, ih = h; - - computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), m_width, m_height); - - if(w <= 0 || h <= 0) - return; //zero area - - if (this->m_data == src->m_data) - { - // The images may overlap. - int minsx = RI_INT_MIN(sx, dx); - int minsy = RI_INT_MIN(sy, dy); - int maxsx = RI_INT_MAX(sx, dx); - int maxsy = RI_INT_MAX(sy, dy); - - if ((maxsx < (minsx + w)) && (maxsy < (minsy + h))) - { - overlap = true; - } - } - - if (!scissors) - { - // Currently the blitter does not support scissors - if (!overlap) - { - blitter.prepareBlit(this, src, sx+src->m_storageOffsetX, sy+src->m_storageOffsetY, - dx+m_storageOffsetX, dy+m_storageOffsetY, w, h); - blitter.blit(); - } else - { - Image temp(src->getDescriptor(), w, h, VG_IMAGE_QUALITY_NONANTIALIASED); - blitter.prepareBlit(&temp, src, sx+src->m_storageOffsetX, sy+src->m_storageOffsetY, 0, 0, w, h); - blitter.blit(); - blitter.prepareBlit(this, &temp, 0, 0, dx+m_storageOffsetX, dy+m_storageOffsetY, w, h); - blitter.blit(); - } - } else - { - // For the moment, use the generic poly-rasterizer for scissored images. - if (!overlap) - { - // Create a child image - Image blitImage((Image*)src, sx, sy, w, h); - Matrix3x3 tx; - tx.set(1, 0, dx, 0, 1, dy, 0, 0, 1); - - drawImageBody(context, &blitImage, tx, - VG_IMAGE_QUALITY_NONANTIALIASED, - VG_BLEND_SRC, - false, - false, - VG_DRAW_IMAGE_NORMAL); - } else - { - // Create a copy of the source region - Image temp(src->getDescriptor(), w, h, VG_IMAGE_QUALITY_NONANTIALIASED); - blitter.prepareBlit(&temp, src, sx, sy, 0, 0, w, h); - blitter.blit(); - - Image blitImage((Image*)src, sx, sy, w, h); - Matrix3x3 tx; - tx.set(1, 0, dx, 0, 1, dy, 0, 0, 1); - - drawImageBody(context, &blitImage, tx, - VG_IMAGE_QUALITY_NONANTIALIASED, - VG_BLEND_SRC, - false, - false, - VG_DRAW_IMAGE_NORMAL); - } - } - -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns the color at pixel (x,y). -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Color Image::readPixel(int x, int y) const -{ - const RIuint32 p = readPackedPixel(x, y); - - Color c; - c.unpack(p, m_desc); - return c; -} - -/*-------------------------------------------------------------------*//*! -* \brief Writes the color to pixel (x,y). Internal color formats must -* match. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Image::writePixel(int x, int y, const Color& c) -{ - RI_ASSERT(c.getInternalFormat() == m_desc.internalFormat); - - RIuint32 p = c.pack(m_desc); - writePackedPixel(x, y, p); -} - -/*-------------------------------------------------------------------*//*! -* \brief Writes a filtered color to destination surface -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Image::writeFilteredPixel(int i, int j, const Color& color, VGbitfield channelMask) -{ - //section 3.4.4: before color space conversion, premultiplied colors are - //clamped to alpha, and the color is converted to nonpremultiplied format - //section 11.2: how to deal with channel mask - //step 1 - Color f = color; - f.clamp(); //vgColorMatrix and vgLookups can produce colors that exceed alpha or [0,1] range - - //step 2: color space conversion - f.convert((Color::InternalFormat)(m_desc.internalFormat & (Color::NONLINEAR | Color::LUMINANCE))); - - //step 3: read the destination color and convert it to nonpremultiplied - Color d = readPixel(i,j); - d.unpremultiply(); - RI_ASSERT(d.getInternalFormat() == f.getInternalFormat()); - - //step 4: replace the destination channels specified by the channelMask (channelmask is ignored for luminance formats) - if(!m_desc.isLuminance()) - { //rgba format => use channelmask - if(channelMask & VG_RED) - d.r = f.r; - if(channelMask & VG_GREEN) - d.g = f.g; - if(channelMask & VG_BLUE) - d.b = f.b; - if(channelMask & VG_ALPHA) - d.a = f.a; - } - else d = f; - - //step 5: if destination is premultiplied, convert to premultiplied format - if(m_desc.isPremultiplied()) - d.premultiply(); - //write the color to destination - writePixel(i,j,d); -} - -/*-------------------------------------------------------------------*//*! -* \brief Reads the pixel (x,y) and converts it into an alpha mask value. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -RIfloat Image::readMaskPixel(int x, int y) const -{ - RI_ASSERT(m_data); - RI_ASSERT(x >= 0 && x < m_width); - RI_ASSERT(y >= 0 && y < m_height); - RI_ASSERT(m_referenceCount > 0); - - Color c = readPixel(x,y); - if(m_desc.isLuminance()) - { - return c.r; - } - else - { //rgba - if(m_desc.alphaBits) - return c.a; - return c.r; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Writes the alpha mask to pixel (x,y). -* \param -* \return -* \note Overwrites color. -*//*-------------------------------------------------------------------*/ - -void Image::writeMaskPixel(int x, int y, RIfloat m) -{ - RI_ASSERT(m_data); - RI_ASSERT(x >= 0 && x < m_width); - RI_ASSERT(y >= 0 && y < m_height); - RI_ASSERT(m_referenceCount > 0); - - //if luminance or no alpha, red channel will be used, otherwise alpha channel will be used - writePixel(x, y, Color(m,m,m,m,m_desc.internalFormat)); -} - -/*-------------------------------------------------------------------*//*! -* \brief Reads a texel (u,v) at the given mipmap level. Tiling modes and -* color space conversion are applied. Outputs color in premultiplied -* format. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Color Image::readTexel(int u, int v, int level, VGTilingMode tilingMode, const Color& tileFillColor) const -{ - const Image* image = this; - if( level > 0 ) - { - RI_ASSERT(false); - } - RI_ASSERT(image); - - Color p; - if(tilingMode == VG_TILE_FILL) - { - if(u < 0 || v < 0 || u >= image->m_width || v >= image->m_height) - p = tileFillColor; - else - p = image->readPixel(u, v); - } - else if(tilingMode == VG_TILE_PAD) - { - u = RI_INT_MIN(RI_INT_MAX(u,0),image->m_width-1); - v = RI_INT_MIN(RI_INT_MAX(v,0),image->m_height-1); - p = image->readPixel(u, v); - } - else if(tilingMode == VG_TILE_REPEAT) - { - u = RI_INT_MOD(u, image->m_width); - v = RI_INT_MOD(v, image->m_height); - p = image->readPixel(u, v); - } - else - { - RI_ASSERT(tilingMode == VG_TILE_REFLECT); - - u = RI_INT_MOD(u, image->m_width*2); - v = RI_INT_MOD(v, image->m_height*2); - if( u >= image->m_width ) u = image->m_width*2-1 - u; - if( v >= image->m_height ) v = image->m_height*2-1 - v; - p = image->readPixel(u, v); - } - - p.premultiply(); //interpolate in premultiplied format - return p; -} - -/*-------------------------------------------------------------------*//*! -* \brief Maps point (x,y) to an image and returns a filtered, -* premultiplied color value. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Color Image::resample(RIfloat x, RIfloat y, const Matrix3x3& surfaceToImage, VGImageQuality quality, VGTilingMode tilingMode, const Color& tileFillColor) //throws bad_alloc -{ - RI_ASSERT(m_referenceCount > 0); - - VGbitfield aq = getAllowedQuality(); - aq &= (VGbitfield)quality; - - Vector3 uvw(x,y,1.0f); - uvw = surfaceToImage * uvw; - RIfloat oow = 1.0f / uvw.z; - uvw *= oow; - -#if 0 - if(aq & VG_IMAGE_QUALITY_BETTER) - { //EWA on mipmaps - makeMipMaps(); //throws bad_alloc - - Color::InternalFormat procFormat = (Color::InternalFormat)(m_desc.internalFormat | Color::PREMULTIPLIED); - - RIfloat m_pixelFilterRadius = 1.25f; - RIfloat m_resamplingFilterRadius = 1.25f; - - RIfloat Ux = (surfaceToImage[0][0] - uvw.x * surfaceToImage[2][0]) * oow * m_pixelFilterRadius; - RIfloat Vx = (surfaceToImage[1][0] - uvw.y * surfaceToImage[2][0]) * oow * m_pixelFilterRadius; - RIfloat Uy = (surfaceToImage[0][1] - uvw.x * surfaceToImage[2][1]) * oow * m_pixelFilterRadius; - RIfloat Vy = (surfaceToImage[1][1] - uvw.y * surfaceToImage[2][1]) * oow * m_pixelFilterRadius; - RIfloat U0 = uvw.x; - RIfloat V0 = uvw.y; - - //calculate mip level - int level = 0; - RIfloat axis1sq = Ux*Ux + Vx*Vx; - RIfloat axis2sq = Uy*Uy + Vy*Vy; - RIfloat minorAxissq = RI_MIN(axis1sq,axis2sq); - while(minorAxissq > 9.0f && level < m_mipmaps.size()) //half the minor axis must be at least three texels - { - level++; - minorAxissq *= 0.25f; - } - - RIfloat sx = 1.0f; - RIfloat sy = 1.0f; - if(level > 0) - { - sx = (RIfloat)m_mipmaps[level-1]->m_width / (RIfloat)m_width; - sy = (RIfloat)m_mipmaps[level-1]->m_height / (RIfloat)m_height; - } - Ux *= sx; - Vx *= sx; - U0 *= sx; - Uy *= sy; - Vy *= sy; - V0 *= sy; - - //clamp filter size so that filtering doesn't take excessive amount of time (clamping results in aliasing) - RIfloat lim = 100.0f; - axis1sq = Ux*Ux + Vx*Vx; - axis2sq = Uy*Uy + Vy*Vy; - if( axis1sq > lim*lim ) - { - RIfloat s = lim / (RIfloat)sqrt(axis1sq); - Ux *= s; - Vx *= s; - } - if( axis2sq > lim*lim ) - { - RIfloat s = lim / (RIfloat)sqrt(axis2sq); - Uy *= s; - Vy *= s; - } - - - //form elliptic filter by combining texel and pixel filters - RIfloat A = Vx*Vx + Vy*Vy + 1.0f; - RIfloat B = -2.0f*(Ux*Vx + Uy*Vy); - RIfloat C = Ux*Ux + Uy*Uy + 1.0f; - //scale by the user-defined size of the kernel - A *= m_resamplingFilterRadius; - B *= m_resamplingFilterRadius; - C *= m_resamplingFilterRadius; - - //calculate bounding box in texture space - RIfloat usize = (RIfloat)sqrt(C); - RIfloat vsize = (RIfloat)sqrt(A); - int u1 = (int)floor(U0 - usize + 0.5f); - int u2 = (int)floor(U0 + usize + 0.5f); - int v1 = (int)floor(V0 - vsize + 0.5f); - int v2 = (int)floor(V0 + vsize + 0.5f); - if( u1 == u2 || v1 == v2 ) - return Color(0,0,0,0,procFormat); - - //scale the filter so that Q = 1 at the cutoff radius - RIfloat F = A*C - 0.25f * B*B; - if( F <= 0.0f ) - return Color(0,0,0,0,procFormat); //invalid filter shape due to numerical inaccuracies => return black - RIfloat ooF = 1.0f / F; - A *= ooF; - B *= ooF; - C *= ooF; - - //evaluate filter by using forward differences to calculate Q = A*U^2 + B*U*V + C*V^2 - Color color(0,0,0,0,procFormat); - RIfloat sumweight = 0.0f; - RIfloat DDQ = 2.0f * A; - RIfloat U = (RIfloat)u1 - U0 + 0.5f; - for(int v=v1;v= 0.0f && Q < 1.0f ) - { //Q = r^2, fit gaussian to the range [0,1] - RIfloat weight = (RIfloat)exp(-0.5f * 10.0f * Q); //gaussian at radius 10 equals 0.0067 - color += weight * readTexel(u, v, level, tilingMode, tileFillColor); - sumweight += weight; - } - Q += DQ; - DQ += DDQ; - } - } - if( sumweight == 0.0f ) - return Color(0,0,0,0,procFormat); - RI_ASSERT(sumweight > 0.0f); - sumweight = 1.0f / sumweight; - return color * sumweight; - } - else -#endif - //if(aq & VG_IMAGE_QUALITY_FASTER) - if(aq & VG_IMAGE_QUALITY_BETTER) - { //bilinear - uvw.x -= 0.5f; - uvw.y -= 0.5f; - int u = (int)floor(uvw.x); - int v = (int)floor(uvw.y); - Color c00 = readTexel(u,v, 0, tilingMode, tileFillColor); - Color c10 = readTexel(u+1,v, 0, tilingMode, tileFillColor); - Color c01 = readTexel(u,v+1, 0, tilingMode, tileFillColor); - Color c11 = readTexel(u+1,v+1, 0, tilingMode, tileFillColor); - RIfloat fu = uvw.x - (RIfloat)u; - RIfloat fv = uvw.y - (RIfloat)v; - Color c0 = c00 * (1.0f - fu) + c10 * fu; - Color c1 = c01 * (1.0f - fu) + c11 * fu; - return c0 * (1.0f - fv) + c1 * fv; - } - else //VG_IMAGE_QUALITY_FASTER and VG_IMAGE_QUALITY_NONANTIALIASED - { //point sampling - return readTexel((int)floor(uvw.x), (int)floor(uvw.y), 0, tilingMode, tileFillColor); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Applies color matrix filter. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Image::colorMatrix(const Image& src, const RIfloat* matrix, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask) -{ - RI_ASSERT(src.m_data); //source exists - RI_ASSERT(m_data); //destination exists - RI_ASSERT(matrix); - RI_ASSERT(m_referenceCount > 0 && src.m_referenceCount > 0); - - int w = RI_INT_MIN(m_width, src.m_width); - int h = RI_INT_MIN(m_height, src.m_height); - RI_ASSERT(w > 0 && h > 0); - - Color::InternalFormat srcFormat = src.m_desc.internalFormat; - Color::InternalFormat procFormat = (Color::InternalFormat)(srcFormat & ~Color::LUMINANCE); //process in RGB, not luminance - if(filterFormatLinear) - procFormat = (Color::InternalFormat)(procFormat & ~Color::NONLINEAR); - else - procFormat = (Color::InternalFormat)(procFormat | Color::NONLINEAR); - - if(filterFormatPremultiplied) - procFormat = (Color::InternalFormat)(procFormat | Color::PREMULTIPLIED); - else - procFormat = (Color::InternalFormat)(procFormat & ~Color::PREMULTIPLIED); - - for(int j=0;j& 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 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= 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 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 tmp2; - tmp2.resize(w*src.m_height); //throws bad_alloc - for(int j=0;j= 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= 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 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 kernelX; - kernelX.resize(kernelWidth*2+1); - int shiftX = kernelWidth; - RIfloat scaleX = 0.0f; - for(int i=0;i kernelY; - kernelY.resize(kernelHeight*2+1); - int shiftY = kernelHeight; - RIfloat scaleY = 0.0f; - for(int i=0;i tmp2; - tmp2.resize(w*src.m_height); //throws bad_alloc - //horizontal pass - for(int j=0;j 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 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>24), 255); - d.g = intToColor((l>>16), 255); - d.b = intToColor((l>> 8), 255); - d.a = intToColor((l ), 255); - - writeFilteredPixel(i, j, d, channelMask); - } - } -} - - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Surface::Surface(const Color::Descriptor& desc, int width, int height, int numSamples) : - m_width(width), - m_height(height), - m_numSamples(numSamples), - m_referenceCount(0), - m_image(NULL) -{ - RI_ASSERT(width > 0 && height > 0 && numSamples > 0 && numSamples <= 32); - m_image = RI_NEW(Image, (desc, width*numSamples, height, 0)); //throws bad_alloc - m_image->addReference(); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Surface::Surface(Image* image) : - m_width(0), - m_height(0), - m_numSamples(1), - m_referenceCount(0), - m_image(image) -{ - RI_ASSERT(image); - m_width = image->getWidth(); - m_height = image->getHeight(); - m_image->addReference(); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Surface::Surface(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data) : - m_width(width), - m_height(height), - m_numSamples(1), - m_referenceCount(0), - m_image(NULL) -{ - RI_ASSERT(width > 0 && height > 0); - m_image = RI_NEW(Image, (desc, width, height, stride, data)); //throws bad_alloc - m_image->addReference(); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Surface::~Surface() -{ - RI_ASSERT(m_referenceCount == 0); - if(!m_image->removeReference()) - RI_DELETE(m_image); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Surface::clear(const Color& clearColor, int x, int y, int w, int h, const Array* scissors) -{ - RI_ASSERT(m_numSamples == 1); - - Image* image = m_image; - - Color col = clearColor; - col.clamp(); - col.convert(m_image->getDescriptor().internalFormat); - - IntegerColor ic = IntegerColor(col); - ic.truncateColor(m_image->getDescriptor()); - const RIuint32 c = ic.getPackedColor(m_image->getDescriptor()); - - if (x != 0 || y != 0 || w != image->getWidth() || h != image->getHeight() || scissors) - { - // Simple implementation: intersect with surface and clip rects -> may clear the - // same area several times. Best if scissors are non-overlapping - Rectangle r(0,0,getWidth(),getHeight()); - r.intersect(Rectangle(x,y,w,h)); - - if (r.isEmpty() || (scissors && scissors->size() == 0)) - return; - - if (scissors && scissors->size()) - { - for (int i = 0; i < scissors->size(); i++) - { - Rectangle s = (*scissors)[i]; - s.intersect(r); - - if (s.isEmpty()) - continue; - - image->fillPackedRectangle(s.x, s.y, s.width, s.height, c); - } - } - else - { - image->fillPackedRectangle(r.x, r.y, r.width, r.height, c); - } - } - else - { - // Clear the whole buffer - - m_image->fillPacked(c); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -#if 0 -void Surface::blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h) -{ - Rectangle rect; - rect.x = 0; - rect.y = 0; - rect.width = getWidth(); - rect.height = getHeight(); - Array scissors; - scissors.push_back(rect); - blit(src, sx, sy, dx, dy, w, h, scissors); -} -#endif - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note no overlap is possible. Single sample to single or multisample (replicate) -*//*-------------------------------------------------------------------*/ - -#if 0 -void Surface::blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h, const Array& 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 scissorEdges; - for(int i=0;i 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 scissorAet; - for(int j=0;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= 0); - - if(scissorWinding) - { - Color c = src.readPixel(sx + i, sy + j); - c.convert(getDescriptor().internalFormat); - for(int s=0;s scissors; - scissors.push_back(rect); - blit(src, sx, sy, dx, dy, w, h, scissors); -} -#endif - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -#if 0 -void Surface::blit(const Surface* src, int sx, int sy, int dx, int dy, int w, int h, const Array& 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 scissorEdges; - for(int i=0;i 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 tmp; - tmp.resize(w*m_numSamples*h); //throws bad_alloc - - //copy source region to tmp - for(int j=0;jm_image->readPixel((sx + i)*m_numSamples+s, sy + j); - c.convert(m_image->getDescriptor().internalFormat); - tmp[(j*w+i)*m_numSamples+s] = c; - } - } - } - - Array scissorAet; - for(int j=0;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= 0); - - if(scissorWinding) - { - int numSamples = m_numSamples; - for(int s=0;swritePixel((dx + i)*m_numSamples+s, dy + j, tmp[(j*w+i)*m_numSamples+s]); - } - } - } - } -} -#endif - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Surface::mask(DynamicBlitter& blitter, const Image* src, VGMaskOperation operation, int x, int y, int w, int h) -{ - RI_ASSERT(w > 0 && h > 0); - RI_ASSERT(m_numSamples == 1); - - if(operation == VG_CLEAR_MASK || operation == VG_FILL_MASK) - { - //intersect clear region with image bounds - Rectangle r(0,0,getWidth(),getHeight()); - r.intersect(Rectangle(x,y,w,h)); - - if(!r.width || !r.height) - return; //intersection is empty or one of the rectangles is invalid - - { - Color mcolor(1.0f, 1.0f, 1.0f, 1.0f, Color::sRGBA_PRE); - if (operation == VG_CLEAR_MASK) - mcolor = Color(0,0,0,0, Color::sRGBA_PRE); - IntegerColor ic = IntegerColor(mcolor); - RIuint32 p = ic.getPackedMaskColor(m_image->getDescriptor()); - m_image->fillPackedRectangle(r.x, r.y, r.width, r.height, p); - } - } - else - { - int sx = 0, sy = 0, dx = x, dy = y; - - computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), getWidth(), getHeight()); - - if(w <= 0 || h <= 0) - return; //zero area - - blitter.enableMaskOperation(true); - blitter.setMaskOperation(operation); - blitter.prepareBlit(this->m_image, src, sx, sy, dx, dy, w, h); - blitter.blit(); - blitter.enableMaskOperation(false); -#if 0 - RI_ASSERT(src); - - int sx = 0, sy = 0, dx = x, dy = y; - computeBlitRegion(sx, sy, dx, dy, w, h, src->getWidth(), src->getHeight(), getWidth(), getHeight()); - if(w <= 0 || h <= 0) - return; //zero area - - { - for(int j=0;jreadMaskPixel(sx + i, sy + j); - if(operation == VG_SET_MASK) - writeMaskCoverage(dx + i, dy + j, amask); - else - { - RIfloat aprev = readMaskCoverage(dx + i, dy + j); - RIfloat anew = 0.0f; - switch(operation) - { - case VG_UNION_MASK: anew = 1.0f - (1.0f - amask)*(1.0f - aprev); break; - case VG_INTERSECT_MASK: anew = amask * aprev; break; - default: anew = aprev * (1.0f - amask); RI_ASSERT(operation == VG_SUBTRACT_MASK); break; - } - writeMaskCoverage(dx + i, dy + j, anew); - } - } - } - } -#endif - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -RIfloat Surface::readMaskCoverage(int x, int y) const -{ - RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height); - RI_ASSERT(m_numSamples == 1); - return m_image->readMaskPixel(x, y); -} - -void Surface::writeMaskCoverage(int x, int y, RIfloat m) -{ - RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height); - RI_ASSERT(m_numSamples == 1); - m_image->writeMaskPixel(x, y, m); //TODO support other than alpha formats but don't write to color channels? -} - -unsigned int Surface::readMaskMSAA(int x, int y) const -{ - RI_ASSERT(x >= 0 && x < m_width && y >= 0 && y < m_height); - RI_ASSERT(m_numSamples > 1); - unsigned int m = 0; - for(int i=0;ireadMaskPixel(x*m_numSamples+i, y) > 0.5f) //TODO is this the right formula for converting alpha to bit mask? does it matter? - m |= 1<= 0 && x < m_width && y >= 0 && y < m_height); - RI_ASSERT(m_numSamples > 1); - for(int i=0;iwriteMaskPixel(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 0 && height > 0 && numSamples > 0 && numSamples <= 32); - RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8); - m_color = RI_NEW(Surface, (desc, width, height, numSamples)); //throws bad_alloc - m_color->addReference(); - if(maskBits) - { - VGImageFormat mf = VG_A_1; - if(maskBits == 4) - mf = VG_A_4; - else if(maskBits == 8) - mf = VG_A_8; - m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), width, height, numSamples)); - m_mask->addReference(); - m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Drawable::Drawable(Image* image, int maskBits) : - m_referenceCount(0), - m_color(NULL), - m_mask(NULL) -{ - RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8); - RI_ASSERT(image); - m_color = RI_NEW(Surface, (image)); - m_color->addReference(); - if(maskBits) - { - VGImageFormat mf = VG_A_1; - if(maskBits == 4) - mf = VG_A_4; - else if(maskBits == 8) - mf = VG_A_8; - m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), image->getWidth(), image->getHeight(), 1)); - m_mask->addReference(); - m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, image->getWidth(), image->getHeight()); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Drawable::Drawable(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data, int maskBits) : - m_referenceCount(0), - m_color(NULL), - m_mask(NULL) -{ - RI_ASSERT(width > 0 && height > 0); - RI_ASSERT(maskBits == 0 || maskBits == 1 || maskBits == 4 || maskBits == 8); - m_color = RI_NEW(Surface, (desc, width, height, stride, data)); //throws bad_alloc - m_color->addReference(); - if(maskBits) - { - VGImageFormat mf = VG_A_1; - if(maskBits == 4) - mf = VG_A_4; - else if(maskBits == 8) - mf = VG_A_8; - m_mask = RI_NEW(Surface, (Color::formatToDescriptor(mf), width, height, 1)); - m_mask->addReference(); - m_mask->clear(Color(1,1,1,1,Color::sRGBA), 0, 0, width, height); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Drawable::~Drawable() -{ - RI_ASSERT(m_referenceCount == 0); - if(!m_color->removeReference()) - RI_DELETE(m_color); - if(m_mask) - if(!m_mask->removeReference()) - RI_DELETE(m_mask); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Drawable::resize(VGContext* context, int newWidth, int newHeight) -{ - Surface* oldcolor = m_color; - Surface* oldmask = m_mask; - int oldWidth = m_color->getWidth(); - int oldHeight = m_color->getHeight(); - - //TODO check that image is not a proxy - m_color = RI_NEW(Surface, (m_color->getDescriptor(), newWidth, newHeight, m_color->getNumSamples())); - m_color->addReference(); - if(m_mask) - { - m_mask = RI_NEW(Surface, (m_mask->getDescriptor(), newWidth, newHeight, m_mask->getNumSamples())); - m_mask->addReference(); - } - - int wmin = RI_INT_MIN(newWidth,oldWidth); - int hmin = RI_INT_MIN(newHeight,oldHeight); - m_color->clear(Color(0.0f, 0.0f, 0.0f, 0.0f, getDescriptor().internalFormat), 0, 0, m_color->getWidth(), m_color->getHeight()); - m_color->m_image->blit(context, oldcolor->m_image, 0, 0, 0, 0, wmin, hmin); - if(m_mask) - { - m_mask->clear(Color(1.0f, 1.0f, 1.0f, 1.0f, getDescriptor().internalFormat), 0, 0, m_mask->getWidth(), m_mask->getHeight()); - m_mask->m_image->blit(context, oldmask->m_image, 0, 0, 0, 0, wmin, hmin); - } - - if(!oldcolor->removeReference()) - RI_DELETE(oldcolor); - if(oldmask) - if(!oldmask->removeReference()) - RI_DELETE(oldmask); -} - -#ifndef RI_COMPILE_LLVM_BYTECODE - -#endif /* RI_COMPILE_LLVM_BYTECODE */ - -//============================================================================================== - -} //namespace OpenVGRI - -//============================================================================================== diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riImage.h --- a/hostsupport/hostopenvg/src/src/riImage.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1593 +0,0 @@ -#ifndef __RIIMAGE_H -#define __RIIMAGE_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Color and Image classes. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef _OPENVG_H -#include "VG/openvg.h" -#endif - -#ifndef __RIMATH_H -#include "riMath.h" -#endif - -#ifndef __RIARRAY_H -#include "riArray.h" -#endif - -#include "sfAlphaRcp.h" -#include "sfGammaLUT.h" -#include "riUtils.h" - -//============================================================================================== - -namespace OpenVGRI -{ - -class VGContext; -class DynamicBlitter; - -/*-------------------------------------------------------------------*//*! -* \brief A class representing rectangles. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class Rectangle -{ -public: - Rectangle() : x(0), y(0), width(0), height(0) {} - Rectangle(int rx, int ry, int rw, int rh) : x(rx), y(ry), width(rw), height(rh) {} - void intersect(const Rectangle& r) - { - if(width >= 0 && r.width >= 0 && height >= 0 && r.height >= 0) - { - int x1 = RI_INT_MIN(RI_INT_ADDSATURATE(x, width), RI_INT_ADDSATURATE(r.x, r.width)); - x = RI_INT_MAX(x, r.x); - width = RI_INT_MAX(x1 - x, 0); - - int y1 = RI_INT_MIN(RI_INT_ADDSATURATE(y, height), RI_INT_ADDSATURATE(r.y, r.height)); - y = RI_INT_MAX(y, r.y); - height = RI_INT_MAX(y1 - y, 0); - } - else - { - x = 0; - y = 0; - width = 0; - height = 0; - } - } - bool isEmpty() const { return width == 0 || height == 0; } - - int x; - int y; - int width; - int height; -}; - -/*-------------------------------------------------------------------*//*! -* \brief A class representing color for processing and converting it -* to and from various surface formats. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class Color -{ -public: - enum FormatSize - { - SIZE_1 = 0, - SIZE_4 = 1, - SIZE_8 = 2, - SIZE_16 = 3, - SIZE_24 = 4, - SIZE_32 = 5 - }; - - enum Shape - { - SHAPE_RGBA = 0, - SHAPE_RGBX = 1, - SHAPE_RGB = 2, - SHAPE_LA = 3, - SHAPE_L = 4, - SHAPE_A = 5, - SHAPE_ARGB = 6, - SHAPE_XRGB = 7, - SHAPE_AL = 8, - SHAPE_BGRA = 9, - SHAPE_BGRX = 10, - SHAPE_BGR = 11, - SHAPE_ABGR = 12, - SHAPE_XBGR = 13 - }; - enum InternalFormat - { - lRGBA = 0, - sRGBA = 1, - lRGBA_PRE = 2, - sRGBA_PRE = 3, - lLA = 4, - sLA = 5, - lLA_PRE = 6, - sLA_PRE = 7 - }; - enum FormatBits - { - NONLINEAR = (1<<0), - PREMULTIPLIED = (1<<1), - LUMINANCE = (1<<2) - }; - struct SmallDescriptor - { - RIuint32 toUint32() - { - RIuint32 ret = 0; - ret = (RIuint32)size; - ret |= (RIuint32)shape << 3; - ret |= (RIuint32)internalFormat << (3 + 4); - return ret; - } - FormatSize size; - Shape shape; - InternalFormat internalFormat; - }; - class Descriptor - { - public: - Descriptor() {}; - RI_INLINE Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp, Shape shape); - RI_INLINE bool isNonlinear() const { return (internalFormat & NONLINEAR) ? true : false; } - RI_INLINE void setNonlinear(bool nonlinear); - RI_INLINE bool isPremultiplied() const { return (internalFormat & PREMULTIPLIED) ? true : false; } - RI_INLINE bool isLuminance() const { return (internalFormat & LUMINANCE) ? true : false; } - RI_INLINE bool isAlphaOnly() const { return (alphaBits && (redBits+greenBits+blueBits+luminanceBits) == 0) ? true : false; } - RI_INLINE bool isBW() const { return isLuminance() && (luminanceBits == 1); } - RI_INLINE bool hasAlpha() const { return alphaBits > 0; } - RI_INLINE bool operator==(const Descriptor& rhs) const; - RI_INLINE bool isShiftConversionToLower(const Descriptor& rhs) const; - RI_INLINE bool isShiftConversion(const Descriptor& rhs) const; - RI_INLINE bool isZeroConversion(const Descriptor& rhs) const; - RI_INLINE bool maybeUnsafe() const { return internalFormat & PREMULTIPLIED ? true : false; }; - static RI_INLINE RIuint32 crossConvertToLower(RIuint32 c, const Descriptor& src, const Descriptor& dst); - void toSmallDescriptor(SmallDescriptor& smallDesc) const; - RI_INLINE RIuint32 toIndex() const; - static Descriptor getDummyDescriptor(); - Shape getShape() const; - - int redBits; - int redShift; - int greenBits; - int greenShift; - int blueBits; - int blueShift; - int alphaBits; - int alphaShift; - int luminanceBits; - int luminanceShift; - Shape shape; - VGImageFormat vgFormat; // \note Storage only - InternalFormat internalFormat; - int bitsPerPixel; - // Derived info: - int bytesPerPixel; - int maskBits; - int maskShift; - }; - - RI_INLINE Color() : r(0.0f), g(0.0f), b(0.0f), a(0.0f), m_format(sRGBA_PRE) {} - RI_INLINE Color(RIfloat cl, RIfloat ca, InternalFormat cs) : r(cl), g(cl), b(cl), a(ca), m_format(cs) { RI_ASSERT(cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); } - RI_INLINE Color(RIfloat cr, RIfloat cg, RIfloat cb, RIfloat ca, InternalFormat cs) : r(cr), g(cg), b(cb), a(ca), m_format(cs) { RI_ASSERT(cs == lRGBA || cs == sRGBA || cs == lRGBA_PRE || cs == sRGBA_PRE || cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); } - RI_INLINE Color(const Color& c) : r(c.r), g(c.g), b(c.b), a(c.a), m_format(c.m_format) {} - RI_INLINE Color& operator=(const Color&c) { r = c.r; g = c.g; b = c.b; a = c.a; m_format = c.m_format; return *this; } - RI_INLINE void operator*=(RIfloat f) { r *= f; g *= f; b *= f; a*= f; } - RI_INLINE void operator+=(const Color& c1) { RI_ASSERT(m_format == c1.getInternalFormat()); r += c1.r; g += c1.g; b += c1.b; a += c1.a; } - RI_INLINE void operator-=(const Color& c1) { RI_ASSERT(m_format == c1.getInternalFormat()); r -= c1.r; g -= c1.g; b -= c1.b; a -= c1.a; } - - void set(RIfloat cl, RIfloat ca, InternalFormat cs) { RI_ASSERT(cs == lLA || cs == sLA || cs == lLA_PRE || cs == sLA_PRE); r = cl; g = cl; b = cl; a = ca; m_format = cs; } - void set(RIfloat cr, RIfloat cg, RIfloat cb, RIfloat ca, InternalFormat cs) { RI_ASSERT(cs == lRGBA || cs == sRGBA || cs == lRGBA_PRE || cs == sRGBA_PRE); r = cr; g = cg; b = cb; a = ca; m_format = cs; } - void unpack(unsigned int inputData, const Descriptor& inputDesc); - unsigned int pack(const Descriptor& outputDesc) const; - RI_INLINE InternalFormat getInternalFormat() const { return m_format; } - - //clamps nonpremultiplied colors and alpha to [0,1] range, and premultiplied alpha to [0,1], colors to [0,a] - void clamp() { a = RI_CLAMP(a,0.0f,1.0f); RIfloat u = (m_format & PREMULTIPLIED) ? a : (RIfloat)1.0f; r = RI_CLAMP(r,0.0f,u); g = RI_CLAMP(g,0.0f,u); b = RI_CLAMP(b,0.0f,u); } - void convert(InternalFormat outputFormat); - void premultiply() { if(!(m_format & PREMULTIPLIED)) { r *= a; g *= a; b *= a; m_format = (InternalFormat)(m_format | PREMULTIPLIED); } } - void unpremultiply() { if(m_format & PREMULTIPLIED) { RIfloat ooa = (a != 0.0f) ? 1.0f/a : (RIfloat)0.0f; r *= ooa; g *= ooa; b *= ooa; m_format = (InternalFormat)(m_format & ~PREMULTIPLIED); } } - void luminanceToRGB() { if(m_format & LUMINANCE) { RI_ASSERT(r == g && g == b); m_format = (InternalFormat)(m_format & ~LUMINANCE); } } - - bool isNonlinear() const { return (m_format & NONLINEAR) ? true : false; } - bool isPremultiplied() const { return (m_format & PREMULTIPLIED) ? true : false; } - bool isLuminance() const { return (m_format & LUMINANCE) ? true : false; } - - RI_INLINE void assertConsistency() const; - - // \note Why are these in the color class instead of descriptor? - static VGImageFormat descriptorToVGImageFormat(const Descriptor& desc); - RI_INLINE static Descriptor formatToDescriptorConst(VGImageFormat format); - static Descriptor formatToDescriptor(VGImageFormat format); - static bool isValidDescriptor(const Descriptor& desc); - - RIfloat r; - RIfloat g; - RIfloat b; - RIfloat a; -private: - InternalFormat m_format; -}; - -RI_INLINE Color::Descriptor::Descriptor(int dredBits, int dredShift, int dgreenBits, int dgreenShift, int dblueBits, int dblueShift, int dalphaBits, int dalphaShift, int dluminanceBits, int dluminanceShift, InternalFormat dinternalFormat, int dbpp, Shape shape) : - redBits(dredBits), - redShift(dredShift), - greenBits(dgreenBits), - greenShift(dgreenShift), - blueBits(dblueBits), - blueShift(dblueShift), - alphaBits(dalphaBits), - alphaShift(dalphaShift), - luminanceBits(dluminanceBits), - luminanceShift(dluminanceShift), - shape(shape), - internalFormat(dinternalFormat), - bitsPerPixel(dbpp) -{ - bytesPerPixel = bitsPerPixel / 8; - - if (alphaBits) - { - maskBits = alphaBits; - maskShift = alphaShift; - } - else if (!this->isLuminance()) - { - maskBits = redBits; - maskShift = redShift; - } - else - { - maskBits = luminanceBits; - maskShift = luminanceShift; - } - RI_ASSERT(getShape() == shape); -} - -RI_INLINE void Color::Descriptor::setNonlinear(bool nonlinear) -{ - if (nonlinear) - internalFormat = (InternalFormat)(((RIuint32)internalFormat)|NONLINEAR); - else - internalFormat = (InternalFormat)(((RIuint32)internalFormat)&(~NONLINEAR)); -} - -/** - * \brief Creates a pixel format descriptor out of VGImageFormat - * \todo The formats without alpha were non-premultiplied in the reference - * implementation, but wouldn't it make more sense to consider them - * premultiplied? This would make sense at least when blitting to - * windows, etc., where the output color should have the alpha - * multiplied "in". - */ -RI_INLINE Color::Descriptor Color::formatToDescriptorConst(VGImageFormat format) -{ - switch(format) - { - case VG_sRGBX_8888: - return Color::Descriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_RGBX); - case VG_sRGBA_8888: - return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::sRGBA, 32, SHAPE_RGBA); - case VG_sRGBA_8888_PRE: - return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::sRGBA_PRE, 32, SHAPE_RGBA); - case VG_sRGB_565: - return Color::Descriptor(5, 11, 6, 5, 5, 0, 0, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGB); - case VG_sRGBA_5551: - return Color::Descriptor(5, 11, 5, 6, 5, 1, 1, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGBA); - case VG_sRGBA_4444: - return Color::Descriptor(4, 12, 4, 8, 4, 4, 4, 0, 0, 0, Color::sRGBA, 16, SHAPE_RGBA); - case VG_sL_8: - return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, Color::sLA, 8, SHAPE_L); - case VG_lRGBX_8888: - return Color::Descriptor(8, 24, 8, 16, 8, 8, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_RGBX); - case VG_lRGBA_8888: - return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::lRGBA, 32, SHAPE_RGBA); - case VG_lRGBA_8888_PRE: - return Color::Descriptor(8, 24, 8, 16, 8, 8, 8, 0, 0, 0, Color::lRGBA_PRE, 32, SHAPE_RGBA); - case VG_lL_8: - return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 8, 0, Color::lLA, 8, SHAPE_L); - case VG_A_8: - return Color::Descriptor(0, 0, 0, 0, 0, 0, 8, 0, 0, 0, Color::lRGBA, 8, SHAPE_A); - case VG_BW_1: - return Color::Descriptor(0, 0, 0, 0, 0, 0, 0, 0, 1, 0, Color::lLA, 1, SHAPE_L); - case VG_A_1: - return Color::Descriptor(0, 0, 0, 0, 0, 0, 1, 0, 0, 0, Color::lRGBA, 1, SHAPE_A); - case VG_A_4: - return Color::Descriptor(0, 0, 0, 0, 0, 0, 4, 0, 0, 0, Color::lRGBA, 4, SHAPE_A); - - /* {A,X}RGB channel ordering */ - case VG_sXRGB_8888: - return Color::Descriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_XRGB); - case VG_sARGB_8888: - return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::sRGBA, 32, SHAPE_ARGB); - case VG_sARGB_8888_PRE: - return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::sRGBA_PRE, 32, SHAPE_ARGB); - case VG_sARGB_1555: - return Color::Descriptor(5, 10, 5, 5, 5, 0, 1, 15, 0, 0, Color::sRGBA, 16, SHAPE_ARGB); - case VG_sARGB_4444: - return Color::Descriptor(4, 8, 4, 4, 4, 0, 4, 12, 0, 0, Color::sRGBA, 16, SHAPE_ARGB); - case VG_lXRGB_8888: - return Color::Descriptor(8, 16, 8, 8, 8, 0, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_XRGB); - case VG_lARGB_8888: - return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::lRGBA, 32, SHAPE_ARGB); - case VG_lARGB_8888_PRE: - return Color::Descriptor(8, 16, 8, 8, 8, 0, 8, 24, 0, 0, Color::lRGBA_PRE, 32, SHAPE_ARGB); - - /* BGR{A,X} channel ordering */ - case VG_sBGRX_8888: - return Color::Descriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_BGRX); - case VG_sBGRA_8888: - return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::sRGBA, 32, SHAPE_BGRA); - case VG_sBGRA_8888_PRE: - return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::sRGBA_PRE, 32, SHAPE_BGRA); - case VG_sBGR_565: - return Color::Descriptor(5, 0, 6, 5, 5, 11, 0, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGR); - case VG_sBGRA_5551: - return Color::Descriptor(5, 1, 5, 6, 5, 11, 1, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGRA); - case VG_sBGRA_4444: - return Color::Descriptor(4, 4, 4, 8, 4, 12, 4, 0, 0, 0, Color::sRGBA, 16, SHAPE_BGRA); - case VG_lBGRX_8888: - return Color::Descriptor(8, 8, 8, 16, 8, 24, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_BGRX); - case VG_lBGRA_8888: - return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::lRGBA, 32, SHAPE_BGRA); - case VG_lBGRA_8888_PRE: - return Color::Descriptor(8, 8, 8, 16, 8, 24, 8, 0, 0, 0, Color::lRGBA_PRE, 32, SHAPE_BGRA); - - /* {A,X}BGR channel ordering */ - case VG_sXBGR_8888: - return Color::Descriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, Color::sRGBA, 32, SHAPE_XBGR); - case VG_sABGR_8888: - return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::sRGBA, 32, SHAPE_ABGR); - case VG_sABGR_8888_PRE: - return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::sRGBA_PRE, 32, SHAPE_ABGR); - case VG_sABGR_1555: - return Color::Descriptor(5, 0, 5, 5, 5, 10, 1, 15, 0, 0, Color::sRGBA, 16, SHAPE_ABGR); - case VG_sABGR_4444: - return Color::Descriptor(4, 0, 4, 4, 4, 8, 4, 12, 0, 0, Color::sRGBA, 16, SHAPE_ABGR); - case VG_lXBGR_8888: - return Color::Descriptor(8, 0, 8, 8, 8, 16, 0, 0, 0, 0, Color::lRGBA, 32, SHAPE_XBGR); - case VG_lABGR_8888: - return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::lRGBA, 32, SHAPE_ABGR); - default: - //case VG_lABGR_8888_PRE: - RI_ASSERT(format == VG_lABGR_8888_PRE); - return Color::Descriptor(8, 0, 8, 8, 8, 16, 8, 24, 0, 0, Color::lRGBA_PRE, 32, SHAPE_ABGR); - } -} - -RI_INLINE bool Color::Descriptor::operator==(const Descriptor& rhs) const -{ - return memcmp(this, &rhs, sizeof(Descriptor)) ? false : true; -} - -RI_INLINE bool Color::Descriptor::isZeroConversion(const Descriptor& rhs) const -{ - return (shape == rhs.shape) && - (internalFormat == rhs.internalFormat) && - (redBits == rhs.redBits) && - (greenBits == rhs.greenBits) && - (blueBits == rhs.blueBits) && - (alphaBits == rhs.alphaBits) && - (luminanceBits == rhs.luminanceBits); -} - -RI_INLINE bool Color::Descriptor::isShiftConversion(const Descriptor& rhs) const -{ - // \note BW conversion is always forced to full at the moment. - if (isBW() != rhs.isBW()) - return false; - - return (isPremultiplied() == rhs.isPremultiplied()) - && (isNonlinear() == rhs.isNonlinear()) - && (isLuminance() == rhs.isLuminance()); -} - -RI_INLINE bool Color::Descriptor::isShiftConversionToLower(const Descriptor& rhs) const -{ - // \note BW conversion is always forced to full at the moment. - if (isBW() != rhs.isBW()) - return false; - // \note Mask bits are not checked because they are derived information. - return (isShiftConversion(rhs) - && (rhs.redBits <= redBits) - && (rhs.greenBits <= greenBits) - && (rhs.blueBits <= blueBits) - && (rhs.alphaBits <= alphaBits) - && (rhs.luminanceBits <= luminanceBits)); - -} - -/** - * \brief In-place conversion of packed color to lower bit-depth - * \param c Input packed color - * \param src Source color descriptor - * \param dst Destination color descriptor - */ -RI_INLINE RIuint32 Color::Descriptor::crossConvertToLower(RIuint32 c, const Descriptor& src, const Descriptor& dst) -{ - RIuint32 r = 0; - - RI_ASSERT(dst.redBits <= src.redBits); - RI_ASSERT(dst.greenBits <= src.greenBits); - RI_ASSERT(dst.blueBits <= src.blueBits); - RI_ASSERT(dst.alphaBits <= src.alphaBits); - - if (src.isLuminance()) - { - RI_ASSERT(dst.isLuminance()); - r = ((c >> (src.luminanceShift + src.luminanceBits - dst.luminanceBits)) & ((1u<> (src.redShift + src.redBits - dst.redBits)) & ((1u<> (src.greenShift + src.greenBits - dst.greenBits)) & ((1u<> (src.blueShift + src.blueBits - dst.blueBits)) & ((1u<> (src.alphaShift + src.alphaBits - dst.alphaBits)) & ((1u<= 0.0f && r <= 1.0f); - RI_ASSERT(g >= 0.0f && g <= 1.0f); - RI_ASSERT(b >= 0.0f && b <= 1.0f); - RI_ASSERT(a >= 0.0f && a <= 1.0f); - RI_ASSERT(!isPremultiplied() || (r <= a && g <= a && b <= a)); //premultiplied colors must have color channels less than or equal to alpha - RI_ASSERT((isLuminance() && r == g && r == b) || !isLuminance()); //if luminance, r=g=b -} - -class IntegerColor -{ -public: - - IntegerColor() {r = g = b = a = 0;} - IntegerColor(const Color& color); - - RI_INLINE IntegerColor(RIuint32 packedColor, const Color::Descriptor& desc) { fromPackedColor(packedColor, desc); } - RI_INLINE IntegerColor(RIuint32 cr, RIuint32 cg, RIuint32 cb, RIuint32 ca) { r = cr; g = cg; b = cb; a = ca; } - RI_INLINE void asFixedPoint(const Color& color); - RI_INLINE void fromPackedColor(RIuint32 packedColor, const Color::Descriptor& desc); - RI_INLINE void expandColor(const Color::Descriptor& desc); - RI_INLINE void truncateColor(const Color::Descriptor& desc); - RI_INLINE void clampToAlpha(); - RI_INLINE RIuint32 getPackedColor(const Color::Descriptor& desc) const; - RI_INLINE RIuint32 getPackedMaskColor(const Color::Descriptor& desc) const; - RI_INLINE void premultiply(bool luminance = false); - RI_INLINE void unpremultiply(bool luminance = false); - //RI_INLINE void linearToGamma(bool luminance, bool premultipliedIn, bool premultipliedOut); - RI_INLINE void linearToGamma(bool luminance = false); - RI_INLINE void gammaToLinear(bool luminance = false); - RI_INLINE void fromPackedMask(RIuint32 packedColor, const Color::Descriptor& desc); - RI_INLINE void expandMask(const Color::Descriptor& desc); - RI_INLINE void truncateMask(const Color::Descriptor& desc); - RI_INLINE void fullLuminanceToRGB(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut); - RI_INLINE void fullRGBToLuminance(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut); - RI_INLINE void luminanceToRGB(); - RI_INLINE void rgbToLuminance(); - RI_INLINE void convertToFrom(const Color::Descriptor& dst, const Color::Descriptor& src, bool srcIsMask); - - RI_INLINE static IntegerColor linearBlendNS(const IntegerColor& c0, const IntegerColor& c1, int k); - - RIuint32 r; - RIuint32 g; - RIuint32 b; - RIuint32 a; - -}; - -/** - * \brief Blend two colors linearly. The output will not be scaled into original range. - * \param k Blend coefficient. Must be [0..255] for correct results. - * \todo Parameterize against bits in k? To perform well, that setup must be compiled rt. - */ -RI_INLINE IntegerColor IntegerColor::linearBlendNS(const IntegerColor& c0, const IntegerColor& c1, int k) -{ - RI_ASSERT(k >= 0 && k <= 255); - IntegerColor ret; - RIuint32 ik = 255 - k; - - ret.r = ik * c0.r + k * c1.r; - ret.g = ik * c0.g + k * c1.g; - ret.b = ik * c0.b + k * c1.b; - ret.a = ik * c0.a + k * c1.a; - - return ret; -} - -/** - * \note Assumes that each individual component is in proper range (usually indicated by the - * corresponding shift). - */ -RI_INLINE RIuint32 packRGBAInteger(RIuint32 cr, int rs, RIuint32 cg, int gs, RIuint32 cb, int bs, RIuint32 ca, int as) -{ - return (cr << rs) | (cg << gs) | (cb << bs) | (ca << as); -} - -/** - * \brief Packs a color into RIuint32. - * \note The color must have been truncated to contain correct amount of bits per channel - * \note This function is efficient only if runtime compilation is used. - */ -RI_INLINE RIuint32 IntegerColor::getPackedColor(const Color::Descriptor& desc) const -{ - RIuint32 res = 0; - if (desc.luminanceBits) - { - RI_ASSERT(desc.redBits == 0 && desc.greenBits == 0 && desc.blueBits == 0); - RI_ASSERT(r < (1u<>7); - r = (r * fxa); r = (r + (1<<7))>>8; - - if (!luminance) - { - g = (g * fxa); g = (g + (1<<7))>>8; - b = (b * fxa); b = (b + (1<<7))>>8; - } -} - -RI_INLINE void IntegerColor::unpremultiply(bool luminance) -{ - RI_ASSERT(a <= 255); - - RIuint32 rcp = sc_alphaRcp[a]; - r = (r * rcp) >> 8; - - if (!luminance) - { - g = (g * rcp) >> 8; - b = (b * rcp) >> 8; - } -} - -RI_INLINE void IntegerColor::linearToGamma(bool luminance) -{ - RI_ASSERT(r <= 255 && g <= 255 && b <= 255 && a <= 255); - - r = sc_lRGB_to_sRGB[r]; - - if (!luminance) - { - g = sc_lRGB_to_sRGB[g]; - b = sc_lRGB_to_sRGB[b]; - } - - // \note Alpha is _not_ converted and it must be considered linear always -} - -RI_INLINE void IntegerColor::gammaToLinear(bool luminance) -{ - RI_ASSERT(r <= 255 && g <= 255 && b <= 255 && a <= 255); - - r = sc_sRGB_to_lRGB[r]; - if (!luminance) - { - g = sc_sRGB_to_lRGB[g]; - b = sc_sRGB_to_lRGB[b]; - } - - // \note Alpha is _not_ converted and it must be considered linear always -} - -RI_INLINE void IntegerColor::asFixedPoint(const Color& color) -{ - r = (RIuint32)(color.r * 256.0f + 0.5f); - g = (RIuint32)(color.g * 256.0f + 0.5f); - b = (RIuint32)(color.b * 256.0f + 0.5f); - a = (RIuint32)(color.a * 256.0f + 0.5f); -} - -RI_INLINE void IntegerColor::fromPackedColor(RIuint32 packedColor, const Color::Descriptor& desc) -{ - /* \note Expand MUST be done separately! */ - - if (desc.luminanceBits) - { - r = (packedColor >> desc.luminanceShift) & ((1u << desc.luminanceBits)-1); - g = b = r; - } - else - { - r = (packedColor >> desc.redShift) & ((1u << desc.redBits)-1); - g = (packedColor >> desc.greenShift) & ((1u << desc.greenBits)-1); - b = (packedColor >> desc.blueShift) & ((1u << desc.blueBits)-1); - } - - if (desc.alphaBits) - a = (packedColor >> desc.alphaShift) & ((1u << desc.alphaBits)-1); - else - a = 255; -} - -/** - * \brief Expand color to larger (or same) bit depth as in the OpenVG specification. - * \todo 1 and 2 bpp! - */ -RI_INLINE RIuint32 expandComponent(RIuint32 c, RIuint32 srcBits) -{ - const RIuint32 destBits = 8; - RI_ASSERT(destBits >= srcBits); - - if (!srcBits) return 0; - - if (srcBits == destBits) return c; - - switch (srcBits) - { - case 6: - return (c << 2) | (c >> 4); - case 5: - return (c << 3) | (c >> 2); - case 4: - return (c << 4) | c; - case 2: - return c | (c << 2) | (c << 4) | (c << 6); - default: - RI_ASSERT(srcBits == 1); - if (c) return 0xff; - return 0; - } -} - -/** - * \brief Expands integer color representation to internal format (8-bits per component atm.). - * \todo Do nothing when bits == 8. - */ -RI_INLINE void IntegerColor::expandColor(const Color::Descriptor& desc) -{ - if (desc.luminanceBits) - { - r = expandComponent(r, desc.luminanceBits); - g = b = r; - a = 255; - } else - { - if (desc.redBits < 8 || desc.luminanceBits < 8) - r = expandComponent(r, desc.redBits); - if (desc.greenBits < 8) - g = expandComponent(g, desc.greenBits); - if (desc.blueBits < 8) - b = expandComponent(b, desc.blueBits); - } - - if (desc.alphaBits && desc.alphaBits < 8) - a = expandComponent(a, desc.alphaBits); - - if (desc.isAlphaOnly()) - { - if (!desc.isPremultiplied()) - r = g = b = 255; - else - r = g = b = a; - } -} - -/** - * \brief Convert IntegerColor components to destination bitdepth (from internal) by - * shifting. Rounding does not take place. - */ -RI_INLINE void IntegerColor::truncateColor(const Color::Descriptor& desc) -{ - if (desc.luminanceBits) - { - RI_ASSERT(desc.redBits == 0 && desc.greenBits == 0 && desc.blueBits == 0); - if (desc.luminanceBits == 1) - { - // Round the 1-bit case a bit better? - r = (r + 128)>>8; - } else if (desc.luminanceBits < 8) - r >>= (8 - desc.luminanceBits); - } - else - { - if (desc.redBits < 8) - r >>= (8 - desc.redBits); - if (desc.greenBits < 8) - g >>= (8 - desc.greenBits); - if (desc.blueBits < 8) - b >>= (8 - desc.blueBits); - } - - if (desc.alphaBits < 8) - { - if (desc.alphaBits == 1) - a = (a+128)>>8; - else - a >>= (8 - desc.alphaBits); - } -} - -RI_INLINE void IntegerColor::truncateMask(const Color::Descriptor& desc) -{ - if (desc.redBits < 8 || desc.luminanceBits < 8) - r >>= (8 - desc.maskBits); - if (desc.greenBits < 8) - g >>= (8 - desc.maskBits); - if (desc.blueBits < 8) - b >>= (8 - desc.maskBits); - if (desc.alphaBits < 8) - a >>= (8 - desc.maskBits); -} - -RI_INLINE void IntegerColor::clampToAlpha() -{ - if (r > a) r = a; - if (g > a) g = a; - if (b > a) b = a; -} - -RI_INLINE void IntegerColor::fromPackedMask(RIuint32 packedMask, const Color::Descriptor& desc) -{ - RI_ASSERT(desc.maskBits); - a = (packedMask >> desc.maskShift) & ((1u << desc.maskBits)-1); -} - -RI_INLINE void IntegerColor::expandMask(const Color::Descriptor& desc) -{ - a = expandComponent(a, desc.maskBits); - r = g = b = a; -} - -#if 0 -RI_INLINE void IntegerColor::truncateMask(const Color::Descriptor& desc) -{ - a >>= (8 - desc.maskBits); -} -#endif - -RI_INLINE void IntegerColor::fullLuminanceToRGB(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut) -{ - if (premultipliedIn) - unpremultiply(); - - luminanceToRGB(); - - if (gammaIn != gammaOut) - { - if (gammaIn) - gammaToLinear(); - else - linearToGamma(); - } - - if (premultipliedOut) - premultiply(); - -} - -RI_INLINE void IntegerColor::fullRGBToLuminance(bool premultipliedIn, bool gammaIn, bool premultipliedOut, bool gammaOut) -{ - if (premultipliedIn) - unpremultiply(); - - if (gammaIn) - gammaToLinear(); - - rgbToLuminance(); - - if (gammaOut) - linearToGamma(); - - if (premultipliedOut) - premultiply(); - -} - - -// \todo This should not be needed (only r-channel is used anyway) -RI_INLINE void IntegerColor::luminanceToRGB() -{ - g = b = r; -} - -// \todo Only write to R! -RI_INLINE void IntegerColor::rgbToLuminance() -{ - enum { Rx = 871, Gx = 2929, Bx = 296, Bits = 12 }; - //enum { Rx = 54, Gx = 183, Bx = 18, Bits = 8 }; - RIuint32 l = Rx * r + Gx * g + Bx * b; - r = g = b = l >> Bits; -} - -#if 0 -RI_INLINE void IntegerColor::convertFromInternal(const Color::Descriptor& dst) -{ -} -#endif - -/** - * \brief Convert color from one format to another using integer operations. - * \note Currently expands the color to intermediate format first (8 bits - * per component. - */ -RI_INLINE void IntegerColor::convertToFrom(const Color::Descriptor& dst, const Color::Descriptor& src, bool srcIsMask) -{ - if (src.isZeroConversion(dst)) - return; - - if (src.isShiftConversionToLower(dst)) - { - if (dst.luminanceBits) - { - if (dst.luminanceBits == 1) - { - RI_ASSERT(src.luminanceBits == 8); - r = (r + 128)>>8; - } - else - r = r >> (src.luminanceBits - dst.luminanceBits); - } else - { - r = r >> (src.redBits - dst.redBits); - g = g >> (src.greenBits - dst.greenBits); - b = b >> (src.blueBits - dst.blueBits); - } - if (dst.alphaBits) - { - //a = (a+128)>>8; - if (dst.alphaBits == 1) - a = (a+(1<<(src.alphaBits-1)))>>src.alphaBits; - else - a = a >> (src.alphaBits - dst.alphaBits); - } - - return; - } - - if (!srcIsMask) - expandColor(src); - else - expandMask(src); - - - if (dst.isLuminance() != src.isLuminance()) - { - if (src.isLuminance()) - fullLuminanceToRGB(src.isPremultiplied(), src.isNonlinear(), dst.isPremultiplied(), dst.isNonlinear()); - else - fullRGBToLuminance(src.isPremultiplied(), src.isNonlinear(), dst.isPremultiplied(), dst.isNonlinear()); - } - else if (dst.isNonlinear() != src.isNonlinear()) - { - // No luminance/rgb change. - // Change of gamma requires unpremultiplication: - if (src.isPremultiplied() && !(src.isAlphaOnly())) - unpremultiply(); - - if (src.isNonlinear()) - gammaToLinear(src.isLuminance()); - else - linearToGamma(src.isLuminance()); - - if (dst.isPremultiplied() && !(dst.isAlphaOnly())) - premultiply(); - } - else - if ((dst.isPremultiplied() != src.isPremultiplied()) && !(dst.isAlphaOnly() || dst.isAlphaOnly())) - { - // \todo Make sure non-alpha formats are properly handled. - if (src.isPremultiplied()) - unpremultiply(dst.isLuminance()); - else - premultiply(dst.isLuminance()); - } - - truncateColor(dst); -} - -//============================================================================================== - -/*-------------------------------------------------------------------*//*! -* \brief Storage and operations for VGImage. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class Surface; -class Image -{ -public: - Image(const Color::Descriptor& desc, int width, int height, VGbitfield allowedQuality); //throws bad_alloc - //use data from a memory buffer. NOTE: data is not copied, so it is user's responsibility to make sure the data remains valid while the Image is in use. - Image(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data); //throws bad_alloc - //child image constructor - Image(Image* parent, int x, int y, int width, int height); //throws bad_alloc - ~Image(); - - const Color::Descriptor& getDescriptor() const { return m_desc; } - int getWidth() const { return m_width; } - int getHeight() const { return m_height; } - int getStride() const { return m_stride; } - Image* getParent() const { return m_parent; } - VGbitfield getAllowedQuality() const { return m_allowedQuality; } - void addInUse() { m_inUse++; } - void removeInUse() { RI_ASSERT(m_inUse > 0); m_inUse--; } - int isInUse() const { return m_inUse; } - RIuint8* getData() const { return m_data; } - void addReference() { m_referenceCount++; } - int removeReference() { m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; } - bool overlaps(const Image* src) const; - void setUnsafe(bool unsafe) { if (unsafe && m_desc.maybeUnsafe()) m_unsafeData = unsafe; else m_unsafeData = false; } - bool isUnsafe() const { return m_unsafeData; } - - void clear(const Color& clearColor, int x, int y, int w, int h); - void blit(VGContext* context, const Image* src, int sx, int sy, int dx, int dy, int w, int h, Array* scissors = NULL, bool dither = false); //throws bad_alloc - - RI_INLINE static const void* incrementPointer(const void* ptr, int bpp, RIint32 x); - RI_INLINE static void* calculateAddress(const void* basePtr, int bpp, int x, int y, int stride); - - static RI_INLINE RIuint32 readPackedPixelFromAddress(const void *ptr, int bpp, int x); - static RI_INLINE void writePackedPixelToAddress(void* ptr, int bpp, int x, RIuint32 packedColor); - - RI_INLINE RIuint32 readPackedPixel(int x, int y) const; - Color readPixel(int x, int y) const; - RI_INLINE void writePackedPixelToAddress(void* ptr, int x, RIuint32 packedColor); - void writePackedPixel(int x, int y, RIuint32 packedColor); - void writePixel(int x, int y, const Color& c); - - void fillPacked(RIuint32 packedColor); - - static RI_INLINE void fillPackedPixels(void* data, int bpp, int x, int y, int stride, int nPixels, RIuint32 packedColor); - RI_INLINE void fillPackedPixels(int x, int y, int nPixels, RIuint32 packedColor); - RI_INLINE void fillPackedRectangle(int x0, int y0, int width, int height, RIuint32 packedColor); - - void writeFilteredPixel(int x, int y, const Color& c, VGbitfield channelMask); - - RIfloat readMaskPixel(int x, int y) const; //can read any image format - void writeMaskPixel(int x, int y, RIfloat m); //can write only to VG_A_x - - Color resample(RIfloat x, RIfloat y, const Matrix3x3& surfaceToImage, VGImageQuality quality, VGTilingMode tilingMode, const Color& tileFillColor); //throws bad_alloc - void makeMipMaps(); //throws bad_alloc - - void colorMatrix(const Image& src, const RIfloat* matrix, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask); - void convolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernel, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask); - void separableConvolve(const Image& src, int kernelWidth, int kernelHeight, int shiftX, int shiftY, const RIint16* kernelX, const RIint16* kernelY, RIfloat scale, RIfloat bias, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask); - void gaussianBlur(const Image& src, RIfloat stdDeviationX, RIfloat stdDeviationY, VGTilingMode tilingMode, const Color& edgeFillColor, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask); - void lookup(const Image& src, const RIuint8 * redLUT, const RIuint8 * greenLUT, const RIuint8 * blueLUT, const RIuint8 * alphaLUT, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask); - void lookupSingle(const Image& src, const RIuint32 * lookupTable, VGImageChannel sourceChannel, bool outputLinear, bool outputPremultiplied, bool filterFormatLinear, bool filterFormatPremultiplied, VGbitfield channelMask); - - RI_INLINE static int descriptorToStride(const Color::Descriptor& desc, int width) { return (width*desc.bitsPerPixel+7)/8; }; - - void getStorageOffset(int& x, int& y) const { x = m_storageOffsetX; y = m_storageOffsetY; } - -private: - Image(const Image&); //!< Not allowed. - void operator=(const Image&); //!< Not allowed. - -#if defined(RI_DEBUG) - bool ptrInImage(const void* ptr) const; -#endif - Color readTexel(int u, int v, int level, VGTilingMode tilingMode, const Color& tileFillColor) const; - - Color::Descriptor m_desc; - int m_width; - int m_height; - VGbitfield m_allowedQuality; - int m_inUse; - int m_stride; - RIuint8* m_data; - int m_referenceCount; - bool m_ownsData; - Image* m_parent; - int m_storageOffsetX; - int m_storageOffsetY; - bool m_unsafeData; // Data may contain incorrect pixel data - -#ifndef RI_COMPILE_LLVM_BYTECODE - -#endif /* RI_COMPILE_LLVM_BYTECODE */ -}; - -#if defined(RI_DEBUG) -RI_INLINE bool Image::ptrInImage(const void* ptr) const -{ - RIuint8* p = (RIuint8*)ptr; - - if (p < m_data) return false; - if (p >= (m_data + m_height * m_stride)) return false; - return true; -} -#endif - -RI_INLINE const void* Image::incrementPointer(const void* ptr, int bpp, int x) -{ - if (bpp >= 8) - return (((RIuint8*)ptr) + (bpp >> 3)); - // Increment the pointer only when the byte is actually about to change. - int mask; - if (bpp == 4) - mask = 1; - else if (bpp == 2) - mask = 3; - else - mask = 7; - if ((x & mask) == mask) - return ((RIuint8*)ptr + 1); - return ptr; -} - -RI_INLINE void* Image::calculateAddress(const void* basePtr, int bpp, int x, int y, int stride) -{ - if (bpp >= 8) - { - return (void*)((RIuint8*)basePtr + y * stride + x * (bpp >> 3)); - } else - { - // 4, 2, or 1 bits per pixel - RI_ASSERT(bpp == 4 || bpp == 2 || bpp == 1); - return (void*)((RIuint8*)basePtr + y * stride + ((x * bpp) >> 3)); - } -} - -RI_INLINE RIuint32 Image::readPackedPixel(int x, int y) const -{ - RI_ASSERT(m_data); - RI_ASSERT(x >= 0 && x < m_width); - RI_ASSERT(y >= 0 && y < m_height); - RI_ASSERT(m_referenceCount > 0); - - RIuint32 p = 0; - - void* ptr = Image::calculateAddress(m_data, m_desc.bitsPerPixel, x+m_storageOffsetX, y+m_storageOffsetY, m_stride); - p = readPackedPixelFromAddress(ptr, m_desc.bitsPerPixel, x+m_storageOffsetX); - - return p; -} - - -RI_INLINE void Image::writePackedPixelToAddress(void* ptr, int bpp, int x, RIuint32 packedColor) -{ - // \note packedColor must contain the whole data (including < 8 bpp data)? - switch(bpp) - { - case 32: - { - RIuint32* s = ((RIuint32*)ptr); - *s = (RIuint32)packedColor; - break; - } - - case 16: - { - RIuint16* s = ((RIuint16*)ptr); - *s = (RIuint16)packedColor; - break; - } - - case 8: - { - RIuint8* s = ((RIuint8*)ptr); - *s = (RIuint8)packedColor; - break; - } - case 4: - { - RIuint8* s = ((RIuint8*)ptr); - *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2)))); - break; - } - - case 2: - { - RIuint8* s = ((RIuint8*)ptr); - *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1)))); - break; - } - - default: - { - RI_ASSERT(bpp == 1); - RIuint8* s = ((RIuint8*)ptr); - *s = (RIuint8)((packedColor << (x&7)) | ((unsigned int)*s & ~(0x1 << (x&7)))); - break; - } - } - // m_mipmapsValid = false; // \note Will never do this, must be handled outside this class somehow! -} - -/** - * \brief Write packed pixel into address. - * \param x Which x-coordinate (starting from the start of the scanline - * pointed to) is addressed? This is only required for formats - * that have less than 8 bpp. - */ -void Image::writePackedPixelToAddress(void* address, int x, RIuint32 packedColor) -{ - writePackedPixelToAddress(address, m_desc.bitsPerPixel, x, packedColor); -} - -/** - * \brief Read a packed pixel from a given address. Notice the use of param x! - * \param x Check which part of byte to return if bpp < 8 - */ -RI_INLINE RIuint32 Image::readPackedPixelFromAddress(const void *ptr, int bpp, int x) -{ - switch(bpp) - { - case 32: - { - RIuint32* s = (RIuint32*)ptr; - return *s; - } - - case 16: - { - RIuint16* s = (RIuint16*)ptr; - return (RIuint32)*s; - } - - case 8: - { - RIuint8* s = (RIuint8*)ptr; - return (RIuint32)*s; - } - case 4: - { - RIuint8* s = ((RIuint8*)ptr); - return (RIuint32)(*s >> ((x&1)<<2)) & 0xf; - } - - case 2: - { - RIuint8* s = ((RIuint8*)ptr); - return (RIuint32)(*s >> ((x&3)<<1)) & 0x3; - } - - default: - { - RI_ASSERT(bpp == 1); - RIuint8* s = ((RIuint8*)ptr); - return (RIuint32)(*s >> (x&7)) & 0x1; - } - } -} - -RI_INLINE void Image::writePackedPixel(int x, int y, RIuint32 packedColor) -{ - RI_ASSERT(m_data); - RI_ASSERT(x >= 0 && x < m_width); - RI_ASSERT(y >= 0 && y < m_height); - RI_ASSERT(m_referenceCount > 0); - - x += m_storageOffsetX; - y += m_storageOffsetY; - - RIuint8* scanline = m_data + y * m_stride; - switch(m_desc.bitsPerPixel) - { - case 32: - { - RIuint32* s = ((RIuint32*)scanline) + x; - *s = (RIuint32)packedColor; - break; - } - - case 16: - { - RIuint16* s = ((RIuint16*)scanline) + x; - *s = (RIuint16)packedColor; - break; - } - - case 8: - { - RIuint8* s = ((RIuint8*)scanline) + x; - *s = (RIuint8)packedColor; - break; - } - case 4: - { - RIuint8* s = ((RIuint8*)scanline) + (x>>1); - *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2)))); - break; - } - - case 2: - { - RIuint8* s = ((RIuint8*)scanline) + (x>>2); - *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1)))); - break; - } - - default: - { - RI_ASSERT(m_desc.bitsPerPixel == 1); - RIuint8* s = ((RIuint8*)scanline) + (x>>3); - *s = (RIuint8)((packedColor << (x&7)) | ((unsigned int)*s & ~(0x1 << (x&7)))); - break; - } - } - //m_mipmapsValid = false; -} - - -/** - * \brief Unsafe static method for setting image pixels - */ -RI_INLINE void Image::fillPackedPixels(void* data, int bpp, int x, int y, int stride, int nPixels, RIuint32 packedColor) -{ - RI_ASSERT(nPixels > 0); - RI_ASSERT(data); - - RIuint8* scanline = (RIuint8*)data + y * stride; - - switch(bpp) - { - case 32: - { - RIuint32* s = ((RIuint32*)scanline) + x; - - for (int i = 0; i < nPixels; i++) - s[i] = packedColor; - - break; - } - - case 16: - { - RIuint16* s = ((RIuint16*)scanline) + x; - - for (int i = 0; i < nPixels; i++) - s[i] = (RIuint16)packedColor; - - break; - } - - case 8: - { - RIuint8* s = ((RIuint8*)scanline) + x; - - for (int i = 0; i < nPixels; i++) - s[i] = (RIuint8)packedColor; - - break; - } - case 4: - { - //RI_ASSERT((packedColor & 0xf) == 0); - //packedColor &= 0xf; - RIuint8* s = ((RIuint8*)scanline) + (x>>1); - if (x & 1) - { - *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2)))); - s++; - x++; - nPixels--; - } - RI_ASSERT(!(x&1)); - - int c = nPixels / 2; - RIuint8 bytePacked = packedColor | (packedColor << 4); - while (c) - { - *s++ = bytePacked; - c--; - x+=2; - } - nPixels &= 1; - - if (nPixels) - { - *s = (RIuint8)((packedColor << ((x&1)<<2)) | ((unsigned int)*s & ~(0xf << ((x&1)<<2)))); - s++; - x++; - nPixels--; - } - RI_ASSERT(nPixels == 0); - break; - } - - case 2: - { - // This case should not be needed! - RI_ASSERT(false); - RIuint8* s = ((RIuint8*)scanline) + (x>>2); - *s = (RIuint8)((packedColor << ((x&3)<<1)) | ((unsigned int)*s & ~(0x3 << ((x&3)<<1)))); - break; - } - - default: - { - RI_ASSERT(bpp == 1); - RIuint8* s = ((RIuint8*)scanline) + (x>>3); - // \todo Get this as input instead? - RI_ASSERT(packedColor == 1 || packedColor == 0); - RIuint8 fullyPacked = (RIuint8)(-(RIint8)packedColor); - - if (x & 7) - { - // Handle the first byte: - RIuint8 o = *s; - int a = x&7; - RI_ASSERT(a>=1); - int b = RI_INT_MIN(a + nPixels, 8); - RI_ASSERT(b > a); - RIuint8 emask = (1u << b)-1; - RIuint8 mask = (0xffu<0); - RI_ASSERT(mask<=254); - *s++ = (o&(~mask))|(fullyPacked & mask); - nPixels -= 8-(x&7); - x += 8-(x&7); - } - - if (nPixels < 0) - return; - - RI_ASSERT(!(x&1)); - - int c = nPixels/8; - while (c) - { - *s++ = fullyPacked; - c--; - x+=8; - } - nPixels -= ((nPixels/8) * 8); - - - if (nPixels) - { - RI_ASSERT((x&7) == 0); - - RIuint8 o = *s; - int b = nPixels; - RI_ASSERT(b<=7); - RIuint8 mask = (1u<getDescriptor(); } - RI_INLINE int getWidth() const { return m_width; } - RI_INLINE int getHeight() const { return m_height; } - RI_INLINE int getNumSamples() const { return m_numSamples; } - RI_INLINE void addReference() { m_referenceCount++; } - RI_INLINE int removeReference() { m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; } - RI_INLINE int isInUse() const { return m_image->isInUse(); } - RI_INLINE bool isInUse(Image* image) const { return image == m_image ? true : false; } - - void clear(const Color& clearColor, int x, int y, int w, int h, const Array* scissors = NULL); -#if 0 - // Currently does not support msaa surfaces - void blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h); //throws bad_alloc - void blit(const Image& src, int sx, int sy, int dx, int dy, int w, int h, const Array& 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& scissors); //throws bad_alloc -#endif - void mask(DynamicBlitter& blitter, const Image* src, VGMaskOperation operation, int x, int y, int w, int h); - - RI_INLINE void writePackedPixelToAddress(void* address, int x, RIuint32 p) { m_image->writePackedPixelToAddress(address, x, p); } - RI_INLINE RIuint32 readPackedSample(int x, int y, int sample) const { return m_image->readPackedPixel(x*m_numSamples+sample, y); } - RI_INLINE Color readSample(int x, int y, int sample) const { return m_image->readPixel(x*m_numSamples+sample, y); } - RI_INLINE void writePackedSample(int x, int y, int sample, RIuint32 p) { m_image->writePackedPixel(x*m_numSamples+sample, y, p); } - RI_INLINE void writeSample(int x, int y, int sample, const Color& c) { m_image->writePixel(x*m_numSamples+sample, y, c); } - RI_INLINE void fillPackedSamples(int x, int y, int nPixels, RIuint32 p); - - RIfloat readMaskCoverage(int x, int y) const; - void writeMaskCoverage(int x, int y, RIfloat m); - unsigned int readMaskMSAA(int x, int y) const; - void writeMaskMSAA(int x, int y, unsigned int m); - - RIuint32 FSAAResolvePacked(int x, int y) const; - Color FSAAResolve(int x, int y) const; //for fb=>img: vgGetPixels, vgReadPixels - -private: - Surface(const Surface&); //!< Not allowed. - void operator=(const Surface&); //!< Not allowed. - - struct ScissorEdge - { - ScissorEdge() : x(0), miny(0), maxy(0), direction(0) {} - bool operator<(const ScissorEdge& e) const { return x < e.x; } - int x; - int miny; - int maxy; - int direction; //1 start, -1 end - }; - - int m_width; - int m_height; - int m_numSamples; - int m_referenceCount; - -public: - // \todo TERO: Broke the design of this by making it public, make proper - // friend/etc. C++ accessor for optimized pixel-pipelines. Combine with the - // removal of (remnants of) the FSAA support. - Image* m_image; -}; - -RI_INLINE void Surface::fillPackedSamples(int x, int y, int nPixels, RIuint32 p) -{ - m_image->fillPackedPixels(x, y, nPixels, p); -} - - -/*-------------------------------------------------------------------*//*! -* \brief Drawable class for encapsulating color and mask buffers. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class Drawable -{ -public: - Drawable(const Color::Descriptor& desc, int width, int height, int numSamples, int maskBits); //throws bad_alloc - Drawable(Image* image, int maskBits); //throws bad_alloc - Drawable(const Color::Descriptor& desc, int width, int height, int stride, RIuint8* data, int maskBits); //throws bad_alloc - ~Drawable(); - - RI_INLINE const Color::Descriptor& getDescriptor() const { return m_color->getDescriptor(); } - RI_INLINE int getNumMaskBits() const { if(!m_mask) return 0; return m_mask->getDescriptor().alphaBits; } - RI_INLINE int getWidth() const { return m_color->getWidth(); } - RI_INLINE int getHeight() const { return m_color->getHeight(); } - RI_INLINE int getNumSamples() const { return m_color->getNumSamples(); } - RI_INLINE void addReference() { m_referenceCount++; } - RI_INLINE int removeReference() { m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; } - RI_INLINE int isInUse() const { return m_color->isInUse() || (m_mask && m_mask->isInUse()); } - RI_INLINE bool isInUse(Image* image) const { return m_color->isInUse(image) || (m_mask && m_mask->isInUse(image)); } - RI_INLINE Surface* getColorBuffer() const { return m_color; } - RI_INLINE Surface* getMaskBuffer() const { return m_mask; } - - void resize(VGContext* context, int newWidth, int newHeight); //throws bad_alloc -private: - Drawable(const Drawable&); //!< Not allowed. - void operator=(const Drawable&); //!< Not allowed. - - int m_referenceCount; - Surface* m_color; - Surface* m_mask; -}; - -//============================================================================================== - -} //namespace OpenVGRI - -//============================================================================================== - -#endif /* __RIIMAGE_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riMath.cpp --- a/hostsupport/hostopenvg/src/src/riMath.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,102 +0,0 @@ -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementation of non-inline matrix functions. - * \note - *//*-------------------------------------------------------------------*/ - -#include "riDefs.h" -#include "riMath.h" - -#if 0 -#include - -static void printMatrix(const Matrix3x3& m) -{ - // For tracing a bug in matrix inverse in release-builds. - for(int i = 0; i < 3; i++) - { - printf("[%.4f %.4f %.4f]\n", m[i][0], m[i][1], m[i][2]); - } -} - -#endif - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief Inverts a 3x3 matrix. Returns false if the matrix is singular. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool Matrix3x3::invert() -{ - // \todo Save computation on affine matrices? - bool affine = isAffine(); - RIfloat det00 = matrix[1][1]*matrix[2][2] - matrix[2][1]*matrix[1][2]; - RIfloat det01 = matrix[2][0]*matrix[1][2] - matrix[1][0]*matrix[2][2]; - RIfloat det02 = matrix[1][0]*matrix[2][1] - matrix[2][0]*matrix[1][1]; - - RIfloat d = matrix[0][0]*det00 + matrix[0][1]*det01 + matrix[0][2]*det02; - if( d == 0.0f ) return false; //singular, leave the matrix unmodified and return false - d = 1.0f / d; - - Matrix3x3 t; - - // \note There is some bug (in GCC?) in accessing matrix elements: If data - // is accessed like: t[i][j], then the following will produce incorrect - // resulst on optimized builds. If the data is accessed through t.matrix, - // then the output is correct. Debug build works correctly, and if print - // calls are inserted, the code also works correctly. The context to get - // this bug appear are fill paints (linear and radial gradient test - // functions). - - t.matrix[0][0] = d * det00; - t.matrix[1][0] = d * det01; - t.matrix[2][0] = d * det02; - //printf("t\n"); - //printMatrix(t); - t.matrix[0][1] = d * (matrix[2][1]*matrix[0][2] - matrix[0][1]*matrix[2][2]); - t.matrix[1][1] = d * (matrix[0][0]*matrix[2][2] - matrix[2][0]*matrix[0][2]); - t.matrix[2][1] = d * (matrix[2][0]*matrix[0][1] - matrix[0][0]*matrix[2][1]); - t.matrix[0][2] = d * (matrix[0][1]*matrix[1][2] - matrix[1][1]*matrix[0][2]); - t.matrix[1][2] = d * (matrix[1][0]*matrix[0][2] - matrix[0][0]*matrix[1][2]); - t.matrix[2][2] = d * (matrix[0][0]*matrix[1][1] - matrix[1][0]*matrix[0][1]); - if(affine) - t[2].set(0,0,1); //affine matrix stays affine - *this = t; - return true; -} - -//============================================================================================== - -} //namespace OpenVGRI diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riMath.h --- a/hostsupport/hostopenvg/src/src/riMath.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,452 +0,0 @@ -#ifndef __RIMATH_H -#define __RIMATH_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Math functions, Vector and Matrix classes. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef __RIDEFS_H -#include "riDefs.h" -#endif - -#include - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -RI_INLINE int RI_ISNAN(float a) -{ - RIfloatInt p; - p.f = a; - unsigned int exponent = (p.i>>23) & 0xff; - unsigned int mantissa = p.i & 0x7fffff; - if(exponent == 255 && mantissa) - return 1; - return 0; -} - -#if (RI_MANTISSA_BITS > 23) -#error RI_MANTISSA_BITS is greater than 23 -#elif (RI_EXPONENT_BITS > 8) -#error RI_EXPONENT_BITS is greater than 8 -#elif (RI_MANTISSA_BITS != 23) || (RI_EXPONENT_BITS != 8) - -class RIfloat -{ -public: - RIfloat() : v(0.0f) { removeBits(); } - RIfloat(float a) : v(a) { removeBits(); } - RIfloat(double a) : v((float)a) { removeBits(); } - RIfloat(int a) : v((float)a) { removeBits(); } - RIfloat(unsigned int a) : v((float)a) { removeBits(); } - RIfloat& operator=(const RIfloat &a) { v = a.v; removeBits(); return *this; } - RIfloat& operator+=(const RIfloat &a){ v += a.v; removeBits(); return *this; } - RIfloat& operator-=(const RIfloat &a){ v -= a.v; removeBits(); return *this; } - RIfloat& operator*=(const RIfloat &a){ v *= a.v; removeBits(); return *this; } - RIfloat& operator/=(const RIfloat &a){ v /= a.v; removeBits(); return *this; } - RIfloat operator-() const { return -v; } - operator float() const { return v; } - operator double() const { return (double)v; } - operator int() const { return (int)v; } - - friend RIfloat operator+(const RIfloat &a, const RIfloat &b); - friend RIfloat operator+(float a, const RIfloat &b); - friend RIfloat operator+(const RIfloat &a, float b); - friend RIfloat operator-(const RIfloat &a, const RIfloat &b); - friend RIfloat operator-(float a, const RIfloat &b); - friend RIfloat operator-(const RIfloat &a, float b); - friend RIfloat operator*(const RIfloat &a, const RIfloat &b); - friend RIfloat operator*(float a, const RIfloat &b); - friend RIfloat operator*(const RIfloat &a, float b); - friend RIfloat operator/(const RIfloat &a, const RIfloat &b); - friend RIfloat operator/(float a, const RIfloat &b); - friend RIfloat operator/(const RIfloat &a, float b); - - friend bool operator<(const RIfloat &a, const RIfloat &b); - friend bool operator<(float a, const RIfloat &b); - friend bool operator<(const RIfloat &a, float b); - friend bool operator>(const RIfloat &a, const RIfloat &b); - friend bool operator>(float a, const RIfloat &b); - friend bool operator>(const RIfloat &a, float b); - friend bool operator<=(const RIfloat &a, const RIfloat &b); - friend bool operator<=(float a, const RIfloat &b); - friend bool operator<=(const RIfloat &a, float b); - friend bool operator>=(const RIfloat &a, const RIfloat &b); - friend bool operator>=(float a, const RIfloat &b); - friend bool operator>=(const RIfloat &a, float b); - friend bool operator==(const RIfloat &a, const RIfloat &b); - friend bool operator==(float a, const RIfloat &b); - friend bool operator==(const RIfloat &a, float b); - friend bool operator!=(const RIfloat &a, const RIfloat &b); - friend bool operator!=(float a, const RIfloat &b); - friend bool operator!=(const RIfloat &a, float b); -private: - void removeBits() - { - RIfloatInt p; - p.f = v; - unsigned int exponent = (p.i>>23) & 0xff; - if(exponent == 0 || exponent == 255) - return; //zero, denormal, infinite, or NaN - - p.i &= ~((1<<(23-RI_MANTISSA_BITS))-1); - -#if (RI_EXPONENT_BITS != 8) - if (exponent > 127 + (1 << (RI_EXPONENT_BITS-1))) - exponent = 127 + (1 << (RI_EXPONENT_BITS-1)); - - if (exponent < 127 + 1 - (1 << (RI_EXPONENT_BITS-1))) - exponent = 127 + 1 - (1 << (RI_EXPONENT_BITS-1)); - - p.i &= ~(0xff<<23); - p.i |= exponent<<23; -#endif - v = p.f; - } - - float v; -}; - -RI_INLINE RIfloat operator+(const RIfloat &a, const RIfloat &b) { return RIfloat(a.v+b.v); } -RI_INLINE RIfloat operator+(float a, const RIfloat &b) { return RIfloat(a+b.v); } -RI_INLINE RIfloat operator+(const RIfloat &a, float b) { return RIfloat(a.v+b); } -RI_INLINE RIfloat operator-(const RIfloat &a, const RIfloat &b) { return RIfloat(a.v-b.v); } -RI_INLINE RIfloat operator-(float a, const RIfloat &b) { return RIfloat(a-b.v); } -RI_INLINE RIfloat operator-(const RIfloat &a, float b) { return RIfloat(a.v-b); } -RI_INLINE RIfloat operator*(const RIfloat &a, const RIfloat &b) { return RIfloat(a.v*b.v); } -RI_INLINE RIfloat operator*(float a, const RIfloat &b) { return RIfloat(a*b.v); } -RI_INLINE RIfloat operator*(const RIfloat &a, float b) { return RIfloat(a.v*b); } -RI_INLINE RIfloat operator/(const RIfloat &a, const RIfloat &b) { return RIfloat(a.v/b.v); } -RI_INLINE RIfloat operator/(float a, const RIfloat &b) { return RIfloat(a/b.v); } -RI_INLINE RIfloat operator/(const RIfloat &a, float b) { return RIfloat(a.v/b); } - -RI_INLINE bool operator<(const RIfloat &a, const RIfloat &b) { return a.v < b.v ? true : false; } -RI_INLINE bool operator<(float a, const RIfloat &b) { return a < b.v ? true : false; } -RI_INLINE bool operator<(const RIfloat &a, float b) { return a.v < b ? true : false; } -RI_INLINE bool operator>(const RIfloat &a, const RIfloat &b) { return a.v > b.v ? true : false; } -RI_INLINE bool operator>(float a, const RIfloat &b) { return a > b.v ? true : false; } -RI_INLINE bool operator>(const RIfloat &a, float b) { return a.v > b ? true : false; } -RI_INLINE bool operator<=(const RIfloat &a, const RIfloat &b) { return a.v <= b.v ? true : false; } -RI_INLINE bool operator<=(float a, const RIfloat &b) { return a <= b.v ? true : false; } -RI_INLINE bool operator<=(const RIfloat &a, float b) { return a.v <= b ? true : false; } -RI_INLINE bool operator>=(const RIfloat &a, const RIfloat &b) { return a.v >= b.v ? true : false; } -RI_INLINE bool operator>=(float a, const RIfloat &b) { return a >= b.v ? true : false; } -RI_INLINE bool operator>=(const RIfloat &a, float b) { return a.v >= b ? true : false; } -RI_INLINE bool operator==(const RIfloat &a, const RIfloat &b) { return a.v == b.v ? true : false; } -RI_INLINE bool operator==(float a, const RIfloat &b) { return a == b.v ? true : false; } -RI_INLINE bool operator==(const RIfloat &a, float b) { return a.v == b ? true : false; } -RI_INLINE bool operator!=(const RIfloat &a, const RIfloat &b) { return a.v != b.v ? true : false; } -RI_INLINE bool operator!=(float a, const RIfloat &b) { return a != b.v ? true : false; } -RI_INLINE bool operator!=(const RIfloat &a, float b) { return a.v != b ? true : false; } - -#else -typedef float RIfloat; -#endif - -#define RI_PI 3.141592654f - -RI_INLINE RIfloat RI_FRAC(RIfloat f) { return f - (RIfloat)(int)f; } -RI_INLINE int RI_ROUND_TO_INT(RIfloat v) { return (v >= 0.0f) ? (int)(v+0.5f) : (int)(v-0.5f); } -RI_INLINE RIfloat RI_MAX(RIfloat a, RIfloat b) { return (a > b) ? a : b; } -RI_INLINE int RI_MAX(int a, int b) { return (a > b) ? a : b; } -RI_INLINE RIfloat RI_MIN(RIfloat a, RIfloat b) { return (a < b) ? a : b; } -RI_INLINE int RI_MIN(int a, int b) { return (a < b) ? a : b; } -RI_INLINE RIfloat RI_CLAMP(RIfloat a, RIfloat l, RIfloat h) { if(RI_ISNAN(a)) return l; RI_ASSERT(l <= h); return (a < l) ? l : (a > h) ? h : a; } -RI_INLINE int RI_CEIL(RIfloat a) {return (int)ceilf(a);} -RI_INLINE int RI_FLOOR(RIfloat a) { return (int)floorf(a); } -RI_INLINE void RI_SWAP(RIfloat &a, RIfloat &b) { RIfloat tmp = a; a = b; b = tmp; } -RI_INLINE RIfloat RI_ABS(RIfloat a) { return (a < 0.0f) ? -a : a; } -RI_INLINE RIfloat RI_SQR(RIfloat a) { return a * a; } -RI_INLINE RIfloat RI_DEG_TO_RAD(RIfloat a) { return a * RI_PI / 180.0f; } -RI_INLINE RIfloat RI_RAD_TO_DEG(RIfloat a) { return a * 180.0f/ RI_PI; } -RI_INLINE RIfloat RI_MOD(RIfloat a, RIfloat b) { if(RI_ISNAN(a) || RI_ISNAN(b)) return 0.0f; RI_ASSERT(b >= 0.0f); if(b == 0.0f) return 0.0f; RIfloat f = (RIfloat)fmod(a, b); if(f < 0.0f) f += b; RI_ASSERT(f >= 0.0f && f <= b); return f; } - -#define RI_ANY_SWAP(type, a, b) {type tmp = a; a = b; b = tmp;} - -RI_INLINE void RI_INT16_SWAP(RIint16 &a, RIint16 &b) {RIint16 tmp = a; a = b; b = tmp;} -RI_INLINE int RI_INT_ABS(int a) { return (a >= 0) ? a : -a; } -RI_INLINE int RI_INT_MAX(int a, int b) { return (a > b) ? a : b; } -RI_INLINE int RI_INT_MIN(int a, int b) { return (a < b) ? a : b; } -RI_INLINE int RI_INT_CLAMP(int a, int l, int h) { return (a < l) ? l : (a > h) ? h : a; } -RI_INLINE void RI_INT_SWAP(int &a, int &b) { int tmp = a; a = b; b = tmp; } -RI_INLINE int RI_INT_MOD(int a, int b) { RI_ASSERT(b >= 0); if(!b) return 0; int i = a % b; if(i < 0) i += b; RI_ASSERT(i >= 0 && i < b); return i; } -RI_INLINE int RI_INT_ADDSATURATE(int a, int b) { RI_ASSERT(b >= 0); int r = a + b; return (r >= a) ? r : RI_INT32_MAX; } - -RI_INLINE RIfloat validateFloat(RIfloat f) -{ - //this function is used for all floating point input values - if(RI_ISNAN(f)) return 0.0f; //convert NaN to zero - return RI_CLAMP(f, -RI_FLOAT_MAX, RI_FLOAT_MAX); //clamp +-inf to +-RIfloat max -} - - - -RI_INLINE int RI_SHL(int a, int sh) -{ - RI_ASSERT(sh >= 0 && sh <= 31); - int r = a << sh; - RI_ASSERT(a >= 0 ? (r >= 0) : (r < 0)); - return r; -} - -RI_INLINE int RI_SAT_SHL(RIint32 a, int sh) -{ - RI_ASSERT(sh >= 0 && sh <= 31); - - RIint64 r = ((RIint64)a) << sh; - - if (r > 0x7fffffff) - return 0x7fffffff; - else if (r < (long long)(int)0x80000000) - return 0x80000000; - - return (RIint32)r; -} - -RI_INLINE int RI_SHR(int a, int sh) -{ - RI_ASSERT(sh >= 0 && sh <= 31); - int r = a >> sh; - return r; -} - -RI_INLINE RIfloat RI_FLOAT_TO_FX(RIfloat f, unsigned int n) { return (RIfloat)RI_ROUND_TO_INT(f * (RIfloat)RI_SHL(1, n)); } - -class Matrix3x3; -class Vector2; -class Vector3; - -//============================================================================================== - -//MatrixRxC, R = number of rows, C = number of columns -//indexing: matrix[row][column] -//Matrix3x3 inline functions cannot be inside the class because Vector3 is not defined yet when Matrix3x3 is defined - -class Matrix3x3 -{ -public: - RI_INLINE Matrix3x3 (); //initialized to identity - RI_INLINE Matrix3x3 ( const Matrix3x3& m ); - RI_INLINE Matrix3x3 ( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 ); - RI_INLINE ~Matrix3x3 (); - RI_INLINE Matrix3x3& operator= ( const Matrix3x3& m ); - RI_INLINE Vector3& operator[] ( int i ); //returns a row vector - RI_INLINE const Vector3& operator[] ( int i ) const; - RI_INLINE void set ( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 ); - RI_INLINE const Vector3 getRow ( int i ) const; - RI_INLINE const Vector3 getColumn ( int i ) const; - RI_INLINE void setRow ( int i, const Vector3& v ); - RI_INLINE void setColumn ( int i, const Vector3& v ); - RI_INLINE void operator*= ( const Matrix3x3& m ); - RI_INLINE void operator*= ( RIfloat f ); - RI_INLINE void operator+= ( const Matrix3x3& m ); - RI_INLINE void operator-= ( const Matrix3x3& m ); - RI_INLINE const Matrix3x3 operator- () const; - RI_INLINE void identity (); - RI_INLINE void transpose (); - bool invert (); //if the matrix is singular, returns false and leaves it unmodified - RI_INLINE RIfloat det () const; - RI_INLINE bool isAffine () const; - RI_INLINE void assertValid () const; - RI_INLINE void validate (); - -private: - RIfloat matrix[3][3]; -}; - -//============================================================================================== - -class Vector2 -{ -public: - RI_INLINE Vector2 () : x(0.0f), y(0.0f) {} - RI_INLINE Vector2 ( const Vector2& v ) : x(v.x), y(v.y) {} - RI_INLINE Vector2 ( RIfloat fx, RIfloat fy ) : x(fx), y(fy) {} - RI_INLINE ~Vector2 () {} - RI_INLINE Vector2& operator= ( const Vector2& v ) { x = v.x; y = v.y; return *this; } - RI_INLINE RIfloat& operator[] ( int i ) { RI_ASSERT(i>=0&&i<2); return (&x)[i]; } - RI_INLINE const RIfloat& operator[] ( int i ) const { RI_ASSERT(i>=0&&i<2); return (&x)[i]; } - RI_INLINE void set ( RIfloat fx, RIfloat fy ) { x = fx; y = fy; } - RI_INLINE void operator*= ( RIfloat f ) { x *= f; y *= f; } - RI_INLINE void operator+= ( const Vector2& v ) { x += v.x; y += v.y; } - RI_INLINE void operator-= ( const Vector2& v ) { x -= v.x; y -= v.y; } - RI_INLINE const Vector2 operator- () const { return Vector2(-x,-y); } - //if the vector is zero, returns false and leaves it unmodified - RI_INLINE bool normalize () { double l = (double)x*(double)x+(double)y*(double)y; if( l == 0.0 ) return false; l = 1.0 / sqrt(l); x = (RIfloat)((double)x * l); y = (RIfloat)((double)y * l); return true; } - RI_INLINE RIfloat length () const { return (RIfloat)sqrt((double)x*(double)x+(double)y*(double)y); } - RI_INLINE void scale ( const Vector2& v ) { x *= v.x; y *= v.y; } //component-wise scale - RI_INLINE void negate () { x = -x; y = -y; } - - RIfloat x,y; -}; - -//============================================================================================== - -class Vector3 -{ -public: - RI_INLINE Vector3 () : x(0.0f), y(0.0f), z(0.0f) {} - RI_INLINE Vector3 ( const Vector3& v ) : x(v.x), y(v.y), z(v.z) {} - RI_INLINE Vector3 ( RIfloat fx, RIfloat fy, RIfloat fz ) : x(fx), y(fy), z(fz) {} - RI_INLINE ~Vector3 () {} - RI_INLINE Vector3& operator= ( const Vector3& v ) { x = v.x; y = v.y; z = v.z; return *this; } - RI_INLINE RIfloat& operator[] ( int i ) { RI_ASSERT(i>=0&&i<3); return (&x)[i]; } - RI_INLINE const RIfloat& operator[] ( int i ) const { RI_ASSERT(i>=0&&i<3); return (&x)[i]; } - RI_INLINE void set ( RIfloat fx, RIfloat fy, RIfloat fz ){ x = fx; y = fy; z = fz; } - RI_INLINE void operator*= ( RIfloat f ) { x *= f; y *= f; z *= f; } - RI_INLINE void operator+= ( const Vector3& v ) { x += v.x; y += v.y; z += v.z; } - RI_INLINE void operator-= ( const Vector3& v ) { x -= v.x; y -= v.y; z -= v.z; } - RI_INLINE const Vector3 operator- () const { return Vector3(-x,-y,-z); } - //if the vector is zero, returns false and leaves it unmodified - RI_INLINE bool normalize () { double l = (double)x*(double)x+(double)y*(double)y+(double)z*(double)z; if( l == 0.0 ) return false; l = 1.0 / sqrt(l); x = (RIfloat)((double)x * l); y = (RIfloat)((double)y * l); z = (RIfloat)((double)z * l); return true; } - RI_INLINE RIfloat length () const { return (RIfloat)sqrt((double)x*(double)x+(double)y*(double)y+(double)z*(double)z); } - RI_INLINE void scale ( const Vector3& v ) { x *= v.x; y *= v.y; z *= v.z; } //component-wise scale - RI_INLINE void negate () { x = -x; y = -y; z = -z; } - - RIfloat x,y,z; -}; - -//============================================================================================== - -//Vector2 global functions -RI_INLINE bool operator== ( const Vector2& v1, const Vector2& v2 ) { return (v1.x == v2.x) && (v1.y == v2.y); } -RI_INLINE bool operator!= ( const Vector2& v1, const Vector2& v2 ) { return (v1.x != v2.x) || (v1.y != v2.y); } -RI_INLINE bool isEqual ( const Vector2& v1, const Vector2& v2, RIfloat epsilon ) { return RI_SQR(v2.x-v1.x) + RI_SQR(v2.y-v1.y) <= epsilon*epsilon; } -RI_INLINE bool isZero ( const Vector2& v ) { return (v.x == 0.0f) && (v.y == 0.0f); } -RI_INLINE const Vector2 operator* ( RIfloat f, const Vector2& v ) { return Vector2(v.x*f,v.y*f); } -RI_INLINE const Vector2 operator* ( const Vector2& v, RIfloat f ) { return Vector2(v.x*f,v.y*f); } -RI_INLINE const Vector2 operator+ ( const Vector2& v1, const Vector2& v2 ) { return Vector2(v1.x+v2.x, v1.y+v2.y); } -RI_INLINE const Vector2 operator- ( const Vector2& v1, const Vector2& v2 ) { return Vector2(v1.x-v2.x, v1.y-v2.y); } -RI_INLINE RIfloat dot ( const Vector2& v1, const Vector2& v2 ) { return v1.x*v2.x+v1.y*v2.y; } -//if v is a zero vector, returns a zero vector -RI_INLINE const Vector2 normalize ( const Vector2& v ) { double l = (double)v.x*(double)v.x+(double)v.y*(double)v.y; if( l != 0.0 ) l = 1.0 / sqrt(l); return Vector2((RIfloat)((double)v.x * l), (RIfloat)((double)v.y * l)); } -//if onThis is a zero vector, returns a zero vector -RI_INLINE const Vector2 project ( const Vector2& v, const Vector2& onThis ) { RIfloat l = dot(onThis,onThis); if( l != 0.0f ) l = dot(v, onThis)/l; return onThis * l; } -RI_INLINE const Vector2 lerp ( const Vector2& v1, const Vector2& v2, RIfloat ratio ) { return v1 + ratio * (v2 - v1); } -RI_INLINE const Vector2 scale ( const Vector2& v1, const Vector2& v2 ) { return Vector2(v1.x*v2.x, v1.y*v2.y); } -//matrix * column vector. The input vector2 is implicitly expanded to (x,y,1) -RI_INLINE const Vector2 affineTransform( const Matrix3x3& m, const Vector2& v ) { RI_ASSERT(m.isAffine()); return Vector2(v.x * m[0][0] + v.y * m[0][1] + m[0][2], v.x * m[1][0] + v.y * m[1][1] + m[1][2]); } -//matrix * column vector. The input vector2 is implicitly expanded to (x,y,0) -RI_INLINE const Vector2 affineTangentTransform(const Matrix3x3& m, const Vector2& v) { RI_ASSERT(m.isAffine()); return Vector2(v.x * m[0][0] + v.y * m[0][1], v.x * m[1][0] + v.y * m[1][1]); } -RI_INLINE const Vector2 perpendicularCW(const Vector2& v) { return Vector2(v.y, -v.x); } -RI_INLINE const Vector2 perpendicularCCW(const Vector2& v) { return Vector2(-v.y, v.x); } -RI_INLINE const Vector2 perpendicular(const Vector2& v, bool cw) { if(cw) return Vector2(v.y, -v.x); return Vector2(-v.y, v.x); } - -//============================================================================================== - -//Vector3 global functions -RI_INLINE bool operator== ( const Vector3& v1, const Vector3& v2 ) { return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); } -RI_INLINE bool operator!= ( const Vector3& v1, const Vector3& v2 ) { return (v1.x != v2.x) || (v1.y != v2.y) || (v1.z != v2.z); } -RI_INLINE bool isEqual ( const Vector3& v1, const Vector3& v2, RIfloat epsilon ) { return RI_SQR(v2.x-v1.x) + RI_SQR(v2.y-v1.y) + RI_SQR(v2.z-v1.z) <= epsilon*epsilon; } -RI_INLINE const Vector3 operator* ( RIfloat f, const Vector3& v ) { return Vector3(v.x*f,v.y*f,v.z*f); } -RI_INLINE const Vector3 operator* ( const Vector3& v, RIfloat f ) { return Vector3(v.x*f,v.y*f,v.z*f); } -RI_INLINE const Vector3 operator+ ( const Vector3& v1, const Vector3& v2 ) { return Vector3(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z); } -RI_INLINE const Vector3 operator- ( const Vector3& v1, const Vector3& v2 ) { return Vector3(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z); } -RI_INLINE RIfloat dot ( const Vector3& v1, const Vector3& v2 ) { return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z; } -RI_INLINE const Vector3 cross ( const Vector3& v1, const Vector3& v2 ) { return Vector3( v1.y*v2.z-v1.z*v2.y, v1.z*v2.x-v1.x*v2.z, v1.x*v2.y-v1.y*v2.x ); } -//if v is a zero vector, returns a zero vector -RI_INLINE const Vector3 normalize ( const Vector3& v ) { double l = (double)v.x*(double)v.x+(double)v.y*(double)v.y+(double)v.z*(double)v.z; if( l != 0.0 ) l = 1.0 / sqrt(l); return Vector3((RIfloat)((double)v.x * l), (RIfloat)((double)v.y * l), (RIfloat)((double)v.z * l)); } -RI_INLINE const Vector3 lerp ( const Vector3& v1, const Vector3& v2, RIfloat ratio ) { return v1 + ratio * (v2 - v1); } -RI_INLINE const Vector3 scale ( const Vector3& v1, const Vector3& v2 ) { return Vector3(v1.x*v2.x, v1.y*v2.y, v1.z*v2.z); } - -//============================================================================================== - -//matrix * column vector -RI_INLINE const Vector3 operator* ( const Matrix3x3& m, const Vector3& v) { return Vector3( v.x*m[0][0]+v.y*m[0][1]+v.z*m[0][2], v.x*m[1][0]+v.y*m[1][1]+v.z*m[1][2], v.x*m[2][0]+v.y*m[2][1]+v.z*m[2][2] ); } - -//============================================================================================== - -//Matrix3x3 global functions -RI_INLINE bool operator== ( const Matrix3x3& m1, const Matrix3x3& m2 ) { for(int i=0;i<3;i++) for(int j=0;j<3;j++) if( m1[i][j] != m2[i][j] ) return false; return true; } -RI_INLINE bool operator!= ( const Matrix3x3& m1, const Matrix3x3& m2 ) { return !(m1 == m2); } -RI_INLINE const Matrix3x3 operator* ( const Matrix3x3& m1, const Matrix3x3& m2 ) { Matrix3x3 t; for(int i=0;i<3;i++) for(int j=0;j<3;j++) t[i][j] = m1[i][0] * m2[0][j] + m1[i][1] * m2[1][j] + m1[i][2] * m2[2][j]; return t; } -RI_INLINE const Matrix3x3 operator* ( RIfloat f, const Matrix3x3& m ) { Matrix3x3 t(m); t *= f; return t; } -RI_INLINE const Matrix3x3 operator* ( const Matrix3x3& m, RIfloat f ) { Matrix3x3 t(m); t *= f; return t; } -RI_INLINE const Matrix3x3 operator+ ( const Matrix3x3& m1, const Matrix3x3& m2 ) { Matrix3x3 t(m1); t += m2; return t; } -RI_INLINE const Matrix3x3 operator- ( const Matrix3x3& m1, const Matrix3x3& m2 ) { Matrix3x3 t(m1); t -= m2; return t; } -RI_INLINE const Matrix3x3 transpose ( const Matrix3x3& m ) { Matrix3x3 t(m); t.transpose(); return t; } -// if the matrix is singular, returns it unmodified -RI_INLINE const Matrix3x3 invert ( const Matrix3x3& m ) { Matrix3x3 t(m); t.invert(); return t; } - -//============================================================================================== - -//Matrix3x3 inline functions (cannot be inside the class because Vector3 is not defined yet when Matrix3x3 is defined) -RI_INLINE Matrix3x3::Matrix3x3 () { identity(); } -RI_INLINE Matrix3x3::Matrix3x3 ( const Matrix3x3& m ) { *this = m; } -RI_INLINE Matrix3x3::Matrix3x3 ( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 ) { set(m00,m01,m02,m10,m11,m12,m20,m21,m22); } -RI_INLINE Matrix3x3::~Matrix3x3 () {} -RI_INLINE Matrix3x3& Matrix3x3::operator= ( const Matrix3x3& m ) { for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] = m.matrix[i][j]; return *this; } -RI_INLINE Vector3& Matrix3x3::operator[] ( int i ) { RI_ASSERT(i>=0&&i<3); return (Vector3&)matrix[i][0]; } -RI_INLINE const Vector3& Matrix3x3::operator[] ( int i ) const { RI_ASSERT(i>=0&&i<3); return (const Vector3&)matrix[i][0]; } -RI_INLINE void Matrix3x3::set ( RIfloat m00, RIfloat m01, RIfloat m02, RIfloat m10, RIfloat m11, RIfloat m12, RIfloat m20, RIfloat m21, RIfloat m22 ) { matrix[0][0] = m00; matrix[0][1] = m01; matrix[0][2] = m02; matrix[1][0] = m10; matrix[1][1] = m11; matrix[1][2] = m12; matrix[2][0] = m20; matrix[2][1] = m21; matrix[2][2] = m22; } -RI_INLINE const Vector3 Matrix3x3::getRow ( int i ) const { RI_ASSERT(i>=0&&i<3); return Vector3(matrix[i][0], matrix[i][1], matrix[i][2]); } -RI_INLINE const Vector3 Matrix3x3::getColumn ( int i ) const { RI_ASSERT(i>=0&&i<3); return Vector3(matrix[0][i], matrix[1][i], matrix[2][i]); } -RI_INLINE void Matrix3x3::setRow ( int i, const Vector3& v ) { RI_ASSERT(i>=0&&i<3); matrix[i][0] = v.x; matrix[i][1] = v.y; matrix[i][2] = v.z; } -RI_INLINE void Matrix3x3::setColumn ( int i, const Vector3& v ) { RI_ASSERT(i>=0&&i<3); matrix[0][i] = v.x; matrix[1][i] = v.y; matrix[2][i] = v.z; } -RI_INLINE void Matrix3x3::operator*= ( const Matrix3x3& m ) { *this = *this * m; } -RI_INLINE void Matrix3x3::operator*= ( RIfloat f ) { for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] *= f; } -RI_INLINE void Matrix3x3::operator+= ( const Matrix3x3& m ) { for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] += m.matrix[i][j]; } -RI_INLINE void Matrix3x3::operator-= ( const Matrix3x3& m ) { for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] -= m.matrix[i][j]; } -RI_INLINE const Matrix3x3 Matrix3x3::operator- () const { return Matrix3x3( -matrix[0][0],-matrix[0][1],-matrix[0][2], -matrix[1][0],-matrix[1][1],-matrix[1][2], -matrix[2][0],-matrix[2][1],-matrix[2][2]); } -RI_INLINE void Matrix3x3::identity () { for(int i=0;i<3;i++) for(int j=0;j<3;j++) matrix[i][j] = (i == j) ? 1.0f : 0.0f; } -RI_INLINE void Matrix3x3::transpose () { RI_SWAP(matrix[1][0], matrix[0][1]); RI_SWAP(matrix[2][0], matrix[0][2]); RI_SWAP(matrix[2][1], matrix[1][2]); } -RI_INLINE RIfloat Matrix3x3::det () const { return matrix[0][0] * (matrix[1][1]*matrix[2][2] - matrix[2][1]*matrix[1][2]) + matrix[0][1] * (matrix[2][0]*matrix[1][2] - matrix[1][0]*matrix[2][2]) + matrix[0][2] * (matrix[1][0]*matrix[2][1] - matrix[2][0]*matrix[1][1]); } -RI_INLINE bool Matrix3x3::isAffine () const { if(matrix[2][0] == 0.0f && matrix[2][1] == 0.0f && matrix[2][2] == 1.0f) return true; return false; } - -RI_INLINE void Matrix3x3::validate() -{ - for (int i = 0; i < 3; i++) - for (int j = 0; j < 3; j++) - matrix[i][j] = validateFloat(matrix[i][j]); -} - -RI_INLINE void Matrix3x3::assertValid() const -{ -#if defined(RI_DEBUG) - for (int i = 0; i < 3; i++) - for (int j = 0; j < 3; j++) - RI_ASSERT(!RI_ISNAN(matrix[i][j])); -#endif -} - -//============================================================================================== - -} //namespace OpenVGRI - -#endif /* __RIMATH_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riMiniEGL.cpp --- a/hostsupport/hostopenvg/src/src/riMiniEGL.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,2210 +0,0 @@ -/*------------------------------------------------------------------------ - * - * EGL 1.3 - * ------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Simple implementation of EGL 1.3 - * \note caveats: - - always renders into the backbuffer and blits it to window (no single buffered rendering) - - no native Windows or Mac OS X pixmap support - - no power management events - - no support for swap interval - * \todo what happens in egl functions when eglTerminate has been called but the context and surface are still in use? - * \todo OSDeinitMutex should be called in case getEGL fails. - *//*-------------------------------------------------------------------*/ - -#include "EGL/egl.h" -#include "openvg.h" -#include "riArray.h" -#include "riMath.h" -#include "riContext.h" -#include "riImage.h" - -#include "riEGLOS.h" - -// Temp: A blitter is kept in the egl context for surface copies, but it will -// be placed into the EGL to VG interface in the future. -#ifndef __SFDYNAMICBLITTER_H -# include "sfDynamicBlitter.h" -#endif - - -//============================================================================================== - -namespace OpenVGRI -{ - -#if 0 -void* OSGetCurrentThreadID(void); -void OSAcquireMutex(void); -void OSReleaseMutex(void); -void OSDeinitMutex(void); - -EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id); -void* OSCreateWindowContext(EGLNativeWindowType window); -void OSDestroyWindowContext(void* context); -bool OSIsWindow(const void* context); -void OSGetWindowSize(const void* context, int& width, int& height); -void OSBlitToWindow(void* context, const Drawable* drawable); -#else - - -#endif - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class RIEGLConfig -{ -public: - RIEGLConfig() : m_desc(Color::formatToDescriptor(VG_sRGBA_8888)), m_configID(0) {} - ~RIEGLConfig() {} - void set(int r, int g, int b, int a, int l, int bpp, int samples, int maskBits, int ID) - { - Color::Shape shape; - m_desc.redBits = r; - m_desc.greenBits = g; - m_desc.blueBits = b; - m_desc.alphaBits = a; - m_desc.luminanceBits = l; -#if !defined(_WIN32) && 0 - m_desc.alphaShift = 0; - m_desc.luminanceShift = 0; - m_desc.blueShift = b ? a : 0; - m_desc.greenShift = g ? a + b : 0; - m_desc.redShift = r ? a + b + g : 0; -#else - m_desc.luminanceShift = 0; - m_desc.redShift = 0; - m_desc.greenShift = g ? r : 0; - m_desc.blueShift = b ? r + g : 0; - m_desc.alphaShift = a ? r + g + b : 0; - -#endif - m_desc.internalFormat = l ? (a ? Color::sLA : Color::lLA) : ((r || g || b ) ? Color::sRGBA : Color::lRGBA); - - m_desc.bitsPerPixel = bpp; - m_desc.bytesPerPixel = bpp / 8; - - { - // Determine shape - if (m_desc.hasAlpha()) - { - if (m_desc.redBits > 0) - shape = Color::SHAPE_ARGB; - else if (m_desc.isLuminance()) - shape = Color::SHAPE_AL; - else - { - RI_ASSERT(m_desc.isAlphaOnly()); - shape = Color::SHAPE_A; - } - } else - { - if (m_desc.redBits > 0) - { - if (m_desc.bitsPerPixel == 32) - shape = Color::SHAPE_XRGB; - else - { - RI_ASSERT(m_desc.bitsPerPixel == 24 || m_desc.bitsPerPixel == 16); - shape = Color::SHAPE_RGB; - } - } else if (m_desc.isLuminance()) - { - shape = Color::SHAPE_L; - } else - { - RI_ASSERT(false); - } - } - } - - m_desc.shape = shape; - //m_desc.format = Color::descriptorToVGImageFormat(m_desc); - m_desc.vgFormat = (VGImageFormat)-1; - RI_ASSERT(Color::isValidDescriptor(m_desc)); - m_samples = samples; - m_maskBits = maskBits; - m_configID = ID; - m_config = (EGLConfig)ID; - } - - Color::Descriptor configToDescriptor(bool sRGB, bool premultiplied) const - { - Color::Descriptor desc = m_desc; - unsigned int f = m_desc.luminanceBits ? Color::LUMINANCE : 0; - f |= sRGB ? Color::NONLINEAR : 0; - f |= premultiplied ? Color::PREMULTIPLIED : 0; - desc.internalFormat = (Color::InternalFormat)f; - return desc; - } - - //EGL RED SIZE bits of Red in the color buffer - //EGL GREEN SIZE bits of Green in the color buffer - //EGL BLUE SIZE bits of Blue in the color buffer - //EGL ALPHA SIZE bits of Alpha in the color buffer - //EGL LUMINANCE SIZE bits of Luminance in the color buffer - Color::Descriptor m_desc; - int m_samples; - int m_maskBits; - EGLint m_configID; //EGL CONFIG ID unique EGLConfig identifier - EGLConfig m_config; - //EGL BUFFER SIZE depth of the color buffer (sum of channel bits) - //EGL ALPHA MASK SIZE number alpha mask bits (always 8) - //EGL BIND TO TEXTURE RGB boolean True if bindable to RGB textures. (always EGL_FALSE) - //EGL BIND TO TEXTURE RGBA boolean True if bindable to RGBA textures. (always EGL_FALSE) - //EGL COLOR BUFFER TYPE enum color buffer type (EGL_RGB_BUFFER, EGL_LUMINANCE_BUFFER) - //EGL CONFIG CAVEAT enum any caveats for the configuration (always EGL_NONE) - //EGL DEPTH SIZE integer bits of Z in the depth buffer (always 0) - //EGL LEVEL integer frame buffer level (always 0) - //EGL MAX PBUFFER WIDTH integer maximum width of pbuffer (always INT_MAX) - //EGL MAX PBUFFER HEIGHT integer maximum height of pbuffer (always INT_MAX) - //EGL MAX PBUFFER PIXELS integer maximum size of pbuffer (always INT_MAX) - //EGL MAX SWAP INTERVAL integer maximum swap interval (always 1) - //EGL MIN SWAP INTERVAL integer minimum swap interval (always 1) - //EGL NATIVE RENDERABLE boolean EGL TRUE if native rendering APIs can render to surface (always EGL_FALSE) - //EGL NATIVE VISUAL ID integer handle of corresponding native visual (always 0) - //EGL NATIVE VISUAL TYPE integer native visual type of the associated visual (always EGL_NONE) - //EGL RENDERABLE TYPE bitmask which client rendering APIs are supported. (always EGL_OPENVG_BIT) - //EGL SAMPLE BUFFERS integer number of multisample buffers (always 0) - //EGL SAMPLES integer number of samples per pixel (always 0) - //EGL STENCIL SIZE integer bits of Stencil in the stencil buffer (always 0) - //EGL SURFACE TYPE bitmask which types of EGL surfaces are supported. (always EGL WINDOW BIT | EGL PIXMAP BIT | EGL PBUFFER BIT) - //EGL TRANSPARENT TYPE enum type of transparency supported (always EGL_NONE) - //EGL TRANSPARENT RED VALUE integer transparent red value (undefined) - //EGL TRANSPARENT GREEN VALUE integer transparent green value (undefined) - //EGL TRANSPARENT BLUE VALUE integer transparent blue value (undefined) -}; - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class RIEGLContext -{ -public: - RIEGLContext(OpenVGRI::VGContext* vgctx, const EGLConfig config); - ~RIEGLContext(); - void addReference() { m_referenceCount++; } - int removeReference() { m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; } - - VGContext* getVGContext() const { return m_vgContext; } - EGLConfig getConfig() const { return m_config; } - DynamicBlitter& getBlitter() { return m_blitter; } -private: - RIEGLContext(const RIEGLContext&); - RIEGLContext& operator=(const RIEGLContext&); - VGContext* m_vgContext; - const EGLConfig m_config; - int m_referenceCount; - DynamicBlitter m_blitter; -}; - -RIEGLContext::RIEGLContext(OpenVGRI::VGContext* vgctx, const EGLConfig config) : - m_vgContext(vgctx), - m_config(config), - m_referenceCount(0) -{ -} -RIEGLContext::~RIEGLContext() -{ - RI_ASSERT(m_referenceCount == 0); - RI_DELETE(m_vgContext); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class RIEGLSurface -{ -public: - RIEGLSurface(void* OSWindowContext, const EGLConfig config, Drawable* drawable, bool largestPbuffer, int renderBuffer); - ~RIEGLSurface(); - void addReference() { m_referenceCount++; } - int removeReference() { m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; } - - void* getOSWindowContext() const { return m_OSWindowContext; } - EGLConfig getConfig() const { return m_config; } - Drawable* getDrawable() const { return m_drawable; } - bool isLargestPbuffer() const { return m_largestPbuffer; } - int getRenderBuffer() const { return m_renderBuffer; } - -private: - RIEGLSurface(const RIEGLSurface&); - RIEGLSurface& operator=(const RIEGLSurface&); - void* m_OSWindowContext; - const EGLConfig m_config; - Drawable* m_drawable; - bool m_largestPbuffer; - int m_renderBuffer; //EGL_BACK_BUFFER or EGL_SINGLE_BUFFER - int m_referenceCount; -}; - -RIEGLSurface::RIEGLSurface(void* OSWindowContext, const EGLConfig config, Drawable* drawable, bool largestPbuffer, int renderBuffer) : - m_OSWindowContext(OSWindowContext), - m_config(config), - m_drawable(drawable), - m_largestPbuffer(largestPbuffer), - m_renderBuffer(renderBuffer), - m_referenceCount(0) -{ - RI_ASSERT(m_renderBuffer == EGL_BACK_BUFFER); //only back buffer rendering is supported - m_drawable->addReference(); -} - -RIEGLSurface::~RIEGLSurface() -{ - RI_ASSERT(m_referenceCount == 0); - OSDestroyWindowContext((OSWindowContext*)m_OSWindowContext); - if(m_drawable) - { - if(!m_drawable->removeReference()) - RI_DELETE(m_drawable); - } -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -#define EGL_NUMCONFIGS 5 - -class RIEGLDisplay -{ -public: - RIEGLDisplay(EGLDisplay id); - ~RIEGLDisplay(); - - int getNumConfigs() const { return EGL_NUMCONFIGS; } - const RIEGLConfig& getConfig(int i) const { RI_ASSERT(i >= 0 && i < EGL_NUMCONFIGS); return m_configs[i]; } - const RIEGLConfig& getConfig(const EGLConfig config) const { for(int i=0;i m_contexts; - Array m_surfaces; - - RIEGLConfig m_configs[EGL_NUMCONFIGS]; -}; - -RIEGLDisplay::RIEGLDisplay(EGLDisplay id) : - m_id(id), - m_contexts(), - m_surfaces() -{ - - //sorted by RGB/LUMINANCE (exact), larger total number of color bits (at least), buffer size (at least), config ID (exact) - //NOTE: 16 bit configs need to be sorted on the fly if the request ignores some channels - //NOTE: config IDs start from 1 - // R B G A L bpp samples maskBits ID - int i = 0; - m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 8, i+1); i++; //EGL_RGB_BUFFER, buffer size = 32 - m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++; // RGBX - m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 8, i+1); i++; // 565 - m_configs[i].set(0, 0, 0, 0, 8, 8, 1, 8, i+1); i++; // L8 - m_configs[i].set(0, 0, 0, 8, 0, 8, 1, 8, i+1); i++; // A8 - // \note The reference implementation does not support LA16 config, so it is currently - // not possible to test it. See if the format fits the specification. - //m_configs[i].set(0, 0, 0, 8, 8, 16, 1, 8, i+1); i++; // LA16 -#if 0 - m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 8, i+1); i++; //EGL_RGB_BUFFER, buffer size = 32 - m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++; // RGBX - m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 8, i+1); i++; //EGL_RGB_BUFFER, buffer size = 24 - //m_configs[i].set(5, 5, 5, 1, 0, 16, 1, 4, i+1); i++; //EGL_RGB_BUFFER, buffer size = 16 - m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 4, i+1); i++; //EGL_RGB_BUFFER, buffer size = 16 - //m_configs[i].set(4, 4, 4, 4, 0, 16, 1, 4, i+1); i++; //EGL_RGB_BUFFER, buffer size = 16 - m_configs[i].set(0, 0, 0, 8, 0, 8, 1, 8, i+1); i++; //EGL_RGB_BUFFER, buffer size = 8 - m_configs[i].set(0, 0, 0, 4, 0, 4, 1, 4, i+1); i++; //EGL_RGB_BUFFER, buffer size = 8 - m_configs[i].set(0, 0, 0, 1, 0, 1, 1, 1, i+1); i++; //EGL_RGB_BUFFER, buffer size = 8 - m_configs[i].set(0, 0, 0, 0, 8, 8, 1, 8, i+1); i++; //EGL_LUMINANCE_BUFFER, buffer size = 8 - //m_configs[i].set(0, 0, 0, 0, 1, 1, 1, 1, i+1); i++; //EGL_LUMINANCE_BUFFER, buffer size = 1 - - //configs without mask - m_configs[i].set(8, 8, 8, 8, 0, 32, 1, 0, i+1); i++; //EGL_RGB_BUFFER, buffer size = 32 - m_configs[i].set(8, 8, 8, 0, 0, 32, 1, 0, i+1); i++; //EGL_RGB_BUFFER, buffer size = 24 - //m_configs[i].set(5, 5, 5, 1, 0, 16, 1, 0, i+1); i++; //EGL_RGB_BUFFER, buffer size = 16 - m_configs[i].set(5, 6, 5, 0, 0, 16, 1, 0, i+1); i++; //EGL_RGB_BUFFER, buffer size = 16 - //m_configs[i].set(4, 4, 4, 4, 0, 16, 1, 0, i+1); i++; //EGL_RGB_BUFFER, buffer size = 16 - m_configs[i].set(0, 0, 0, 8, 0, 8, 1, 0, i+1); i++; //EGL_RGB_BUFFER, buffer size = 8 - m_configs[i].set(0, 0, 0, 4, 0, 4, 1, 0, i+1); i++; //EGL_RGB_BUFFER, buffer size = 8 - m_configs[i].set(0, 0, 0, 1, 0, 1, 1, 0, i+1); i++; //EGL_RGB_BUFFER, buffer size = 8 - m_configs[i].set(0, 0, 0, 0, 8, 8, 1, 0, i+1); i++; //EGL_LUMINANCE_BUFFER, buffer size = 8 - //m_configs[i].set(0, 0, 0, 0, 1, 1, 1, 0, 20); //EGL_LUMINANCE_BUFFER, buffer size = 1 -#endif - - RI_ASSERT(EGL_NUMCONFIGS == i); - -/* -attrib default criteria order priority --------------------------------------------------------------- -EGL_COLOR_BUFFER_TYPE EGL_RGB_BUFFER Exact None 2 -EGL_RED_SIZE 0 AtLeast Special 3 -EGL_GREEN_SIZE 0 AtLeast Special 3 -EGL_BLUE_SIZE 0 AtLeast Special 3 -EGL_LUMINANCE_SIZE 0 AtLeast Special 3 -EGL_ALPHA_SIZE 0 AtLeast Special 3 -EGL_BUFFER_SIZE 0 AtLeast Smaller 4 -EGL_ALPHA_MASK_SIZE 0 AtLeast Smaller 9 -EGL_CONFIG_ID EGL_DONT_CARE Exact Smaller 11 -*/ -} - -RIEGLDisplay::~RIEGLDisplay() -{ - //mark everything for deletion, but don't delete the current context and surface - for(int i=0;iremoveReference()) - 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;iremoveReference()) - 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= 0); return m_referenceCount; } - - void addDisplay(RIEGLDisplay* display) { RI_ASSERT(display); m_displays.push_back(display); } //throws bad alloc - void removeDisplay(RIEGLDisplay* display) { RI_ASSERT(display); bool res = m_displays.remove(display); RI_ASSERT(res); RI_UNREF(res); } - RIEGLDisplay* getDisplay(const EGLDisplay displayID) const; - EGLDisplay findDisplay(const EGLContext ctx) const; - - void addCurrentThread(RIEGLThread* thread) { RI_ASSERT(thread); m_currentThreads.push_back(thread); } //throws bad alloc - void removeCurrentThread(RIEGLThread* thread) { RI_ASSERT(thread); bool res = m_currentThreads.remove(thread); RI_ASSERT(res); RI_UNREF(res); } - RIEGLThread* getCurrentThread() const; - - RIEGLThread* getThread(); - void destroyThread(); - - bool isInUse(const void* image) const; - -private: - EGL(const EGL&); // Not allowed. - const EGL& operator=(const EGL&); // Not allowed. - - Array m_threads; //threads that have called EGL - Array m_currentThreads; //threads that have a bound context - Array m_displays; - - int m_referenceCount; -}; - -EGL::EGL() : - m_threads(), - m_currentThreads(), - m_displays(), - m_referenceCount(0) -{ -} -EGL::~EGL() -{ - for(int i=0;iaddReference(); - } - 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;igetID()) - return m_displays[i]; - } - return NULL; //error: the display hasn't been eglInitialized -} - -/*-------------------------------------------------------------------*//*! -* \brief return EGLDisplay for the current context -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLDisplay EGL::findDisplay(EGLContext ctx) const -{ - for(int i=0;icontextExists(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;igetThreadID()) - 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;igetThreadID()) - 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;igetThreadID()) - { - 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;igetCurrentSurface(); - if(s && s->getDrawable() && s->getDrawable()->isInUse((Image*)image)) - return true; - } - return false; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -#define EGL_GET_DISPLAY(DISPLAY, RETVAL) \ - OSAcquireMutex(); \ - EGL* egl = getEGL(); \ - if(!egl) \ - { \ - OSReleaseMutex(); \ - return RETVAL; \ - } \ - RIEGLDisplay* display = egl->getDisplay(DISPLAY); \ - -#define EGL_GET_EGL(RETVAL) \ - OSAcquireMutex(); \ - EGL* egl = getEGL(); \ - if(!egl) \ - { \ - OSReleaseMutex(); \ - return RETVAL; \ - } \ - -#define EGL_IF_ERROR(COND, ERRORCODE, RETVAL) \ - if(COND) { eglSetError(egl, ERRORCODE); OSReleaseMutex(); return RETVAL; } \ - -#define EGL_RETURN(ERRORCODE, RETVAL) \ - { \ - eglSetError(egl, ERRORCODE); \ - OSReleaseMutex(); \ - return RETVAL; \ - } - -// Note: egl error handling model differs from OpenVG. The latest error is stored instead of the oldest one. -static void eglSetError(EGL* egl, EGLint error) -{ - RIEGLThread* thread = egl->getThread(); - if(thread) - thread->setError(error); -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns the OpenVG context current to the calling thread. -* \param -* \return -* \note This function is always called from a mutexed API function -*//*-------------------------------------------------------------------*/ - -void* eglvgGetCurrentVGContext(void) -{ - EGL* egl = getEGL(); - if(egl) - { - RIEGLThread* thread = egl->getCurrentThread(); - if(thread) - { - RI_ASSERT(thread->getCurrentContext() && thread->getCurrentSurface()); - return thread->getCurrentContext()->getVGContext(); - } - } - return NULL; //not initialized or made current -} - -bool eglvgLockSurface(bool read, bool write) -{ - (void)read; - (void)write; - return true; -} - -bool eglvgUnlockSurface() -{ - return true; -} - -/*-------------------------------------------------------------------*//*! -* \brief Check if the image is current in any of the displays -* \param -* \return -* \note This function is always called from a mutexed API function -*//*-------------------------------------------------------------------*/ - -bool eglvgIsInUse(void* image) -{ - EGL* egl = getEGL(); - if(egl) - { - return egl->isInUse(image); - } - return false; -} - -//============================================================================================== - -} //namespace OpenVGRI - -using namespace OpenVGRI; - - - - - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLint EGLAPIENTRY eglGetError() -{ - OSAcquireMutex(); - EGLint ret = EGL_SUCCESS; - EGL* egl = getEGL(); - if(egl) - { - RIEGLThread* thread = egl->getThread(); - if(thread) - ret = thread->getError(); //initialized, return error code - } - else ret = EGL_NOT_INITIALIZED; - OSReleaseMutex(); - return ret; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id) -{ - return OSGetDisplay(display_id); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(display, EGL_SUCCESS, EGL_TRUE); //already initialized - - //create the current display - //if a context and a surface are bound by the time of eglTerminate, they remain bound until eglMakeCurrent is called - RIEGLDisplay* newDisplay = NULL; - try - { - newDisplay = RI_NEW(RIEGLDisplay, (dpy)); //throws bad_alloc - egl->addDisplay(newDisplay); //throws bad_alloc - display = newDisplay; - RI_ASSERT(display); - } - catch(std::bad_alloc) - { - RI_DELETE(newDisplay); - EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE); - } - - if(major) *major = 1; - if(minor) *minor = 2; - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglTerminate(EGLDisplay dpy) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_SUCCESS, EGL_TRUE); - egl->removeDisplay(display); - RI_DELETE(display); - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -const char* EGLAPIENTRY eglQueryString(EGLDisplay dpy, EGLint name) -{ - EGL_GET_DISPLAY(dpy, NULL); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, NULL); - - static const char apis[] = "OpenVG"; - static const char extensions[] = ""; - static const char vendor[] = "Khronos Group"; - static const char version[] = "1.3"; - - const char* ret = NULL; - switch(name) - { - case EGL_CLIENT_APIS: - ret = apis; - break; - - case EGL_EXTENSIONS: - ret = extensions; - break; - - case EGL_VENDOR: - ret = vendor; - break; - - case EGL_VERSION: - ret = version; - break; - - default: - EGL_RETURN(EGL_BAD_PARAMETER, NULL); - } - EGL_RETURN(EGL_SUCCESS, ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglGetConfigs(EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!num_config, EGL_BAD_PARAMETER, EGL_FALSE); - if(!configs) - { - *num_config = display->getNumConfigs(); - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); - } - *num_config = RI_INT_MIN(config_size, display->getNumConfigs()); - for(int i=0;i<*num_config;i++) - configs[i] = display->getConfig(i).m_config; - - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static bool smaller(EGLint c, EGLint filter) -{ - return (filter != EGL_DONT_CARE) && (c < filter); -} - -EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!num_config, EGL_BAD_PARAMETER, EGL_FALSE); - - if(!configs) - { - *num_config = display->getNumConfigs(); - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); - } - *num_config = 0; - if(!config_size) - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); - - int bufferSize = 0; - int redSize = 0; - int greenSize = 0; - int blueSize = 0; - int luminanceSize = 0; - int alphaSize = 0; - int alphaMaskSize = 0; - int colorBufferType = EGL_RGB_BUFFER; - int configID = EGL_DONT_CARE; - int sampleBuffers = 0; - int samples = 0; - if(attrib_list) - { - for(int i=0;attrib_list[i] != EGL_NONE;i+=2) - { - switch(attrib_list[i]) - { - case EGL_BUFFER_SIZE: //depth of the color buffer - bufferSize = attrib_list[i+1]; - break; - case EGL_RED_SIZE: //bits of Red in the color buffer - redSize = attrib_list[i+1]; - break; - case EGL_GREEN_SIZE: //bits of Green in the color buffer - greenSize = attrib_list[i+1]; - break; - case EGL_BLUE_SIZE: //bits of Blue in the color buffer - blueSize = attrib_list[i+1]; - break; - case EGL_LUMINANCE_SIZE: //bits of Luminance in the color buffer - luminanceSize = attrib_list[i+1]; - break; - case EGL_ALPHA_SIZE: //bits of Alpha in the color buffer - alphaSize = attrib_list[i+1]; - break; - case EGL_ALPHA_MASK_SIZE: //bits of Alpha in the alpha mask buffer - alphaMaskSize = attrib_list[i+1]; - if(attrib_list[i+1] > 8) - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); //not supported - break; - case EGL_COLOR_BUFFER_TYPE: //enum color buffer type (EGL_RGB_BUFFER, EGL_LUMINANCE_BUFFER) - EGL_IF_ERROR(attrib_list[i+1] != EGL_RGB_BUFFER && attrib_list[i+1] != EGL_LUMINANCE_BUFFER && attrib_list[i+1] != EGL_DONT_CARE, EGL_BAD_ATTRIBUTE, EGL_FALSE); - colorBufferType = attrib_list[i+1]; - break; - case EGL_CONFIG_ID: //unique EGLConfig identifier - configID = attrib_list[i+1]; - break; - - case EGL_SAMPLE_BUFFERS: //integer number of multisample buffers - sampleBuffers = attrib_list[i+1]; - break; - case EGL_SAMPLES: //integer number of samples per pixel - samples = attrib_list[i+1]; - break; - - case EGL_BIND_TO_TEXTURE_RGB: //boolean True if bindable to RGB textures. (always EGL_FALSE) - case EGL_BIND_TO_TEXTURE_RGBA: //boolean True if bindable to RGBA textures. (always EGL_FALSE) - case EGL_DEPTH_SIZE: //integer bits of Z in the depth buffer (always 0) - case EGL_LEVEL: //integer frame buffer level (always 0) - case EGL_NATIVE_RENDERABLE: //boolean EGL TRUE if native rendering APIs can render to surface (always EGL_FALSE) - case EGL_STENCIL_SIZE: //integer bits of Stencil in the stencil buffer (always 0) - if(attrib_list[i+1]) - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); //not supported - break; - - case EGL_CONFIG_CAVEAT: //enum any caveats for the configuration (always EGL_NONE) - case EGL_NATIVE_VISUAL_TYPE: //integer native visual type of the associated visual (always EGL_NONE) - if(attrib_list[i+1] != EGL_NONE) - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); //not supported - break; - - case EGL_MAX_SWAP_INTERVAL: //integer maximum swap interval (always 1) - case EGL_MIN_SWAP_INTERVAL: //integer minimum swap interval (always 1) - if(attrib_list[i+1] != 1) - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); //not supported - break; - - case EGL_RENDERABLE_TYPE: //bitmask which client rendering APIs are supported. (always EGL_OPENVG_BIT) - if(!(attrib_list[i+1] & EGL_OPENVG_BIT)) - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); //not supported - break; - - case EGL_SURFACE_TYPE: //bitmask which types of EGL surfaces are supported. (always EGL_WINDOW_BIT | EGL_PIXMAP_BIT | EGL_PBUFFER_BIT | EGL_VG_COLORSPACE_LINEAR_BIT | EGL_VG_ALPHA_FORMAT_PRE_BIT) - break; //all types are always supported - - case EGL_TRANSPARENT_TYPE: //enum type of transparency supported (always EGL_NONE) - case EGL_NATIVE_VISUAL_ID: //integer handle of corresponding native visual (always 0) - case EGL_MAX_PBUFFER_WIDTH: //integer maximum width of pbuffer (always INT_MAX) - case EGL_MAX_PBUFFER_HEIGHT: //integer maximum height of pbuffer (always INT_MAX) - case EGL_MAX_PBUFFER_PIXELS: //integer maximum size of pbuffer (always INT_MAX) - case EGL_TRANSPARENT_RED_VALUE: //integer transparent red value (undefined) - case EGL_TRANSPARENT_GREEN_VALUE: //integer transparent green value (undefined) - case EGL_TRANSPARENT_BLUE_VALUE: //integer transparent blue value (undefined) - break; //ignored - - default: - EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE); //unknown attribute - } - } - } - - if(configID && configID != EGL_DONT_CARE) - { //if CONFIG_ID is defined, ignore the rest of the attribs - for(int i=0;igetConfig(i).m_configID == configID) - { - *num_config = 1; - *configs = display->getConfig(i).m_config; - } - } - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); - } - - //go through all configs, add passed configs to return list - //TODO take alpha mask size into account - EGLConfig found[EGL_NUMCONFIGS]; - int keys[EGL_NUMCONFIGS]; - int numFound = 0; - for(int i=0;igetNumConfigs();i++) - { - const RIEGLConfig& c = display->getConfig(i); - - int configMaskBits = c.m_maskBits; - int colorBits = c.m_desc.redBits + c.m_desc.greenBits + c.m_desc.blueBits; - int luminanceBits = c.m_desc.luminanceBits; - int configBufferSize; - if(colorBits) - { - RI_ASSERT(!luminanceBits); - colorBits += c.m_desc.alphaBits; - configBufferSize = colorBits; - } - else if(luminanceBits) - { - luminanceBits += c.m_desc.alphaBits; - configBufferSize = luminanceBits; - } - else - { //alpha only surface - colorBits = c.m_desc.alphaBits; - luminanceBits = c.m_desc.alphaBits; - configBufferSize = colorBits; - } - - if (smaller(configBufferSize, bufferSize)) - continue; - - int configSampleBuffers = c.m_samples == 1 ? 0 : 1; - if (smaller(configSampleBuffers, sampleBuffers)) - continue; - if (smaller(c.m_samples, samples)) - continue; - - if (smaller(c.m_desc.redBits, redSize) - || smaller(c.m_desc.greenBits, greenSize) - || smaller(c.m_desc.blueBits, blueSize) - || smaller(c.m_desc.alphaBits, alphaSize) ) - continue; - - if (smaller(c.m_desc.luminanceBits, luminanceSize)) - continue; - - if (smaller(configMaskBits, alphaMaskSize)) - continue; - - if ((colorBufferType == EGL_RGB_BUFFER && !colorBits) || - (colorBufferType == EGL_LUMINANCE_BUFFER && !luminanceBits)) - continue; - - // \todo Add the alphaMaskSize into the sort order also! - int sortKey = c.m_configID; //sort from smaller to larger - int sortBits = 0; - if(redSize != 0 && redSize != EGL_DONT_CARE) - sortBits += c.m_desc.redBits; - if(greenSize != 0 && greenSize != EGL_DONT_CARE) - sortBits += c.m_desc.greenBits; - if(blueSize != 0 && blueSize != EGL_DONT_CARE) - sortBits += c.m_desc.blueBits; - if(alphaSize != 0 && alphaSize != EGL_DONT_CARE) - sortBits += c.m_desc.alphaBits; - if(luminanceSize != 0 && luminanceSize != EGL_DONT_CARE) - sortBits += c.m_desc.luminanceBits; - RI_ASSERT(c.m_configID <= EGL_NUMCONFIGS); //if there are more configs, increase the shift value - RI_ASSERT(sortBits <= 32); - sortKey += (32-sortBits) << 4; //sort from larger to smaller - - found[numFound] = c.m_config; - keys[numFound++] = sortKey; - } - if(!numFound) - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); - - //sort return list into increasing order - for(int e=0;e keys[f]) - { - EGLConfig tmp = found[e]; - found[e] = found[f]; - found[f] = tmp; - RI_INT_SWAP(keys[e], keys[f]); - } - } - } - - //write configs into return array - numFound = RI_INT_MIN(numFound, config_size); - for(int i=0;iconfigExists(config), EGL_BAD_CONFIG, EGL_FALSE); - const RIEGLConfig& c = display->getConfig(config); - switch(attribute) - { - case EGL_BUFFER_SIZE: - *value = RI_INT_MAX(c.m_desc.redBits + c.m_desc.greenBits + c.m_desc.blueBits + c.m_desc.alphaBits, c.m_desc.luminanceBits + c.m_desc.alphaBits); - break; - - case EGL_RED_SIZE: - *value = c.m_desc.redBits; - break; - - case EGL_GREEN_SIZE: - *value = c.m_desc.greenBits; - break; - - case EGL_BLUE_SIZE: - *value = c.m_desc.blueBits; - break; - - case EGL_LUMINANCE_SIZE: - *value = c.m_desc.luminanceBits; - break; - - case EGL_ALPHA_SIZE: - *value = c.m_desc.alphaBits; - break; - - case EGL_ALPHA_MASK_SIZE: - *value = c.m_maskBits; - break; - - case EGL_BIND_TO_TEXTURE_RGB: - case EGL_BIND_TO_TEXTURE_RGBA: - *value = EGL_FALSE; - break; - - case EGL_COLOR_BUFFER_TYPE: - if(c.m_desc.redBits) - *value = EGL_RGB_BUFFER; - else - *value = EGL_LUMINANCE_BUFFER; - break; - - case EGL_CONFIG_CAVEAT: - *value = EGL_NONE; - break; - - case EGL_CONFIG_ID: - *value = c.m_configID; - break; - - case EGL_DEPTH_SIZE: - *value = 0; - break; - - case EGL_LEVEL: - *value = 0; - break; - - case EGL_MAX_PBUFFER_WIDTH: - case EGL_MAX_PBUFFER_HEIGHT: - *value = 16384; //NOTE arbitrary maximum - break; - - case EGL_MAX_PBUFFER_PIXELS: - *value = 16384*16384; //NOTE arbitrary maximum - break; - - case EGL_MAX_SWAP_INTERVAL: - case EGL_MIN_SWAP_INTERVAL: - *value = 1; - break; - - case EGL_NATIVE_RENDERABLE: - *value = EGL_FALSE; - break; - - case EGL_NATIVE_VISUAL_ID: - *value = 0; - break; - - case EGL_NATIVE_VISUAL_TYPE: - *value = EGL_NONE; - break; - - case EGL_RENDERABLE_TYPE: - *value = EGL_OPENVG_BIT; - break; - - case EGL_SAMPLE_BUFFERS: - *value = c.m_samples > 1 ? 1 : 0; - break; - - case EGL_SAMPLES: - *value = c.m_samples > 1 ? c.m_samples : 0; - break; - - case EGL_STENCIL_SIZE: - *value = 0; - break; - - case EGL_SURFACE_TYPE: - *value = EGL_WINDOW_BIT | EGL_PIXMAP_BIT | EGL_PBUFFER_BIT | EGL_VG_COLORSPACE_LINEAR_BIT | EGL_VG_ALPHA_FORMAT_PRE_BIT; - break; - - case EGL_TRANSPARENT_TYPE: - *value = EGL_NONE; - break; - - case EGL_TRANSPARENT_RED_VALUE: - case EGL_TRANSPARENT_GREEN_VALUE: - case EGL_TRANSPARENT_BLUE_VALUE: - *value = 0; - break; - - case EGL_CONFORMANT: - *value = EGL_OPENVG_BIT; //TODO return proper value - break; - - default: - EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE); - } - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLSurface EGLAPIENTRY eglCreateWindowSurface(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list) -{ - EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE); - EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE); - - int renderBuffer = EGL_BACK_BUFFER; - int colorSpace = EGL_VG_COLORSPACE_sRGB; - int alphaFormat = EGL_VG_ALPHA_FORMAT_NONPRE; - if(attrib_list) - { - for(int i=0;attrib_list[i] != EGL_NONE;i+=2) - { - switch(attrib_list[i]) - { - case EGL_RENDER_BUFFER: - renderBuffer = attrib_list[i+1]; - break; - - case EGL_VG_COLORSPACE: - colorSpace = attrib_list[i+1]; - break; - - case EGL_VG_ALPHA_FORMAT: - alphaFormat = attrib_list[i+1]; - break; - - default: - EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE); - } - } - } - //we ignore the renderBuffer parameter since we can only render to double buffered surfaces - - //TODO If the attributes of win do not correspond to config, then an EGL BAD MATCH error is generated. - //TODO If there is already an EGLConfig associated with win (as a result of a previous eglCreateWindowSurface call), then an EGL BAD ALLOC error is generated - - void* wc = NULL; - OpenVGRI::Drawable* d = NULL; - RIEGLSurface* s = NULL; - try - { - wc = OSCreateWindowContext((EGLNativeWindowType)win); - RI_ASSERT(wc); - //TODO what should happen if window width or height is zero? - int windowWidth = 0, windowHeight = 0; - OSGetWindowSize((OSWindowContext*)wc, windowWidth, windowHeight); - bool isWindow = OSIsWindow((const OSWindowContext*)wc); - if(windowWidth <= 0 || windowHeight <= 0 || !isWindow) - { - OSDestroyWindowContext((OSWindowContext*)wc); - EGL_IF_ERROR(!isWindow, EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE); - EGL_IF_ERROR(windowWidth <= 0 || windowHeight <= 0, EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE); - } - Color::Descriptor colorDescriptor = display->getConfig(config).configToDescriptor((colorSpace == EGL_VG_COLORSPACE_LINEAR) ? false : true, (alphaFormat == EGL_VG_ALPHA_FORMAT_PRE) ? true : false); - d = RI_NEW(OpenVGRI::Drawable, (colorDescriptor, windowWidth, windowHeight, display->getConfig(config).m_samples, display->getConfig(config).m_maskBits)); //throws bad_alloc - RI_ASSERT(d); - s = RI_NEW(RIEGLSurface,(wc, config, d, false, renderBuffer)); //throws bad_alloc - RI_ASSERT(s); - s->addReference(); - display->addSurface(s); //throws bad_alloc - } - catch(std::bad_alloc) - { - OSDestroyWindowContext((OSWindowContext*)wc); - RI_DELETE(d); - RI_DELETE(s); - EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE); - } - EGL_RETURN(EGL_SUCCESS, (EGLSurface)s); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list) -{ - EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE); - EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE); - - int width = 0, height = 0; - bool largestPbuffer = false; - int colorSpace = EGL_VG_COLORSPACE_sRGB; - int alphaFormat = EGL_VG_ALPHA_FORMAT_NONPRE; - if(attrib_list) - { - for(int i=0;attrib_list[i] != EGL_NONE;i+=2) - { - switch(attrib_list[i]) - { - case EGL_WIDTH: - width = attrib_list[i+1]; - break; - - case EGL_HEIGHT: - height = attrib_list[i+1]; - break; - - case EGL_LARGEST_PBUFFER: - largestPbuffer = attrib_list[i+1] ? true : false; - break; - - case EGL_VG_COLORSPACE: - colorSpace = attrib_list[i+1]; - break; - - case EGL_VG_ALPHA_FORMAT: - alphaFormat = attrib_list[i+1]; - break; - - case EGL_TEXTURE_FORMAT: //config doesn't support OpenGL ES - case EGL_TEXTURE_TARGET: //config doesn't support OpenGL ES - case EGL_MIPMAP_TEXTURE: //config doesn't support OpenGL ES - default: - EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE); - break; - } - } - } - EGL_IF_ERROR(width <= 0 || height <= 0, EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE); - - OpenVGRI::Drawable* d = NULL; - RIEGLSurface* s = NULL; - try - { - d = RI_NEW(OpenVGRI::Drawable, (display->getConfig(config).configToDescriptor((colorSpace == EGL_VG_COLORSPACE_LINEAR) ? false : true, (alphaFormat == EGL_VG_ALPHA_FORMAT_PRE) ? true : false), width, height, display->getConfig(config).m_samples, display->getConfig(config).m_maskBits)); //throws bad_alloc - RI_ASSERT(d); - s = RI_NEW(RIEGLSurface,(NULL, config, d, largestPbuffer, EGL_BACK_BUFFER)); //throws bad_alloc - RI_ASSERT(s); - s->addReference(); - display->addSurface(s); //throws bad_alloc - } - catch(std::bad_alloc) - { - RI_DELETE(d); - RI_DELETE(s); - EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE); - } - EGL_RETURN(EGL_SUCCESS, (EGLSurface)s); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer(EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list) -{ - EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE); - EGL_IF_ERROR(buftype != EGL_OPENVG_IMAGE, EGL_BAD_PARAMETER, EGL_NO_SURFACE); - EGL_IF_ERROR(!buffer, EGL_BAD_PARAMETER, EGL_NO_SURFACE); //TODO should also check if buffer really is a valid VGImage object (needs VG context for that) - Image* image = (Image*)buffer; - EGL_IF_ERROR(image->isInUse(), EGL_BAD_ACCESS, EGL_NO_SURFACE); //buffer is in use by OpenVG - EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE); - EGL_IF_ERROR(attrib_list && attrib_list[0] != EGL_NONE, EGL_BAD_ATTRIBUTE, EGL_NO_SURFACE); //there are no valid attribs for OpenVG - const Color::Descriptor& bc = ((Image*)buffer)->getDescriptor(); - const Color::Descriptor& cc = display->getConfig(config).m_desc; - EGL_IF_ERROR(bc.redBits != cc.redBits || bc.greenBits != cc.greenBits || bc.blueBits != cc.blueBits || - bc.alphaBits != cc.alphaBits || bc.luminanceBits != cc.luminanceBits, EGL_BAD_MATCH, EGL_NO_SURFACE); - - //TODO If buffer is already bound to another pbuffer, an EGL BAD ACCESS error is generated. - - OpenVGRI::Drawable* d = NULL; - RIEGLSurface* s = NULL; - try - { - d = RI_NEW(OpenVGRI::Drawable, (image, display->getConfig(config).m_maskBits)); - RI_ASSERT(d); - s = RI_NEW(RIEGLSurface,(NULL, config, d, false, EGL_BACK_BUFFER)); //throws bad_alloc - RI_ASSERT(s); - s->addReference(); - display->addSurface(s); //throws bad_alloc - } - catch(std::bad_alloc) - { - RI_DELETE(d); - RI_DELETE(s); - EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE); - } - EGL_RETURN(EGL_SUCCESS, (EGLSurface)s); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLSurface EGLAPIENTRY eglCreatePixmapSurface(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list) -{ - // Seems that this function has not been implemented correctly in the RI: - // cannot assume that EGLNativePixmapType has format, data, etc. -#if 0 - EGL_GET_DISPLAY(dpy, EGL_NO_SURFACE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_SURFACE); - EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_SURFACE); - EGL_IF_ERROR(!pixmap || !isValidImageFormat(pixmap->format) || !pixmap->data || pixmap->width <= 0 || pixmap->height <= 0, EGL_BAD_NATIVE_PIXMAP, EGL_NO_SURFACE); - RI_UNREF(attrib_list); - EGL_IF_ERROR(display->getConfig(config).m_samples != 1, EGL_BAD_MATCH, EGL_NO_SURFACE); - - //TODO If there is already an EGLSurface associated with pixmap (as a result of a previous eglCreatePixmapSurface call), then a EGL BAD ALLOC error is generated. - - Drawable* d = NULL; - RIEGLSurface* s = NULL; - try - { - d = RI_NEW(Drawable, (Color::formatToDescriptor((VGImageFormat)pixmap->format), pixmap->width, pixmap->height, pixmap->stride, (RIuint8*)pixmap->data, display->getConfig(config).m_maskBits)); //throws bad_alloc - RI_ASSERT(d); - s = RI_NEW(RIEGLSurface,(NULL, config, d, false, EGL_BACK_BUFFER)); //throws bad_alloc - RI_ASSERT(s); - s->addReference(); - display->addSurface(s); //throws bad_alloc - } - catch(std::bad_alloc) - { - RI_DELETE(d); - RI_DELETE(s); - EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_SURFACE); - } - EGL_RETURN(EGL_SUCCESS, (EGLSurface)s); -#else - (void)dpy; - (void)config; - (void)pixmap; - (void)attrib_list; - return 0; -#endif -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglDestroySurface(EGLDisplay dpy, EGLSurface surface) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE); - - display->removeSurface((RIEGLSurface*)surface); - if(!((RIEGLSurface*)surface)->removeReference()) - RI_DELETE((RIEGLSurface*)surface); - - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglSurfaceAttrib(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE); - RI_UNREF(attribute); - RI_UNREF(value); - //do nothing - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglQuerySurface(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE); - //TODO give an error if value is NULL? - - RIEGLSurface* s = (RIEGLSurface*)surface; - switch(attribute) - { - case EGL_VG_ALPHA_FORMAT: - *value = (s->getDrawable()->getDescriptor().isPremultiplied()) ? EGL_VG_ALPHA_FORMAT_PRE : EGL_VG_ALPHA_FORMAT_NONPRE; - break; - - case EGL_VG_COLORSPACE: - *value = (s->getDrawable()->getDescriptor().isNonlinear()) ? EGL_VG_COLORSPACE_sRGB : EGL_VG_COLORSPACE_LINEAR; - break; - - case EGL_CONFIG_ID: - *value = display->getConfig(s->getConfig()).m_configID; - break; - - case EGL_HEIGHT: - *value = s->getDrawable()->getHeight(); - break; - - case EGL_HORIZONTAL_RESOLUTION: - *value = EGL_UNKNOWN; //TODO Horizontal dot pitch - break; - - case EGL_LARGEST_PBUFFER: - if(!s->getOSWindowContext()) - *value = s->isLargestPbuffer() ? EGL_TRUE : EGL_FALSE; - break; - - case EGL_MIPMAP_TEXTURE: - if(!s->getOSWindowContext()) - *value = EGL_FALSE; - break; - - case EGL_MIPMAP_LEVEL: - if(!s->getOSWindowContext()) - *value = 0; - break; - - case EGL_PIXEL_ASPECT_RATIO: - *value = EGL_UNKNOWN; //TODO Display aspect ratio - break; - - case EGL_RENDER_BUFFER: - *value = s->getRenderBuffer(); - break; - - case EGL_SWAP_BEHAVIOR: - *value = EGL_BUFFER_PRESERVED; - break; - - case EGL_TEXTURE_FORMAT: - if(!s->getOSWindowContext()) - *value = EGL_NO_TEXTURE; - break; - - case EGL_TEXTURE_TARGET: - if(!s->getOSWindowContext()) - *value = EGL_NO_TEXTURE; - break; - - case EGL_VERTICAL_RESOLUTION: - *value = EGL_UNKNOWN; //TODO Vertical dot pitch - break; - - case EGL_WIDTH: - *value = s->getDrawable()->getWidth(); - break; - - default: - EGL_RETURN(EGL_BAD_ATTRIBUTE, EGL_FALSE); - } - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list) -{ - EGL_GET_DISPLAY(dpy, EGL_NO_CONTEXT); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_NO_CONTEXT); - EGL_IF_ERROR(!display->configExists(config), EGL_BAD_CONFIG, EGL_NO_CONTEXT); - RI_UNREF(attrib_list); - - RIEGLThread* thread = egl->getThread(); - if(!thread) - EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_CONTEXT); - - //creation of OpenGL ES contexts is not allowed in this implementation - if(thread->getBoundAPI() != EGL_OPENVG_API) - EGL_RETURN(EGL_BAD_MATCH, EGL_NO_CONTEXT); - - OpenVGRI::VGContext* vgctx = NULL; - RIEGLContext* c = NULL; - try - { - vgctx = RI_NEW(OpenVGRI::VGContext, (share_context ? ((RIEGLContext*)share_context)->getVGContext() : NULL)); //throws bad_alloc - c = RI_NEW(RIEGLContext, (vgctx, config)); //throws bad_alloc - c->addReference(); - display->addContext(c); //throws bad_alloc - } - catch(std::bad_alloc) - { - RI_DELETE(vgctx); - RI_DELETE(c); - EGL_RETURN(EGL_BAD_ALLOC, EGL_NO_CONTEXT); - } - - EGL_RETURN(EGL_SUCCESS, (EGLContext)c); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglDestroyContext(EGLDisplay dpy, EGLContext ctx) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE); - - RIEGLContext* context = (RIEGLContext*)ctx; - display->removeContext(context); - if(!context->removeReference() ) - RI_DELETE(context); - - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(ctx != EGL_NO_CONTEXT && !display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE); - EGL_IF_ERROR(draw != EGL_NO_SURFACE && !display->surfaceExists(draw), EGL_BAD_SURFACE, EGL_FALSE); - EGL_IF_ERROR(read != EGL_NO_SURFACE && !display->surfaceExists(read), EGL_BAD_SURFACE, EGL_FALSE); - EGL_IF_ERROR(draw != read, EGL_BAD_MATCH, EGL_FALSE); //TODO what's the proper error code? - EGL_IF_ERROR((draw != EGL_NO_SURFACE && ctx == EGL_NO_CONTEXT) || (draw == EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT), EGL_BAD_MATCH, EGL_FALSE); - - RIEGLSurface* s = NULL; - RIEGLContext* c = NULL; - if(draw != EGL_NO_SURFACE && ctx != EGL_NO_CONTEXT) - { - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - - s = (RIEGLSurface*)draw; - c = (RIEGLContext*)ctx; - - //If either draw or read are pbuffers created with eglCreatePbufferFromClientBuffer, and the underlying bound client API buffers - //are in use by the client API that created them, an EGL BAD ACCESS error is generated. - EGL_IF_ERROR(s->getDrawable()->isInUse(), EGL_BAD_ACCESS, EGL_FALSE); - - - //TODO properly check compatibility of surface and context: - //-both have RGB or LUMINANCE configs - //-buffer bit depths match - //-configs support OpenVG - //-both have the same display - EGL_IF_ERROR(s->getConfig() != c->getConfig(), EGL_BAD_MATCH, EGL_FALSE); - //TODO check if context or surfaces are already bound to another thread - - //If a native window underlying either draw or read is no longer valid, an EGL BAD NATIVE WINDOW error is generated. - EGL_IF_ERROR(s->getOSWindowContext() && !OSIsWindow((const OSWindowContext*)s->getOSWindowContext()), EGL_BAD_NATIVE_WINDOW, EGL_FALSE); - - //TODO If the previous context of the calling display has unflushed commands, and the previous surface is no longer valid, an EGL BAD CURRENT SURFACE error is generated. (can this happen?) - //TODO If the ancillary buffers for draw and read cannot be allocated, an EGL BAD ALLOC error is generated. (mask buffer?) - } - - //check if the thread is current - RIEGLThread* thread = egl->getCurrentThread(); - if(thread) - { //thread is current, release the old bindinds and remove the thread from the current thread list - RIEGLContext* pc = thread->getCurrentContext(); - RIEGLSurface* ps = thread->getCurrentSurface(); - if(pc) - { - vgFlush(); - pc->getVGContext()->setDefaultDrawable(NULL); - if(!pc->removeReference()) - RI_DELETE(pc); - } - if(ps) - { - if(!ps->removeReference()) - RI_DELETE(ps); - } - - egl->removeCurrentThread(thread); - } - - if( c && s ) - { - //bind context and surface to the current display - RIEGLThread* newThread = egl->getThread(); - if(!newThread) - EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE); - newThread->makeCurrent(c, s); - c->getVGContext()->setDefaultDrawable(s->getDrawable()); - - try - { - egl->addCurrentThread(newThread); //throws bad_alloc - } - catch(std::bad_alloc) - { - EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE); - } - - c->addReference(); - s->addReference(); - } - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLContext EGLAPIENTRY eglGetCurrentContext() -{ - EGL_GET_EGL(EGL_NO_CONTEXT); - EGLContext ret = EGL_NO_CONTEXT; - RIEGLThread* thread = egl->getCurrentThread(); - if(thread && thread->getBoundAPI() == EGL_OPENVG_API) - { - ret = thread->getCurrentContext(); - RI_ASSERT(ret); - } - EGL_RETURN(EGL_SUCCESS, ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLSurface EGLAPIENTRY eglGetCurrentSurface(EGLint readdraw) -{ - EGL_GET_EGL(EGL_NO_SURFACE); - EGL_IF_ERROR(readdraw != EGL_READ && readdraw != EGL_DRAW, EGL_BAD_PARAMETER, EGL_NO_SURFACE); - EGLContext ret = EGL_NO_SURFACE; - RIEGLThread* thread = egl->getCurrentThread(); - if(thread && thread->getBoundAPI() == EGL_OPENVG_API) - { - ret = thread->getCurrentSurface(); - RI_ASSERT(ret); - } - EGL_RETURN(EGL_SUCCESS, ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns the current display -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLDisplay EGLAPIENTRY eglGetCurrentDisplay(void) -{ - EGL_GET_EGL(EGL_NO_DISPLAY); - - RIEGLThread* thread = egl->getCurrentThread(); - if(!thread || thread->getBoundAPI() != EGL_OPENVG_API) - EGL_RETURN(EGL_SUCCESS, EGL_NO_DISPLAY); - - RIEGLContext* ctx = thread->getCurrentContext(); - RI_ASSERT(ctx); - EGLDisplay ret = egl->findDisplay(ctx); - EGL_RETURN(EGL_SUCCESS, ret); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglQueryContext(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint* value) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!display->contextExists(ctx), EGL_BAD_CONTEXT, EGL_FALSE); - EGL_IF_ERROR(attribute != EGL_CONFIG_ID && attribute != EGL_CONTEXT_CLIENT_TYPE, EGL_BAD_ATTRIBUTE, EGL_FALSE); - if(attribute == EGL_CONFIG_ID) - *value = display->getConfig(((RIEGLContext*)ctx)->getConfig()).m_configID; - if(attribute == EGL_CONTEXT_CLIENT_TYPE) - *value = EGL_OPENVG_API; - // \todo [kalle 05/Jul/05] Handling of EGL_RENDER_BUFFER attribute is missing. - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglBindAPI(EGLenum api) -{ - EGL_GET_EGL(EGL_FALSE); - EGL_IF_ERROR(api != EGL_OPENVG_API && api != EGL_OPENGL_ES_API, EGL_BAD_PARAMETER, EGL_FALSE); - RIEGLThread* thread = egl->getThread(); - if(thread) - thread->bindAPI(api); - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLenum EGLAPIENTRY eglQueryAPI(void) -{ - EGL_GET_EGL(EGL_NONE); - RIEGLThread* thread = egl->getThread(); - if(thread) - EGL_RETURN(EGL_SUCCESS, thread->getBoundAPI()); - EGL_RETURN(EGL_SUCCESS, EGL_NONE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglWaitClient() -{ - EGL_GET_EGL(EGL_FALSE); - RIEGLThread* thread = egl->getCurrentThread(); - if(thread && thread->getBoundAPI() == EGL_OPENVG_API) - vgFinish(); - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief Waits for OpenGL ES -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglWaitGL(void) -{ - return EGL_TRUE; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note We don't support native rendering -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglWaitNative(EGLint engine) -{ - RI_UNREF(engine); - return EGL_TRUE; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglSwapBuffers(EGLDisplay dpy, EGLSurface surface) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE); - - RIEGLSurface* s = (RIEGLSurface*)surface; - - RIEGLThread* currentThread = egl->getCurrentThread(); - EGL_IF_ERROR(!currentThread || currentThread->getCurrentSurface() != s, EGL_BAD_SURFACE, EGL_FALSE); - EGL_IF_ERROR(!OSIsWindow((const OSWindowContext*)s->getOSWindowContext()), EGL_BAD_NATIVE_WINDOW, EGL_FALSE); - - vgFlush(); - - if(!s->getOSWindowContext()) - { //do nothing for other than window surfaces (NOTE: single-buffered window surfaces should return immediately as well) - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); - } - - int windowWidth = 0, windowHeight = 0; - OSGetWindowSize((OSWindowContext*)s->getOSWindowContext(), windowWidth, windowHeight); - - if(windowWidth != s->getDrawable()->getWidth() || windowHeight != s->getDrawable()->getHeight()) - { //resize the back buffer - RIEGLContext* c = currentThread->getCurrentContext(); - RI_ASSERT(c); - try - { - s->getDrawable()->resize(c->getVGContext(), windowWidth, windowHeight); //throws bad_alloc - } - catch(std::bad_alloc) - { - c->getVGContext()->setDefaultDrawable(NULL); - EGL_RETURN(EGL_BAD_ALLOC, EGL_FALSE); - } - } - - OSBlitToWindow((OSWindowContext*)s->getOSWindowContext(), s->getDrawable()); - - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglCopyBuffers(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target) -{ - // This RI implementation does not make sense. -#if 0 - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - EGL_IF_ERROR(!display->surfaceExists(surface), EGL_BAD_SURFACE, EGL_FALSE); - EGL_IF_ERROR(!target || !isValidImageFormat(target->format) || !target->data || target->width <= 0 || target->height <= 0, EGL_BAD_NATIVE_PIXMAP, EGL_FALSE); - RIEGLThread* currentThread = egl->getCurrentThread(); - RIEGLContext* c = currentThread->getCurrentContext(); - RI_ASSERT(c); - try - { - Image output(Color::formatToDescriptor((VGImageFormat)target->format), target->width, target->height, target->stride, (RIuint8*)target->data); - output.addReference(); - output.blit(c->getVGContext(), ((RIEGLSurface*)surface)->getDrawable()->getColorBuffer()->getImage(), 0, 0, 0, 0, target->width, target->height); //throws bad_alloc - output.removeReference(); - } - catch(std::bad_alloc) - { - } - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -#else - (void)dpy; - (void)surface; - (void)target; - return EGL_FALSE; -#endif -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note We support only swap interval one -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglSwapInterval(EGLDisplay dpy, EGLint interval) -{ - EGL_GET_DISPLAY(dpy, EGL_FALSE); - EGL_IF_ERROR(!display, EGL_NOT_INITIALIZED, EGL_FALSE); - RI_UNREF(interval); - EGL_RETURN(EGL_SUCCESS, EGL_TRUE); -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -typedef void RI_Proc(); - -__eglMustCastToProperFunctionPointerType EGLAPIENTRY eglGetProcAddress(const char *procname) -{ - if(!procname) - return NULL; - return NULL; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -EGLBoolean EGLAPIENTRY eglReleaseThread(void) -{ - EGL_GET_EGL(EGL_FALSE); - - //check if the thread is current - RIEGLThread* thread = egl->getCurrentThread(); - if(thread) - { //thread is current, release the old bindings and remove the thread from the current thread list - RIEGLContext* pc = thread->getCurrentContext(); - RIEGLSurface* ps = thread->getCurrentSurface(); - if(pc) - { - vgFlush(); - pc->getVGContext()->setDefaultDrawable(NULL); - if(!pc->removeReference()) - RI_DELETE(pc); - } - if(ps) - { - if(!ps->removeReference()) - RI_DELETE(ps); - } - - egl->removeCurrentThread(thread); - } - - //destroy EGL's thread struct - egl->destroyThread(); - - //destroy the EGL instance - releaseEGL(); - - OSReleaseMutex(); - OSDeinitMutex(); - - return EGL_SUCCESS; -} - -#undef EGL_NUMCONFIGS diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riPath.cpp --- a/hostsupport/hostopenvg/src/src/riPath.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,2779 +0,0 @@ -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementation of Path functions. - * \note - *//*-------------------------------------------------------------------*/ - -#include "riPath.h" - -//============================================================================================== - - -//============================================================================================== - -namespace OpenVGRI -{ - -RIfloat inputFloat(VGfloat f); //defined in riApi.cpp - -/*-------------------------------------------------------------------*//*! -* \brief Form a reliable normalized average of the two unit input vectors. -* The average always lies to the given direction from the first -* vector. -* \param u0, u1 Unit input vectors. -* \param cw True if the average should be clockwise from u0, false if -* counterclockwise. -* \return Average of the two input vectors. -* \note -*//*-------------------------------------------------------------------*/ - -static const Vector2 unitAverage(const Vector2& u0, const Vector2& u1, bool cw) -{ - Vector2 u = 0.5f * (u0 + u1); - Vector2 n0 = perpendicularCCW(u0); - - if( dot(u, u) > 0.25f ) - { //the average is long enough and thus reliable - if( dot(n0, u1) < 0.0f ) - u = -u; //choose the larger angle - } - else - { // the average is too short, use the average of the normals to the vectors instead - Vector2 n1 = perpendicularCW(u1); - u = 0.5f * (n0 + n1); - } - if( cw ) - u = -u; - - return normalize(u); -} - -/*-------------------------------------------------------------------*//*! -* \brief Form a reliable normalized average of the two unit input vectors. -* The average lies on the side where the angle between the input -* vectors is less than 180 degrees. -* \param u0, u1 Unit input vectors. -* \return Average of the two input vectors. -* \note -*//*-------------------------------------------------------------------*/ - -static const Vector2 unitAverage(const Vector2& u0, const Vector2& u1) -{ - Vector2 u = 0.5f * (u0 + u1); - - if( dot(u, u) < 0.25f ) - { // the average is unreliable, use the average of the normals to the vectors instead - Vector2 n0 = perpendicularCCW(u0); - Vector2 n1 = perpendicularCW(u1); - u = 0.5f * (n0 + n1); - if( dot(n1, u0) < 0.0f ) - u = -u; - } - - return normalize(u); -} - -/*-------------------------------------------------------------------*//*! -* \brief Interpolate the given unit tangent vectors to the given -* direction on a unit circle. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static const Vector2 circularLerp(const Vector2& t0, const Vector2& t1, RIfloat ratio, bool cw) -{ - Vector2 u0 = t0, u1 = t1; - RIfloat l0 = 0.0f, l1 = 1.0f; - for(int i=0;i<18;i++) - { - Vector2 n = unitAverage(u0, u1, cw); - RIfloat l = 0.5f * (l0 + l1); - if( ratio < l ) - { - u1 = n; - l1 = l; - } - else - { - u0 = n; - l0 = l; - } - } - return u0; -} - -/*-------------------------------------------------------------------*//*! -* \brief Interpolate the given unit tangent vectors on a unit circle. -* Smaller angle between the vectors is used. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static const Vector2 circularLerp(const Vector2& t0, const Vector2& t1, RIfloat ratio) -{ - Vector2 u0 = t0, u1 = t1; - RIfloat l0 = 0.0f, l1 = 1.0f; - for(int i=0;i<18;i++) - { - Vector2 n = unitAverage(u0, u1); - RIfloat l = 0.5f * (l0 + l1); - if( ratio < l ) - { - u1 = n; - l1 = l; - } - else - { - u0 = n; - l0 = l; - } - } - return u0; -} - -/*-------------------------------------------------------------------*//*! -* \brief Path constructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Path::Path(VGint format, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int segmentCapacityHint, int coordCapacityHint, VGbitfield caps) : - m_format(format), - m_datatype(datatype), - m_scale(scale), - m_bias(bias), - m_capabilities(caps), - m_referenceCount(0), - m_segments(), - m_data(), - m_vertices(), - m_segmentToVertex(), - m_userMinx(0.0f), - m_userMiny(0.0f), - m_userMaxx(0.0f), - m_userMaxy(0.0f) -{ - RI_ASSERT(format == VG_PATH_FORMAT_STANDARD); - RI_ASSERT(datatype >= VG_PATH_DATATYPE_S_8 && datatype <= VG_PATH_DATATYPE_F); - if(segmentCapacityHint > 0) - m_segments.reserve(RI_INT_MIN(segmentCapacityHint, 65536)); - if(coordCapacityHint > 0) - m_data.reserve(RI_INT_MIN(coordCapacityHint, 65536) * getBytesPerCoordinate(datatype)); -} - -/*-------------------------------------------------------------------*//*! -* \brief Path destructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Path::~Path() -{ - RI_ASSERT(m_referenceCount == 0); -} - -/*-------------------------------------------------------------------*//*! -* \brief Reads a coordinate and applies scale and bias. -* \param -* \return -*//*-------------------------------------------------------------------*/ - -RIfloat Path::getCoordinate(int i) const -{ - RI_ASSERT(i >= 0 && i < m_data.size() / getBytesPerCoordinate(m_datatype)); - RI_ASSERT(m_scale != 0.0f); - - const RIuint8* ptr = &m_data[0]; - switch(m_datatype) - { - case VG_PATH_DATATYPE_S_8: - return (RIfloat)(((const RIint8*)ptr)[i]) * m_scale + m_bias; - - case VG_PATH_DATATYPE_S_16: - return (RIfloat)(((const RIint16*)ptr)[i]) * m_scale + m_bias; - - case VG_PATH_DATATYPE_S_32: - return (RIfloat)(((const RIint32*)ptr)[i]) * m_scale + m_bias; - - default: - RI_ASSERT(m_datatype == VG_PATH_DATATYPE_F); - return (RIfloat)(((const RIfloat32*)ptr)[i]) * m_scale + m_bias; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Writes a coordinate, subtracting bias and dividing out scale. -* \param -* \return -* \note If the coordinates do not fit into path datatype range, they -* will overflow silently. -*//*-------------------------------------------------------------------*/ - -void Path::setCoordinate(Array& data, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int i, RIfloat c) -{ - RI_ASSERT(i >= 0 && i < data.size()/getBytesPerCoordinate(datatype)); - RI_ASSERT(!RI_ISNAN(scale)); - RI_ASSERT(!RI_ISNAN(bias)); - RI_ASSERT(scale != 0.0f); - - c = inputFloat(c); // Revalidate: Can happen when a coordinate has been transformed. - c -= bias; - c /= scale; - - RI_ASSERT(!RI_ISNAN(c)); - - RIuint8* ptr = &data[0]; - switch(datatype) - { - case VG_PATH_DATATYPE_S_8: - ((RIint8*)ptr)[i] = (RIint8)floor(c + 0.5f); //add 0.5 for correct rounding - break; - - case VG_PATH_DATATYPE_S_16: - ((RIint16*)ptr)[i] = (RIint16)floor(c + 0.5f); //add 0.5 for correct rounding - break; - - case VG_PATH_DATATYPE_S_32: - ((RIint32*)ptr)[i] = (RIint32)floor(c + 0.5f); //add 0.5 for correct rounding - break; - - default: - RI_ASSERT(datatype == VG_PATH_DATATYPE_F); - ((RIfloat32*)ptr)[i] = (RIfloat32)c; - break; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Given a datatype, returns the number of bytes per coordinate. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -int Path::getBytesPerCoordinate(VGPathDatatype datatype) -{ - if(datatype == VG_PATH_DATATYPE_S_8) - return 1; - if(datatype == VG_PATH_DATATYPE_S_16) - return 2; - RI_ASSERT(datatype == VG_PATH_DATATYPE_S_32 || datatype == VG_PATH_DATATYPE_F); - return 4; -} - -/*-------------------------------------------------------------------*//*! -* \brief Given a path segment type, returns the number of coordinates -* it uses. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -int Path::segmentToNumCoordinates(VGPathSegment segment) -{ - RI_ASSERT(((int)segment >> 1) >= 0 && ((int)segment >> 1) <= 12); - static const int coords[13] = {0,2,2,1,1,4,6,2,4,5,5,5,5}; - return coords[(int)segment >> 1]; -} - -/*-------------------------------------------------------------------*//*! -* \brief Computes the number of coordinates a segment sequence uses. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -int Path::countNumCoordinates(const RIuint8* segments, int numSegments) -{ - RI_ASSERT(segments); - RI_ASSERT(numSegments >= 0); - - int coordinates = 0; - for(int i=0;i 0); - RI_ASSERT(segments && data); - RI_ASSERT(m_referenceCount > 0); - - //allocate new arrays - int oldSegmentsSize = m_segments.size(); - int newSegmentsSize = oldSegmentsSize + numSegments; - Array 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 newData; - newData.resize(newDataSize); //throws bad_alloc - //if we get here, the memory allocations have succeeded - - //copy old segments and append new ones - if(m_segments.size()) - ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size()); - ri_memcpy(&newSegments[0] + m_segments.size(), segments, numSegments); - - //copy old data and append new ones - if(newData.size()) - { - if(m_data.size()) - ri_memcpy(&newData[0], &m_data[0], m_data.size()); - if(m_datatype == VG_PATH_DATATYPE_F) - { - RIfloat32* d = (RIfloat32*)(&newData[0] + m_data.size()); - const RIfloat32* s = (const RIfloat32*)data; - for(int i=0;i 0 && srcPath->m_referenceCount > 0); - - if(srcPath->m_segments.size()) - { - //allocate new arrays - int newSegmentsSize = m_segments.size() + srcPath->m_segments.size(); - Array newSegments; - newSegments.resize(newSegmentsSize); //throws bad_alloc - - int newDataSize = m_data.size() + srcPath->getNumCoordinates() * getBytesPerCoordinate(m_datatype); - Array newData; - newData.resize(newDataSize); //throws bad_alloc - //if we get here, the memory allocations have succeeded - - //copy old segments and append new ones - if(m_segments.size()) - ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size()); - if(srcPath->m_segments.size()) - ri_memcpy(&newSegments[0] + m_segments.size(), &srcPath->m_segments[0], srcPath->m_segments.size()); - - //copy old data and append new ones - if(m_data.size()) - ri_memcpy(&newData[0], &m_data[0], m_data.size()); - for(int i=0;igetNumCoordinates();i++) - setCoordinate(newData, m_datatype, m_scale, m_bias, i + getNumCoordinates(), srcPath->getCoordinate(i)); - - RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype)); - - //replace old arrays - m_segments.swap(newSegments); - m_data.swap(newData); - } -} - -int Path::coordsSizeInBytes( int startIndex, int numSegments ) - { - RI_ASSERT(numSegments > 0); - RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size()); - RI_ASSERT(m_referenceCount > 0); - - int numCoords = countNumCoordinates(&m_segments[startIndex], numSegments); - if(!numCoords) - return 0; - int bytesPerCoordinate = getBytesPerCoordinate(m_datatype); - return (numCoords * bytesPerCoordinate); - } - -/*-------------------------------------------------------------------*//*! -* \brief Modifies existing coordinate data. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Path::modifyCoords(int startIndex, int numSegments, const RIuint8* data) -{ - RI_ASSERT(numSegments > 0); - RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size()); - RI_ASSERT(data); - RI_ASSERT(m_referenceCount > 0); - - int startCoord = countNumCoordinates(&m_segments[0], startIndex); - int numCoords = countNumCoordinates(&m_segments[startIndex], numSegments); - if(!numCoords) - return; - int bytesPerCoordinate = getBytesPerCoordinate(m_datatype); - RIuint8* dst = &m_data[startCoord * bytesPerCoordinate]; - if(m_datatype == VG_PATH_DATATYPE_F) - { - RIfloat32* d = (RIfloat32*)dst; - const RIfloat32* s = (const RIfloat32*)data; - for(int i=0;i 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;im_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 newSegments; - newSegments.resize(m_segments.size() + srcPath->m_segments.size()); //throws bad_alloc - Array newData; - newData.resize(m_data.size() + numDstCoords * getBytesPerCoordinate(m_datatype)); //throws bad_alloc - //if we get here, the memory allocations have succeeded - - //copy old segments - if(m_segments.size()) - ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size()); - - //copy old data - if(m_data.size()) - ri_memcpy(&newData[0], &m_data[0], m_data.size()); - - int srcCoord = 0; - int dstCoord = getNumCoordinates(); - Vector2 s(0,0); //the beginning of the current subpath - Vector2 o(0,0); //the last point of the previous segment - for(int i=0;im_segments.size();i++) - { - VGPathSegment segment = getPathSegment(srcPath->m_segments[i]); - VGPathAbsRel absRel = getPathAbsRel(srcPath->m_segments[i]); - int coords = segmentToNumCoordinates(segment); - - switch(segment) - { - case VG_CLOSE_PATH: - { - RI_ASSERT(coords == 0); - o = s; - break; - } - - case VG_MOVE_TO: - { - RI_ASSERT(coords == 2); - Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1)); - Vector2 tc; - - if (absRel == VG_ABSOLUTE) - tc = affineTransform(matrix, c); - else - { - tc = affineTangentTransform(matrix, c); - c += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y); - s = c; - o = c; - break; - } - - case VG_LINE_TO: - { - RI_ASSERT(coords == 2); - Vector2 c(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1)); - Vector2 tc; - - if (absRel == VG_ABSOLUTE) - tc = affineTransform(matrix, c); - else - { - tc = affineTangentTransform(matrix, c); - c += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y); - o = c; - break; - } - - case VG_HLINE_TO: - { - RI_ASSERT(coords == 1); - Vector2 c(srcPath->getCoordinate(srcCoord+0), 0); - Vector2 tc; - - if (absRel == VG_ABSOLUTE) - { - c.y = o.y; - tc = affineTransform(matrix, c); - } - else - { - tc = affineTangentTransform(matrix, c); - c += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y); - o = c; - segment = VG_LINE_TO; - break; - } - - case VG_VLINE_TO: - { - RI_ASSERT(coords == 1); - Vector2 c(0, srcPath->getCoordinate(srcCoord+0)); - Vector2 tc; - - if (absRel == VG_ABSOLUTE) - { - c.x = o.x; - tc = affineTransform(matrix, c); - } - else - { - tc = affineTangentTransform(matrix, c); - c += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y); - o = c; - segment = VG_LINE_TO; - break; - } - - case VG_QUAD_TO: - { - RI_ASSERT(coords == 4); - Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1)); - Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3)); - Vector2 tc0, tc1; - - if (absRel == VG_ABSOLUTE) - { - tc0 = affineTransform(matrix, c0); - tc1 = affineTransform(matrix, c1); - } - else - { - tc0 = affineTangentTransform(matrix, c0); - tc1 = affineTangentTransform(matrix, c1); - c1 += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.y); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y); - o = c1; - break; - } - - case VG_CUBIC_TO: - { - RI_ASSERT(coords == 6); - Vector2 c0(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1)); - Vector2 c1(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3)); - Vector2 c2(srcPath->getCoordinate(srcCoord+4), srcPath->getCoordinate(srcCoord+5)); - Vector2 tc0, tc1, tc2; - - if (absRel == VG_ABSOLUTE) - { - tc0 = affineTransform(matrix, c0); - tc1 = affineTransform(matrix, c1); - tc2 = affineTransform(matrix, c2); - } - else - { - tc0 = affineTangentTransform(matrix, c0); - tc1 = affineTangentTransform(matrix, c1); - tc2 = affineTangentTransform(matrix, c2); - c2 += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc0.y); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.y); - o = c2; - break; - } - - case VG_SQUAD_TO: - { - RI_ASSERT(coords == 2); - Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1)); - Vector2 tc1; - - if (absRel == VG_ABSOLUTE) - tc1 = affineTransform(matrix, c1); - else - { - tc1 = affineTangentTransform(matrix, c1); - c1 += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y); - o = c1; - break; - } - - case VG_SCUBIC_TO: - { - RI_ASSERT(coords == 4); - Vector2 c1(srcPath->getCoordinate(srcCoord+0), srcPath->getCoordinate(srcCoord+1)); - Vector2 c2(srcPath->getCoordinate(srcCoord+2), srcPath->getCoordinate(srcCoord+3)); - Vector2 tc1, tc2; - - if (absRel == VG_ABSOLUTE) - { - tc1 = affineTransform(matrix, c1); - tc2 = affineTransform(matrix, c2); - } - else - { - tc1 = affineTangentTransform(matrix, c1); - tc2 = affineTangentTransform(matrix, c2); - c2 += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc1.y); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc2.y); - o = c2; - break; - } - - default: - { - RI_ASSERT(segment == VG_SCCWARC_TO || segment == VG_SCWARC_TO || - segment == VG_LCCWARC_TO || segment == VG_LCWARC_TO); - RI_ASSERT(coords == 5); - RIfloat rh = srcPath->getCoordinate(srcCoord+0); - RIfloat rv = srcPath->getCoordinate(srcCoord+1); - RIfloat rot = srcPath->getCoordinate(srcCoord+2); - Vector2 c(srcPath->getCoordinate(srcCoord+3), srcPath->getCoordinate(srcCoord+4)); - - rot = RI_DEG_TO_RAD(rot); - Matrix3x3 u((RIfloat)cos(rot)*rh, -(RIfloat)sin(rot)*rv, 0, - (RIfloat)sin(rot)*rh, (RIfloat)cos(rot)*rv, 0, - 0, 0, 1); - u = matrix * u; - u[2].set(0,0,1); //force affinity - //u maps from the unit circle to transformed ellipse - - //compute new rh, rv and rot - Vector2 p(u[0][0], u[1][0]); - Vector2 q(u[1][1], -u[0][1]); - bool swapped = false; - if(dot(p,p) < dot(q,q)) - { - RI_SWAP(p.x,q.x); - RI_SWAP(p.y,q.y); - swapped = true; - } - Vector2 h = (p+q) * 0.5f; - Vector2 hp = (p-q) * 0.5f; - RIfloat hlen = h.length(); - RIfloat hplen = hp.length(); - rh = hlen + hplen; - rv = hlen - hplen; - - if (RI_ISNAN(rh)) rh = 0.0f; - if (RI_ISNAN(rv)) rv = 0.0f; - - h = hplen * h + hlen * hp; - hlen = dot(h,h); - if(hlen == 0.0f) - rot = 0.0f; - else - { - h.normalize(); - rot = (RIfloat)acos(h.x); - if(h.y < 0.0f) - rot = 2.0f*RI_PI - rot; - if (RI_ISNAN(rot)) - rot = 0.0f; - } - if(swapped) - rot += RI_PI*0.5f; - - Vector2 tc; - if (absRel == VG_ABSOLUTE) - tc = affineTransform(matrix, c); - else - { - tc = affineTangentTransform(matrix, c); - c += o; - } - - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, rh); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, rv); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, RI_RAD_TO_DEG(rot)); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.x); - setCoordinate(newData, m_datatype, m_scale, m_bias, dstCoord++, tc.y); - o = c; - - //flip winding if the determinant is negative - if (matrix.det() < 0) - { - switch (segment) - { - case VG_SCCWARC_TO: segment = VG_SCWARC_TO; break; - case VG_SCWARC_TO: segment = VG_SCCWARC_TO; break; - case VG_LCCWARC_TO: segment = VG_LCWARC_TO; break; - case VG_LCWARC_TO: segment = VG_LCCWARC_TO; break; - default: break; - } - } - break; - } - } - - newSegments[m_segments.size() + i] = (RIuint8)(segment | absRel); - srcCoord += coords; - } - RI_ASSERT(srcCoord == numSrcCoords); - RI_ASSERT(dstCoord == getNumCoordinates() + numDstCoords); - - RI_ASSERT(newData.size() == countNumCoordinates(&newSegments[0],newSegments.size()) * getBytesPerCoordinate(m_datatype)); - - //replace old arrays - m_segments.swap(newSegments); - m_data.swap(newData); -} - -/*-------------------------------------------------------------------*//*! -* \brief Normalizes a path for interpolation. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Path::normalizeForInterpolation(const Path* srcPath) -{ - RI_ASSERT(srcPath); - RI_ASSERT(srcPath != this); - RI_ASSERT(srcPath->m_referenceCount > 0); - - //count the number of resulting coordinates - int numSrcCoords = 0; - int numDstCoords = 0; - for(int i=0;im_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;im_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 newSegments; - newSegments.resize(m_segments.size() + start.m_segments.size()); //throws bad_alloc - Array newData; - newData.resize(m_data.size() + start.m_data.size() * getBytesPerCoordinate(m_datatype) / getBytesPerCoordinate(start.m_datatype)); //throws bad_alloc - //if we get here, the memory allocations have succeeded - - //copy old segments - if(m_segments.size()) - ri_memcpy(&newSegments[0], &m_segments[0], m_segments.size()); - - //copy old data - if(m_data.size()) - ri_memcpy(&newData[0], &m_data[0], m_data.size()); - - //copy segments - for(int i=0;i 0); - RI_ASSERT(pathToSurface.isAffine()); - - tessellate(pathToSurface, 0.0f); //throws bad_alloc - - try - { - Vector2 p0(0,0), p1(0,0); - for(int i=0;ip1) and (p2->p3) - * \todo This must be done in the rasterizer to get correct results. - */ -static void intersectLines(const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3, Vector2& pt) -{ - RIfloat n = (p1.x-p0.x)*(p0.y-p2.y)-(p1.y-p0.y)*(p0.x-p2.x); - RIfloat d = (p3.y-p2.y)*(p1.x-p0.x)-(p3.x-p2.x)*(p1.y-p0.y); - if (d == 0) - { - pt = p0; - return; - } - RIfloat t = n/d; - Vector2 dir = p1-p0; - - pt = p0+t*dir; -} - -static bool isCCW(const Vector2& a, const Vector2& b) -{ - RIfloat c = a.x*b.y - a.y*b.x; - return c >= 0; -} - -/** - * \brief Add a CCW stitch-triangle so that accw -> acw is the base of the triangle. - * \param accw Counter-clockwise stroke end (for example). - * \param acw Clockwise stroke end. - * \param p Tip of the triangle to form. - */ -static void addStitchTriangle(Rasterizer& rasterizer, const Vector2& accw, const Vector2& acw, const Vector2& p) -{ - if (isCCW(p - accw, acw - accw)) - { - // p "below" - rasterizer.addEdge(accw, p); - rasterizer.addEdge(p, acw); - rasterizer.addEdge(acw, accw); - } - else - { - rasterizer.addEdge(accw, acw); - rasterizer.addEdge(acw, p); - rasterizer.addEdge(p, accw); - } -} - -/** - * \brief Add a (ccw-closed) segment to path. See the naming of parameters for input order: - * pp = previous, nn = next - */ -static void addStrokeSegment(Rasterizer& rasterizer, const Vector2& ppccw, const Vector2& ppcw, const Vector2& nnccw, const Vector2& nncw) -{ - RIfloat d = dot(nnccw-ppccw, nncw-ppcw); - if(d < 0) - { - Vector2 ip; - intersectLines(ppccw, ppcw, nnccw, nncw, ip); - - // Create two triangles from the self-intersecting part - if (isCCW(ppccw - nnccw, ip - nnccw)) - { - rasterizer.addEdge(nnccw, ppccw); - rasterizer.addEdge(ppccw, ip); - rasterizer.addEdge(ip, nnccw); - - rasterizer.addEdge(nncw, ppcw); - rasterizer.addEdge(ppcw, ip); - rasterizer.addEdge(ip, nncw); - } - else - { - rasterizer.addEdge(nnccw, ip); - rasterizer.addEdge(ip, ppccw); - rasterizer.addEdge(ppccw, nnccw); - - rasterizer.addEdge(nncw, ip); - rasterizer.addEdge(ip, ppcw); - rasterizer.addEdge(ppcw, nncw); - } - // Final stitch (not necessary if done in the rasterizer) - addStitchTriangle(rasterizer, ppccw, ppcw, ip); - addStitchTriangle(rasterizer, nnccw, nncw, ip); - } - else - { - rasterizer.addEdge(ppccw, ppcw); //throws bad_alloc - rasterizer.addEdge(ppcw, nncw); //throws bad_alloc - rasterizer.addEdge(nncw, nnccw); //throws bad_alloc - rasterizer.addEdge(nnccw, ppccw); //throws bad_alloc - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Smoothly interpolates between two StrokeVertices. Positions -* are interpolated linearly, while tangents are interpolated -* on a unit circle. Stroking is implemented so that overlapping -* geometry doesnt cancel itself when filled with nonzero rule. -* The resulting polygons are closed. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Path::interpolateStroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const StrokeVertex& v0, const StrokeVertex& v1, RIfloat strokeWidth) const -{ - Vector2 ppccw, endccw; - Vector2 ppcw, endcw; - - if (m_mirror) - { - ppccw = affineTransform(pathToSurface, v0.cw); - ppcw = affineTransform(pathToSurface, v0.ccw); - endccw = affineTransform(pathToSurface, v1.cw); - endcw = affineTransform(pathToSurface, v1.ccw); - } - else - { - ppccw = affineTransform(pathToSurface, v0.ccw); - ppcw = affineTransform(pathToSurface, v0.cw); - endccw = affineTransform(pathToSurface, v1.ccw); - endcw = affineTransform(pathToSurface, v1.cw); - } - - const RIfloat tessellationAngle = 5.0f; - - RIfloat angle = RI_RAD_TO_DEG((RIfloat)acos(RI_CLAMP(dot(v0.t, v1.t), -1.0f, 1.0f))) / tessellationAngle; - int samples = RI_INT_MAX((int)ceil(angle), 1); - Vector2 prev = v0.p; - Vector2 prevt = v0.t; - Vector2 position = v0.p; - for(int j=0;j= 0) - cw = false; - - // Add the bevel (which is part of all the other joins also) - // This would be a "consistent" way to handle joins (in addition - // to creating rounding to _both_ side of the join). However, - // the conformance test currently invalidates this case. - // \note Causes some extra geometry. - if (cw) - addStrokeSegment(rasterizer, ccw0t, m0t, ccw1t, m1t); - else - addStrokeSegment(rasterizer, m0t, cw0t, m1t, cw1t); - - switch (joinStyle) - { - case VG_JOIN_BEVEL: - break; - case VG_JOIN_MITER: - { - RIfloat theta = (RIfloat)acos(RI_CLAMP(dot(v0.t, -v1.t), -1.0f, 1.0f)); - RIfloat miterLengthPerStrokeWidth = 1.0f / (RIfloat)sin(theta*0.5f); - if (miterLengthPerStrokeWidth < miterLimit) - { - // Miter - if (cw) - { - m = !mirror ? v0.ccw : v0.cw; - s = ccw1t; - e = ccw0t; - } else - { - m = !mirror ? v0.cw : v0.ccw; - s = cw0t; - e = cw1t; - } - - RIfloat l = (RIfloat)cos(theta*0.5f) * miterLengthPerStrokeWidth * (strokeWidth * 0.5f); - l = RI_MIN(l, RI_FLOAT_MAX); //force finite - Vector2 c = m + v0.t * l; - c = affineTransform(pathToSurface, c); - - rasterizer.addEdge(s, c); - rasterizer.addEdge(c, e); - rasterizer.addEdge(e, s); - } - break; - } - default: - { - RI_ASSERT(joinStyle == VG_JOIN_ROUND); - - Vector2 sp, ep; - - const RIfloat tessellationAngle = 5.0f; - - if (cw) - { - s = ccw1t; - st = -v1.t; - e = ccw0t; - et = -v0.t; - sp = v1.p; - ep = v0.p; - } else - { - s = cw0t; - st = v0.t; - e = cw1t; - et = v1.t; - sp = v0.p; - ep = v1.p; - } - - Vector2 prev = s; - RIfloat angle = RI_RAD_TO_DEG((RIfloat)acos(RI_CLAMP(dot(st, et), -1.0f, 1.0f))) / tessellationAngle; - int samples = (int)ceil(angle); - if( samples ) - { - RIfloat step = 1.0f / samples; - RIfloat t = step; - for(int j=1;j& dashPattern, RIfloat dashPhase, bool dashPhaseReset, RIfloat strokeWidth, VGCapStyle capStyle, VGJoinStyle joinStyle, RIfloat miterLimit) -{ - RI_ASSERT(pathToSurface.isAffine()); - RI_ASSERT(m_referenceCount > 0); - RI_ASSERT(strokeWidth >= 0.0f); - RI_ASSERT(miterLimit >= 1.0f); - - tessellate(pathToSurface, strokeWidth); //throws bad_alloc - - m_mirror = pathToSurface[0][0]*pathToSurface[1][1] < 0 ? true : false; - - if(!m_vertices.size()) - return; - - bool dashing = true; - int dashPatternSize = dashPattern.size(); - if( dashPattern.size() & 1 ) - dashPatternSize--; //odd number of dash pattern entries, discard the last one - RIfloat dashPatternLength = 0.0f; - for(int i=0;i= 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= 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= v0.pathLength && distance < v1.pathLength) - { //segment found, interpolate linearly between its end points - RIfloat edgeLength = v1.pathLength - v0.pathLength; - RI_ASSERT(edgeLength > 0.0f); - RIfloat r = (distance - v0.pathLength) / edgeLength; - p = (1.0f - r) * v0.userPosition + r * v1.userPosition; - t = (1.0f - r) * v0.userTangent + r * v1.userTangent; - return; - } - } - } - } - - RI_ASSERT(0); //point not found (should never get here) -} - -/*-------------------------------------------------------------------*//*! -* \brief Tessellates a path, and computes its length. -* \param -* \return -* \note if runs out of memory, throws bad_alloc and leaves the path as it was -*//*-------------------------------------------------------------------*/ - -RIfloat Path::getPathLength(int startIndex, int numSegments) -{ - RI_ASSERT(m_referenceCount > 0); - RI_ASSERT(startIndex >= 0 && startIndex + numSegments <= m_segments.size() && numSegments > 0); - - Matrix3x3 identity; - identity.identity(); - tessellate(identity, 0.0f); //throws bad_alloc - - RI_ASSERT(startIndex >= 0 && startIndex < m_segmentToVertex.size()); - RI_ASSERT(startIndex + numSegments >= 0 && startIndex + numSegments <= m_segmentToVertex.size()); - - int startVertex = m_segmentToVertex[startIndex].start; - int endVertex = m_segmentToVertex[startIndex + numSegments - 1].end; - - if(!m_vertices.size()) - return 0.0f; - - RIfloat startPathLength = 0.0f; - if(startVertex >= 0) - { - RI_ASSERT(startVertex >= 0 && startVertex < m_vertices.size()); - startPathLength = m_vertices[startVertex].pathLength; - } - RIfloat endPathLength = 0.0f; - if(endVertex >= 0) - { - RI_ASSERT(endVertex >= 0 && endVertex < m_vertices.size()); - endPathLength = m_vertices[endVertex].pathLength; - } - - return endPathLength - startPathLength; -} - -/*-------------------------------------------------------------------*//*! -* \brief Tessellates a path, and computes its bounding box in user space. -* \param -* \return -* \note if runs out of memory, throws bad_alloc and leaves the path as it was -*//*-------------------------------------------------------------------*/ - -void Path::getPathBounds(RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy) -{ - RI_ASSERT(m_referenceCount > 0); - - Matrix3x3 identity; - identity.identity(); - tessellate(identity, 0.0f); //throws bad_alloc - - if(m_vertices.size()) - { - minx = m_userMinx; - miny = m_userMiny; - maxx = m_userMaxx; - maxy = m_userMaxy; - } - else - { - minx = miny = 0; - maxx = maxy = -1; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Tessellates a path, and computes its bounding box in surface space. -* \param -* \return -* \note if runs out of memory, throws bad_alloc and leaves the path as it was -*//*-------------------------------------------------------------------*/ - -void Path::getPathTransformedBounds(const Matrix3x3& pathToSurface, RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy) -{ - RI_ASSERT(m_referenceCount > 0); - RI_ASSERT(pathToSurface.isAffine()); - - Matrix3x3 identity; - identity.identity(); - tessellate(identity, 0.0f); //throws bad_alloc - - if(m_vertices.size()) - { - Vector3 p0(m_userMinx, m_userMiny, 1.0f); - Vector3 p1(m_userMinx, m_userMaxy, 1.0f); - Vector3 p2(m_userMaxx, m_userMaxy, 1.0f); - Vector3 p3(m_userMaxx, m_userMiny, 1.0f); - p0 = pathToSurface * p0; - p1 = pathToSurface * p1; - p2 = pathToSurface * p2; - p3 = pathToSurface * p3; - - minx = RI_MIN(RI_MIN(RI_MIN(p0.x, p1.x), p2.x), p3.x); - miny = RI_MIN(RI_MIN(RI_MIN(p0.y, p1.y), p2.y), p3.y); - maxx = RI_MAX(RI_MAX(RI_MAX(p0.x, p1.x), p2.x), p3.x); - maxy = RI_MAX(RI_MAX(RI_MAX(p0.y, p1.y), p2.y), p3.y); - } - else - { - minx = miny = 0; - maxx = maxy = -1; - } -} - -/*-------------------------------------------------------------------*//*! -* \brief Adds a vertex to a tessellated path. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Path::addVertex(const Vector2& p, const Vector2& t, RIfloat pathLength, unsigned int flags) -{ - RI_ASSERT(!isZero(t)); - - Vertex v; - v.pathLength = pathLength; - v.userPosition = p; - v.userTangent = t; - v.flags = flags; - m_vertices.push_back(v); //throws bad_alloc - m_numTessVertices++; - - m_userMinx = RI_MIN(m_userMinx, v.userPosition.x); - m_userMiny = RI_MIN(m_userMiny, v.userPosition.y); - m_userMaxx = RI_MAX(m_userMaxx, v.userPosition.x); - m_userMaxy = RI_MAX(m_userMaxy, v.userPosition.y); -} - -/*-------------------------------------------------------------------*//*! -* \brief Adds an edge to a tessellated path. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Path::addEdge(const Vector2& p0, const Vector2& p1, const Vector2& t0, const Vector2& t1, unsigned int startFlags, unsigned int endFlags) -{ - Vertex v; - RIfloat pathLength = 0.0f; - - RI_ASSERT(!isZero(t0) && !isZero(t1)); - - //segment midpoints are shared between edges - if(!m_numTessVertices) - { - if(m_vertices.size() > 0) - pathLength = m_vertices[m_vertices.size()-1].pathLength; - - addVertex(p0, t0, pathLength, startFlags); //throws bad_alloc - } - - //other than implicit close paths (caused by a MOVE_TO) add to path length - if( !(endFlags & IMPLICIT_CLOSE_SUBPATH) ) - { - //NOTE: with extremely large coordinates the floating point path length is infinite - RIfloat l = (p1 - p0).length(); - pathLength = m_vertices[m_vertices.size()-1].pathLength + l; - pathLength = RI_MIN(pathLength, RI_FLOAT_MAX); - } - - addVertex(p1, t1, pathLength, endFlags); //throws bad_alloc -} - -/*-------------------------------------------------------------------*//*! -* \brief Tessellates a close-path segment. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Path::addEndPath(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry, unsigned int flags) -{ - RI_UNREF(pathToSurface); - m_numTessVertices = 0; - if(!subpathHasGeometry) - { //single vertex - Vector2 t(1.0f,0.0f); - addEdge(p0, p1, t, t, START_SEGMENT | START_SUBPATH, END_SEGMENT | END_SUBPATH); //throws bad_alloc - m_numTessVertices = 0; - addEdge(p0, p1, -t, -t, IMPLICIT_CLOSE_SUBPATH | START_SEGMENT, IMPLICIT_CLOSE_SUBPATH | END_SEGMENT); //throws bad_alloc - return; - } - //the subpath contains segment commands that have generated geometry - - //add a close path segment to the start point of the subpath - RI_ASSERT(m_vertices.size() > 0); - m_vertices[m_vertices.size()-1].flags |= END_SUBPATH; - - Vector2 t = normalize(p1 - p0); - if(isZero(t)) - t = m_vertices[m_vertices.size()-1].userTangent; //if the segment is zero-length, use the tangent of the last segment end point so that proper join will be generated - RI_ASSERT(!isZero(t)); - - addEdge(p0, p1, t, t, flags | START_SEGMENT, flags | END_SEGMENT); //throws bad_alloc -} - -/*-------------------------------------------------------------------*//*! -* \brief Tessellates a line-to segment. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool Path::addLineTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, bool subpathHasGeometry) -{ - RI_UNREF(pathToSurface); - if(p0 == p1) - return false; //discard zero-length segments - - //compute end point tangents - Vector2 t = normalize(p1 - p0); - RI_ASSERT(!isZero(t)); - - m_numTessVertices = 0; - unsigned int startFlags = START_SEGMENT; - if(!subpathHasGeometry) - startFlags |= START_SUBPATH; - addEdge(p0, p1, t, t, startFlags, END_SEGMENT); //throws bad_alloc - return true; -} - -/*-------------------------------------------------------------------*//*! -* \brief Tessellates a quad-to segment. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -bool Path::addQuadTo(const Matrix3x3& pathToSurface, const Vector2& p0, const Vector2& p1, const Vector2& p2, bool subpathHasGeometry, float strokeWidth) -{ - RI_UNREF(pathToSurface); - RI_UNREF(strokeWidth); - if(p0 == p1 && p0 == p2) - { - RI_ASSERT(p1 == p2); - return false; //discard zero-length segments - } - - //compute end point tangents - - Vector2 incomingTangent = normalize(p1 - p0); - Vector2 outgoingTangent = normalize(p2 - p1); - if(p0 == p1) - incomingTangent = normalize(p2 - p0); - if(p1 == p2) - outgoingTangent = normalize(p2 - p0); - RI_ASSERT(!isZero(incomingTangent) && !isZero(outgoingTangent)); - - m_numTessVertices = 0; - unsigned int startFlags = START_SEGMENT; - if(!subpathHasGeometry) - startFlags |= START_SUBPATH; - - const int segments = RI_NUM_TESSELLATED_SEGMENTS_QUAD; - Vector2 pp = p0; - Vector2 tp = incomingTangent; - unsigned int prevFlags = startFlags; - for(int i=1;i 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= 0 ) - { - RI_ASSERT(segmentStarted); - RI_ASSERT(subpathStarted || ((m_vertices[prev].flags & CLOSE_SUBPATH) && (m_vertices[i].flags & CLOSE_SUBPATH)) || - ((m_vertices[prev].flags & IMPLICIT_CLOSE_SUBPATH) && (m_vertices[i].flags & IMPLICIT_CLOSE_SUBPATH))); - } - - prev = i; - if(v.flags & END_SEGMENT) - { - RI_ASSERT(subpathStarted || (v.flags & CLOSE_SUBPATH) || (v.flags & IMPLICIT_CLOSE_SUBPATH)); - RI_ASSERT(segmentStarted); - RI_ASSERT(!(v.flags & START_SUBPATH)); - RI_ASSERT(!(v.flags & START_SEGMENT)); - segmentStarted = false; - prev = -1; - } - - if(v.flags & END_SUBPATH) - { - RI_ASSERT(subpathStarted); - RI_ASSERT(v.flags & END_SEGMENT); - RI_ASSERT(!(v.flags & START_SUBPATH)); - RI_ASSERT(!(v.flags & START_SEGMENT)); - RI_ASSERT(!(v.flags & CLOSE_SUBPATH)); - RI_ASSERT(!(v.flags & IMPLICIT_CLOSE_SUBPATH)); - subpathStarted = false; - } - } -#endif //RI_DEBUG - } - catch(std::bad_alloc) - { - m_vertices.clear(); - throw; - } -} - -//============================================================================================== - -} //namespace OpenVGRI - -//============================================================================================== diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riPath.h --- a/hostsupport/hostopenvg/src/src/riPath.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,192 +0,0 @@ -#ifndef __RIPATH_H -#define __RIPATH_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Path class. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef _OPENVG_H -#include "openvg.h" -#endif - -#ifndef __RIMATH_H -#include "riMath.h" -#endif - -#ifndef __RIARRAY_H -#include "riArray.h" -#endif - -#ifndef __RIRASTERIZER_H -#include "riRasterizer.h" -#endif - -//============================================================================================== - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief Storage and operations for VGPath. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class Path -{ -public: - Path(VGint format, VGPathDatatype datatype, RIfloat scale, RIfloat bias, int segmentCapacityHint, int coordCapacityHint, VGbitfield caps); //throws bad_alloc - ~Path(); - - VGint getFormat() const { return m_format; } - VGPathDatatype getDatatype() const { return m_datatype; } - RIfloat getScale() const { return m_scale; } - RIfloat getBias() const { return m_bias; } - VGbitfield getCapabilities() const { return m_capabilities; } - void setCapabilities(VGbitfield caps) { m_capabilities = caps; } - int getNumSegments() const { return m_segments.size(); } - int getNumCoordinates() const { return m_data.size() / getBytesPerCoordinate(m_datatype); } - void addReference() { m_referenceCount++; } - int removeReference() { m_referenceCount--; RI_ASSERT(m_referenceCount >= 0); return m_referenceCount; } - - void clear(VGbitfield capabilities); - void appendData(const RIuint8* segments, int numSegments, const RIuint8* data); //throws bad_alloc - void append(const Path* srcPath); //throws bad_alloc - void modifyCoords(int startIndex, int numSegments, const RIuint8* data); - void transform(const Path* srcPath, const Matrix3x3& matrix); //throws bad_alloc - //returns true if interpolation succeeds, false if start and end paths are not compatible - bool interpolate(const Path* startPath, const Path* endPath, RIfloat amount); //throws bad_alloc - void fill(const Matrix3x3& pathToSurface, Rasterizer& rasterizer); //throws bad_alloc - void stroke(const Matrix3x3& pathToSurface, Rasterizer& rasterizer, const Array& dashPattern, RIfloat dashPhase, bool dashPhaseReset, RIfloat strokeWidth, VGCapStyle capStyle, VGJoinStyle joinStyle, RIfloat miterLimit); //throws bad_alloc - - void getPointAlong(int startIndex, int numSegments, RIfloat distance, Vector2& p, Vector2& t); //throws bad_alloc - RIfloat getPathLength(int startIndex, int numSegments); //throws bad_alloc - void getPathBounds(RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy); //throws bad_alloc - void getPathTransformedBounds(const Matrix3x3& pathToSurface, RIfloat& minx, RIfloat& miny, RIfloat& maxx, RIfloat& maxy); //throws bad_alloc - int coordsSizeInBytes( int startIndex, int numSegments ); - -private: - enum VertexFlags - { - START_SUBPATH = (1<<0), - END_SUBPATH = (1<<1), - START_SEGMENT = (1<<2), - END_SEGMENT = (1<<3), - CLOSE_SUBPATH = (1<<4), - IMPLICIT_CLOSE_SUBPATH = (1<<5) - }; - struct Vertex - { - Vertex() : userPosition(), userTangent(), pathLength(0.0f), flags(0) {} - Vector2 userPosition; - Vector2 userTangent; - RIfloat pathLength; - unsigned int flags; - }; - struct StrokeVertex - { - StrokeVertex() : p(), t(), ccw(), cw(), pathLength(0.0f), flags(0), inDash(false) {} - Vector2 p; - Vector2 t; - Vector2 ccw; - Vector2 cw; - RIfloat pathLength; - unsigned int flags; - bool inDash; - }; - - Path(const Path&); //!< Not allowed. - const Path& operator=(const Path&); //!< Not allowed. - - static VGPathSegment getPathSegment(RIuint8 data) { return (VGPathSegment)(data & 0x1e); } - static VGPathAbsRel getPathAbsRel(RIuint8 data) { return (VGPathAbsRel)(data & 0x1); } - static int segmentToNumCoordinates(VGPathSegment segment); - static int countNumCoordinates(const RIuint8* segments, int numSegments); - static int getBytesPerCoordinate(VGPathDatatype datatype); - - static void setCoordinate(Array& 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 m_segments; - Array m_data; - - //data produced by tessellation - struct VertexIndex - { - int start; - int end; - }; - Array m_vertices; - int m_numTessVertices; - Array m_segmentToVertex; - RIfloat m_userMinx; - RIfloat m_userMiny; - RIfloat m_userMaxx; - RIfloat m_userMaxy; - - bool m_mirror; -}; - -//============================================================================================== - -} //namespace OpenVGRI - -//============================================================================================== - -#endif /* __RIPATH_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riPixelPipe.cpp --- a/hostsupport/hostopenvg/src/src/riPixelPipe.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1440 +0,0 @@ -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementation of Paint and pixel pipe functionality. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef __RIPIXELPIPE_H -# include "riPixelPipe.h" -#endif -#ifndef __RIRASTERIZER_H -# include "riRasterizer.h" -#endif -#ifndef __SFDYNAMICPIXELPIPE_H -# include "sfDynamicPixelPipe.h" -#endif -#ifndef __SFCOMPILER_H -# include "sfCompiler.h" -#endif - -//============================================================================================== - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief Paint constructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Paint::Paint() : - m_paintType(VG_PAINT_TYPE_COLOR), - m_paintColor(0,0,0,1,Color::sRGBA_PRE), - m_inputPaintColor(0,0,0,1,Color::sRGBA), - m_colorRampSpreadMode(VG_COLOR_RAMP_SPREAD_PAD), - m_colorRampStops(), - m_inputColorRampStops(), - m_colorRampPremultiplied(VG_TRUE), - m_inputLinearGradientPoint0(0,0), - m_inputLinearGradientPoint1(1,0), - m_inputRadialGradientCenter(0,0), - m_inputRadialGradientFocalPoint(0,0), - m_inputRadialGradientRadius(1.0f), - m_linearGradientPoint0(0,0), - m_linearGradientPoint1(1,0), - m_radialGradientCenter(0,0), - m_radialGradientFocalPoint(0,0), - m_radialGradientRadius(1.0f), - m_patternTilingMode(VG_TILE_FILL), - m_pattern(NULL), - m_referenceCount(0), - m_lutFormat((VGImageFormat)-1), - m_gradientStopsChanged(true) -{ - Paint::GradientStop gs; - gs.offset = 0.0f; - gs.color.set(0,0,0,1,Color::sRGBA); - m_colorRampStops.push_back(gs); //throws bad_alloc - gs.offset = 1.0f; - gs.color.set(1,1,1,1,Color::sRGBA); - m_colorRampStops.push_back(gs); //throws bad_alloc -} - -/*-------------------------------------------------------------------*//*! -* \brief Paint destructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Paint::~Paint() -{ - RI_ASSERT(m_referenceCount == 0); - if(m_pattern) - { - m_pattern->removeInUse(); - if(!m_pattern->removeReference()) - RI_DELETE(m_pattern); - } -} - -static Color readStopColor(const Array& colorRampStops, int i, VGboolean colorRampPremultiplied) -{ - RI_ASSERT(i >= 0 && i < colorRampStops.size()); - Color c = colorRampStops[i].color; - RI_ASSERT(c.getInternalFormat() == Color::sRGBA); - if(colorRampPremultiplied) - c.premultiply(); - return c; -} - -void Paint::setGradientStops(Array& inputStops, Array& stops) -{ - m_colorRampStops.swap(stops); - m_inputColorRampStops.swap(inputStops); - m_gradientStopsChanged = true; -} - -void Paint::setLinearGradient(const Vector2& p0, const Vector2& p1) -{ - m_linearGradientPoint0 = p0; - m_linearGradientPoint1 = p1; -} - -void Paint::setRadialGradient(const Vector2& c, const Vector2& f, VGfloat r) -{ - m_radialGradientCenter = c; - m_radialGradientFocalPoint = f; - m_radialGradientRadius = r; -} - -bool Paint::linearDegenerate() const -{ - return m_linearGradientPoint0 == m_linearGradientPoint1 ? true : false; -} - -bool Paint::radialDegenerate() const -{ - return m_radialGradientRadius == 0.0f ? true : false; -} - -/** - * \brief Returns either the VG_PAINT_COLOR, or evaluated gradient value when the - * gradient is degenerate. - */ -Color Paint::getSolidColor() const -{ - if (m_paintType == VG_PAINT_TYPE_PATTERN) - { - RI_ASSERT(m_pattern == NULL); - return m_paintColor; - } - - if (m_paintType == VG_PAINT_TYPE_COLOR) - return m_paintColor; - - RI_ASSERT(linearDegenerate() || radialDegenerate()); - - // Determine the color at the end of the gradient - RIfloat gs, ge; - if (m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_PAD) - { - gs = 1.0f - 1/256.0f; - ge = 1.0f; - } else if (m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT) - { - gs = 0.0f; - ge = 1/256.0f; - } else - { - gs = 1.0f - 1/256.0f; - ge = 1.0f; - } - Color c = integrateColorRamp(gs, ge); - return c * 256.0f; -} - -/*-------------------------------------------------------------------*//*! -* \brief Returns the average color within an offset range in the color ramp. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Color Paint::integrateColorRamp(RIfloat gmin, RIfloat gmax) const -{ - RI_ASSERT(gmin <= gmax); - RI_ASSERT(gmin >= 0.0f && gmin <= 1.0f); - RI_ASSERT(gmax >= 0.0f && gmax <= 1.0f); - RI_ASSERT(m_colorRampStops.size() >= 2); //there are at least two stops - - Color currC(0,0,0,0,m_colorRampPremultiplied ? Color::sRGBA_PRE : Color::sRGBA); - - if(gmin == 1.0f || gmax == 0.0f) - return currC; - - int i = 0; - - for(; i < m_colorRampStops.size()-1; i++) - { - if(gmin >= m_colorRampStops[i].offset && gmin < m_colorRampStops[i+1].offset) - { - RIfloat s = m_colorRampStops[i].offset; - RIfloat e = m_colorRampStops[i+1].offset; - RI_ASSERT(s < e); - RIfloat g = (gmin - s) / (e - s); - - Color sc = readStopColor(m_colorRampStops, i, m_colorRampPremultiplied); - Color ec = readStopColor(m_colorRampStops, i+1, m_colorRampPremultiplied); - Color rc = (1.0f-g) * sc + g * ec; - - //subtract the average color from the start of the stop to gmin - Color dc = 0.5f*(gmin - s)*(sc + rc); - currC -= dc; - break; - } - } - - for(;i < m_colorRampStops.size()-1; i++) - { - RIfloat s = m_colorRampStops[i].offset; - RIfloat e = m_colorRampStops[i+1].offset; - RI_ASSERT(s <= e); - - Color sc = readStopColor(m_colorRampStops, i, m_colorRampPremultiplied); - Color ec = readStopColor(m_colorRampStops, i+1, m_colorRampPremultiplied); - - //average of the stop - Color dc = 0.5f*(e-s)*(sc + ec); - currC += dc; - - if(gmax >= m_colorRampStops[i].offset && gmax < m_colorRampStops[i+1].offset) - { - RIfloat g = (gmax - s) / (e - s); - Color rc = (1.0f-g) * sc + g * ec; - - //subtract the average color from gmax to the end of the stop - dc = 0.5f*(e - gmax)*(rc + ec); - currC -= dc; - break; - } - } - - return currC; -} - -/** - * \brief Generates gradient color-ramp lookup values. - * - * \param targetFormat Destination or image format to associate LUT with. - * \patam drawImage true if paint is evaluated along drawImage. - * - * \note Must be called prior to rendering, and after the destination - * format is known. The destination format is either destination - * surface format, or the image format in case of image rendering - * operation. - */ -void Paint::generateLUT(PixelPipe& pipe, VGImageFormat preferredFormat) -{ - const RIfloat gstep = 1.0f / (GRADIENT_LUT_COUNT); - const RIfloat rcp = (RIfloat)(GRADIENT_LUT_COUNT); - RIfloat gsx; - gsx = 0.0f; - - if (!pipe.colorTransformChanged() && !m_gradientStopsChanged && (preferredFormat == m_lutFormat)) - return; // Already in correct format - - const bool inputPremultiplied = m_colorRampPremultiplied == VG_TRUE ? true : false; - - // Colortransform premultiplies color. - const Color::Descriptor srcDesc = Color::formatToDescriptorConst( - inputPremultiplied || pipe.hasColorTransform() ? VG_sRGBA_8888_PRE : VG_sRGBA_8888); - - const Color::Descriptor dstDesc = Color::formatToDescriptorConst(preferredFormat); - - // Create a pre-calculated LUT. - for (int i = 0; i < GRADIENT_LUT_COUNT; i++) - { - // \todo Open up the integrator and/or use also integers. - Color c = integrateColorRamp(gsx, gsx + gstep); - c *= rcp; - - // \todo Changing the mode must be tracked somehow! - if (pipe.getImageMode() != VG_DRAW_IMAGE_MULTIPLY) - pipe.colorTransform(c); - - IntegerColor ic = IntegerColor(c); - ic.convertToFrom(dstDesc, srcDesc, false); - m_gradientLUT[i] = ic; - - gsx += gstep; - } - - m_gradientStopsChanged = false; - m_lutFormat = Color::descriptorToVGImageFormat(dstDesc); - pipe.setColorTransformChanged(false); - - RI_ASSERT(m_lutFormat == preferredFormat); -} - -/*-------------------------------------------------------------------*//*! -* \brief PixelPipe constructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -PixelPipe::PixelPipe() : - m_drawable(NULL), - m_image(NULL), - m_paint(NULL), - m_defaultPaint(), - m_blendMode(VG_BLEND_SRC_OVER), - m_imageMode(VG_DRAW_IMAGE_NORMAL), - m_imageQuality(VG_IMAGE_QUALITY_FASTER), - m_tileFillColor(0,0,0,0,Color::sRGBA), - m_colorTransform(false), - m_colorTransformValues(), - m_iColorTransformValues(), - m_surfaceToPaintMatrix(), - m_surfaceToImageMatrix(), - m_paintToSurfaceMatrix(), - m_maskOperation(VG_SET_MASK), - m_renderToMask(false), - m_colorTransformChanged(true) -{ - for(int i=0;i<8;i++) - { - m_colorTransformValues[i] = (i < 4) ? 1.0f : 0.0f; - m_iColorTransformValues[i] = (i < 4) ? (COLOR_TRANSFORM_ONE) : 0; - } -} - - -/*-------------------------------------------------------------------*//*! -* \brief PixelPipe destructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -PixelPipe::~PixelPipe() -{ -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets the rendering surface. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setDrawable(Drawable* drawable) -{ - RI_ASSERT(drawable); - m_drawable = drawable; -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets the blend mode. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setBlendMode(VGBlendMode blendMode) -{ - RI_ASSERT(blendMode >= VG_BLEND_SRC && blendMode <= VG_BLEND_ADDITIVE); - m_blendMode = blendMode; -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets the mask image. NULL disables masking. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setMask(bool masking) -{ - m_masking = masking; -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets the image to be drawn. NULL disables image drawing. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setImage(Image* image, VGImageMode imageMode) -{ - RI_ASSERT(imageMode == VG_DRAW_IMAGE_NORMAL || imageMode == VG_DRAW_IMAGE_MULTIPLY || imageMode == VG_DRAW_IMAGE_STENCIL); - m_image = image; - m_imageMode = imageMode; -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets the surface-to-paint matrix. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setSurfaceToPaintMatrix(const Matrix3x3& surfaceToPaintMatrix) -{ - m_surfaceToPaintMatrix = surfaceToPaintMatrix; -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets the surface-to-image matrix. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setSurfaceToImageMatrix(const Matrix3x3& surfaceToImageMatrix) -{ - m_surfaceToImageMatrix = surfaceToImageMatrix; -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets image quality. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setImageQuality(VGImageQuality imageQuality) -{ - RI_ASSERT(imageQuality == VG_IMAGE_QUALITY_NONANTIALIASED || imageQuality == VG_IMAGE_QUALITY_FASTER || imageQuality == VG_IMAGE_QUALITY_BETTER); - m_imageQuality = imageQuality; -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets fill color for VG_TILE_FILL tiling mode (pattern only). -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setTileFillColor(const Color& c) -{ - m_tileFillColor = c; - m_tileFillColor.clamp(); -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets paint. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setPaint(Paint* paint) -{ - // \temp Only call this right before filling a polygon. - m_paint = paint; - - if(!m_paint) - m_paint = &m_defaultPaint; - - if(m_paint->m_pattern) - m_tileFillColor.convert(m_paint->m_pattern->getDescriptor().internalFormat); - -} - -/*-------------------------------------------------------------------*//*! -* \brief Color transform. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::setColorTransform(bool enable, RIfloat values[8]) -{ - m_colorTransform = enable; - for(int i=0;i<4;i++) - { - m_colorTransformValues[i] = RI_CLAMP(values[i], -127.0f, 127.0f); - m_colorTransformValues[i+4] = RI_CLAMP(values[i+4], -1.0f, 1.0f); - m_iColorTransformValues[i] = RI_ROUND_TO_INT(m_colorTransformValues[i]*(RIfloat)COLOR_TRANSFORM_ONE); - m_iColorTransformValues[i+4] = RI_ROUND_TO_INT(m_colorTransformValues[i+4]*255.0f); - } - m_colorTransformChanged = true; -} - -const Image* PixelPipe::getRenderTargetImage() const -{ - if (m_renderToMask) - return m_drawable->getMaskBuffer()->getImage(); - - return m_drawable->getColorBuffer()->getImage(); -} - -/** - * \brief Determine an appropriate VGImageFormat to use for lookup tables. - * \todo Should return descriptor instead? - */ -VGImageFormat PixelPipe::getPreferredLUTFormat() const -{ - const Image* target = getRenderTargetImage(); - const Color::Descriptor& targetDesc = target->getDescriptor(); - - if (m_renderToMask) - { - RI_ASSERT(!m_image); - if (targetDesc.isNonlinear()) - return VG_sRGBA_8888_PRE; - else - return VG_lRGBA_8888_PRE; - } - - if (m_image && m_imageMode == VG_DRAW_IMAGE_MULTIPLY) - return VG_sRGBA_8888_PRE; // ? - - // Prefer premultiplied formats - // \note Can also generate non-premultiplied if no sampling/other operation and destination - // is in linear format. - // \note Do not use VGImageFormat, because using (s/l)LA88 is possible with - // luminance destination formats. - if (targetDesc.isNonlinear()) - return VG_sRGBA_8888_PRE; - else - return VG_lRGBA_8888_PRE; -} - -void PixelPipe::prepareSolidFill() -{ - if (!(m_drawable && m_paint)) - return; - - Color c = m_paint->getSolidColor(); - //Color c = m_paint->m_paintColor; - - if (!m_image || m_imageMode != VG_DRAW_IMAGE_MULTIPLY) - colorTransform(c); // Output will be premultiplied - // Generate internal color - Color::Descriptor blendDesc = getRenderTargetImage()->getDescriptor(); - - // MULTIPLY uses the color as-is. - if (m_imageMode != VG_DRAW_IMAGE_MULTIPLY) c.convert(blendDesc.internalFormat); - - IntegerColor ic = IntegerColor(c); - blendDesc.internalFormat = (Color::InternalFormat)(blendDesc.internalFormat | (Color::PREMULTIPLIED)); - - if (m_imageMode != VG_DRAW_IMAGE_MULTIPLY) c.convert(blendDesc.internalFormat); - - IntegerColor blendColor = IntegerColor(c); - - if (m_imageMode == VG_DRAW_IMAGE_STENCIL) - blendColor.asFixedPoint(c); // Enhance the precision a bit - - // \todo No need to pack the color if solid fill is not possible - if (!m_renderToMask) - ic.truncateColor(getRenderTargetImage()->getDescriptor()); - else - ic.truncateMask(getRenderTargetImage()->getDescriptor()); - - RIuint32 p = ic.getPackedColor(getRenderTargetImage()->getDescriptor()); - - m_spanUniforms.solidColor = blendColor; // This must be premultiplied - m_spanUniforms.packedSolidColor = p; // This must be exactly the dst color -} - -void PixelPipe::prepareCoverageFill() -{ - IntegerColor ic = IntegerColor(255, 255, 255, 255); - RIuint32 p = ic.getPackedColor(m_drawable->getMaskBuffer()->getDescriptor()); - - m_spanUniforms.solidColor = ic; - m_spanUniforms.packedSolidColor = p; -} - -void PixelPipe::prepareLinearGradient() -{ - const Matrix3x3& s2p = m_surfaceToPaintMatrix; - - Vector2 zero(0,0); - Vector2 p0 = m_paint->m_linearGradientPoint0; - Vector2 p1 = m_paint->m_linearGradientPoint1; - Vector2 delta = p1 - p0; - - zero = affineTransform(s2p, zero); - - RIfloat d = (delta.x * delta.x) + (delta.y * delta.y); - RIfloat gdx = (s2p[0][0] * delta.x + s2p[1][0] * delta.y) / d; - RIfloat gdy = (s2p[0][1] * delta.x + s2p[1][1] * delta.y) / d; - RIfloat cx = (zero.x-p0.x) * (delta.x); - RIfloat cy = (zero.y-p0.y) * (delta.y); - RIfloat c = (cx + cy) / d; - - m_spanUniforms.dgdx = RI_FLOAT_TO_FX(gdx, PixelPipe::GRADIENT_BITS); - m_spanUniforms.dgdy = RI_FLOAT_TO_FX(gdy, PixelPipe::GRADIENT_BITS); - m_spanUniforms.lgc = RI_FLOAT_TO_FX(c + 0.5*(gdx + gdy), PixelPipe::GRADIENT_BITS); - - m_spanUniforms.gradientLookup = m_paint->getGradientLUT(); -} - -void PixelPipe::prepareRadialGradient() -{ - const Matrix3x3& s2p = m_surfaceToPaintMatrix; - - Vector2 c = m_paint->m_radialGradientCenter; - Vector2 f = m_paint->m_radialGradientFocalPoint; - RGScalar r = m_paint->m_radialGradientRadius; - - Vector2 zero(0,0); - Vector2 pzero = affineTransform(s2p, zero); - - Vector2 fp = f - c; - - RGScalar q = fp.length(); - - if (q > r) - { - const RIfloat scale = 0.99f; - fp.normalize(); - fp *= r * scale; - f = fp + c; - } - - RGScalar r1sqr = RI_SQR(r); - RGScalar d = r1sqr - dot(fp, fp); - - m_spanUniforms.rdxdx = s2p[0][0]; - m_spanUniforms.rdxdy = s2p[0][1]; - m_spanUniforms.rdydx = s2p[1][0]; - m_spanUniforms.rdydy = s2p[1][1]; - - m_spanUniforms.rsqrp = r1sqr / RI_SQR(d); - m_spanUniforms.rfxp = fp.x / d; - m_spanUniforms.rfyp = fp.y / d; - m_spanUniforms.rx0 = pzero.x - f.x + 0.5f*(m_spanUniforms.rdxdx + m_spanUniforms.rdxdy); - m_spanUniforms.ry0 = pzero.y - f.y + 0.5f*(m_spanUniforms.rdydy + m_spanUniforms.rdydx); - - m_spanUniforms.gradientLookup = m_paint->getGradientLUT(); -} - -void PixelPipe::preparePattern() -{ - // Patterns only support affine transforms - const Matrix3x3& s2p = m_surfaceToPaintMatrix; - const RIfloat patternWidth = (RIfloat)m_paint->m_pattern->getWidth(); - const RIfloat patternHeight = (RIfloat)m_paint->m_pattern->getHeight(); - const Vector2 zero(0, 0); - Vector2 pzero = affineTransform(s2p, zero); - - m_spanUniforms.paint_x0 = RI_ROUND_TO_INT((pzero.x/patternWidth)*(1<m_pattern->getData(); - m_spanUniforms.patternStride = m_paint->m_pattern->getStride(); - m_spanUniforms.paint_width = m_paint->m_pattern->getWidth(); - m_spanUniforms.paint_height = m_paint->m_pattern->getHeight(); - - m_signatureState.patternDesc = m_paint->m_pattern->getDescriptor(); - - m_spanUniforms.tileFillColor = IntegerColor(m_tileFillColor); - // The tile fill-color must be shifted down to same bit-depth (see integer samplers) - m_spanUniforms.tileFillColor.truncateColor(m_signatureState.patternDesc); - -} - -RI_INLINE static RIfloat floatEqu(RIfloat a, RIfloat b, RIfloat e) -{ - // \note This should be sufficient for our use-cases; - return (RI_ABS(a - b) < e); -} - -RI_INLINE static RIfloat distToInt(RIfloat f) -{ - const RIfloat intF = RI_ROUND_TO_INT(f); - return RI_ABS(intF - f); -} - -/** - * \brief Check if transform is 90 degree rotation, or flip and nothing else. - */ -RI_INLINE static bool orthoNormalCoAxialTransform(const Matrix3x3& t, bool aa) -{ - const RIfloat epsilonCoord = 1/255.0f; // 1/127.0f; - const RIfloat epsilonGradient = epsilonCoord * epsilonCoord; // \todo Too strict? - const RIfloat absPatterns[2][4] = { - {1.0f, 0.0f, 0.0f, 1.0f}, - {0.0f, 1.0f, 1.0f, 0.0f} }; - - if (!t.isAffine()) - return false; - - // \todo This rule only applies if filtering is in use? - if (aa) - if (!floatEqu(distToInt(t[0][2]), 0.0f, epsilonCoord) || !floatEqu(distToInt(t[1][2]), 0.0f, epsilonCoord)) - return false; - - Matrix3x3 u = t; - - for (int j = 0; j < 2; j++) - for (int i = 0; i < 2; i++) - u[j][i] = RI_ABS(u[j][i]); - - bool found; - - for (int m = 0; m < 2; m++) - { - found = true; - for (int j = 0; j < 2; j++) - { - for (int i = 0; i < 2; i++) - { - //if (u[j][i] != absPatterns[m][i+j*2]) - if (!floatEqu(u[j][i], absPatterns[m][i+j*2], epsilonGradient)) - { - found = false; - break; - } - } - if (!found) break; - } - if (found) break; - } - - return found; -} - -void PixelPipe::prepareImage(bool aa) -{ - if (!m_image) - { - m_signatureState.imageGradientType = GRADIENT_TYPE_INTEGER; - return; - } - - RI_ASSERT(m_image); - m_spanUniforms.imagePtr = m_image->getData(); - m_spanUniforms.imageStride = m_image->getStride(); - - if (m_image->getParent() != NULL) - { - // Adjust the pointer. - int x, y; - m_image->getStorageOffset(x, y); - m_spanUniforms.imagePtr = Image::calculateAddress( - m_spanUniforms.imagePtr, m_image->getDescriptor().bitsPerPixel, x, y, m_spanUniforms.imageStride); - } - - // \todo This function writes to derived state also. - // \todo Plenty of fast-paths possible! - const Matrix3x3& s2i = m_surfaceToImageMatrix; - - Vector3 zero(0,0,1); - Vector3 pzero; - - bool fastImage = orthoNormalCoAxialTransform(s2i, aa); - - pzero = s2i * zero; - - if (fastImage) - { - RI_ASSERT(pzero.z == 1.0f); - m_spanUniforms.image_idxdx = RI_ROUND_TO_INT(s2i[0][0]); - m_spanUniforms.image_idxdy = RI_ROUND_TO_INT(s2i[0][1]); - m_spanUniforms.image_idydx = RI_ROUND_TO_INT(s2i[1][0]); - m_spanUniforms.image_idydy = RI_ROUND_TO_INT(s2i[1][1]); - m_spanUniforms.image_ix0 = RI_FLOOR(pzero.x + 0.5f*(s2i[0][0]+s2i[0][1])); - m_spanUniforms.image_iy0 = RI_FLOOR(pzero.y + 0.5f*(s2i[1][1]+s2i[1][0])); - - // Adjust sample-center when using (exactly) integer coordinates. - -#if 0 - if (m_spanUniforms.image_idxdx < 0 || m_spanUniforms.image_idxdy < 0) - m_spanUniforms.image_ix0--; - - if (m_spanUniforms.image_idydy < 0 || m_spanUniforms.image_idydx < 0) - m_spanUniforms.image_iy0--; -#endif - - m_signatureState.imageGradientType = GRADIENT_TYPE_INTEGER; - } - else if (s2i.isAffine()) - { - RI_ASSERT(pzero.z == 1.0f); - const RIfloat imageWidth = m_image->getWidth(); - const RIfloat imageHeight = m_image->getHeight(); - - m_spanUniforms.image_idxdx = RI_ROUND_TO_INT((s2i[0][0]/imageWidth)*(1<getWidth(); - m_spanUniforms.image_fHeight = (RIfloat)m_image->getHeight(); - - m_signatureState.imageGradientType = GRADIENT_TYPE_FLOAT; - } - - m_signatureState.imageDesc = m_image->getDescriptor(); -} - -static PixelPipe::TilingMode tilingModeOfImageTilingMode(VGTilingMode it) -{ - switch(it) - { - case VG_TILE_PAD: - return PixelPipe::TILING_MODE_PAD; - case VG_TILE_REPEAT: - return PixelPipe::TILING_MODE_REPEAT; - case VG_TILE_REFLECT: - return PixelPipe::TILING_MODE_REFLECT; - default: - RI_ASSERT(it == VG_TILE_FILL); - return PixelPipe::TILING_MODE_FILL; - } -} - -static PixelPipe::TilingMode tilingModeOfSpreadMode(VGColorRampSpreadMode sm) -{ - switch(sm) - { - case VG_COLOR_RAMP_SPREAD_PAD: - return PixelPipe::TILING_MODE_PAD; - case VG_COLOR_RAMP_SPREAD_REPEAT: - return PixelPipe::TILING_MODE_REPEAT; - default: - RI_ASSERT(sm == VG_COLOR_RAMP_SPREAD_REFLECT); - return PixelPipe::TILING_MODE_REFLECT; - } -} - -static PixelPipe::TilingMode tilingModeOfPaint(const Paint* paint) -{ - switch(paint->m_paintType) - { - case VG_PAINT_TYPE_COLOR: - return PixelPipe::TILING_MODE_PAD; - case VG_PAINT_TYPE_LINEAR_GRADIENT: - case VG_PAINT_TYPE_RADIAL_GRADIENT: - return tilingModeOfSpreadMode(paint->m_colorRampSpreadMode); - default: - RI_ASSERT(paint->m_paintType == VG_PAINT_TYPE_PATTERN); - return tilingModeOfImageTilingMode(paint->m_patternTilingMode); - } -} - -void PixelPipe::prepareRenderToMask() -{ - RI_ASSERT(m_drawable->getMaskBuffer()); - - m_signatureState.dstDesc = m_drawable->getMaskBuffer()->getDescriptor(); - //RI_ASSERT(m_signatureState.dstFormat >= 0 && m_signatureState.dstFormat <= VG_lABGR_8888_PRE); - - m_signatureState.maskOperation = m_maskOperation; -} - -void PixelPipe::prepareSignatureState() -{ - m_signatureState.isRenderToMask = m_renderToMask; - - if (m_signatureState.isRenderToMask) - { - prepareRenderToMask(); - return; - } - - m_signatureState.blendMode = getBlendMode(); - - m_signatureState.hasColorTransform = this->m_colorTransform; - - m_signatureState.paintType = getPaintType(); - - m_signatureState.paintTilingMode = tilingModeOfPaint(m_paint); - // \todo Derive these from the quality settings somehow. - // Linear and nearest should work atm. - m_signatureState.paintSampler = SAMPLER_TYPE_NEAREST; - m_signatureState.imageSampler = SAMPLER_TYPE_NEAREST; - - m_signatureState.hasMasking = isMasking() && (m_drawable->getMaskBuffer() != NULL); - - m_signatureState.hasImage = m_image ? true : false; - m_signatureState.unsafeImageInput = !m_image ? false : m_image->isUnsafe(); - m_signatureState.imageMode = m_imageMode; - - // Formats. Note that fields that are not filled in / used get set to a derived state in a - // separate function! - - if (m_signatureState.paintType == (RIuint32)VG_PAINT_TYPE_COLOR) - { - RI_ASSERT(m_paint); - if (m_paint->getSolidColor().a == 1.0) - m_signatureState.fillColorTransparent = false; - else - m_signatureState.fillColorTransparent = true; - } - - m_signatureState.dstDesc = m_drawable->getColorBuffer()->getDescriptor(); - - // \todo Why isn't the imagedescriptor set here? - if (m_signatureState.hasMasking) - { - m_signatureState.maskDesc = m_drawable->getMaskBuffer()->getDescriptor(); - } - -} - -/** - * \brief Remove redundancy from the pixel-pipeline state so that less - * pipelines are generated. - */ -static void determineDerivedState(PixelPipe::SignatureState& derivedState, const PixelPipe::SignatureState& originalState) -{ - derivedState = originalState; - - if (derivedState.isRenderToMask) - { - // Set a lot of defaults: - derivedState.blendMode = VG_BLEND_SRC; - derivedState.imageMode = VG_DRAW_IMAGE_NORMAL; - derivedState.paintType = VG_PAINT_TYPE_COLOR; - - derivedState.hasImage = false; - derivedState.hasMasking = false; - derivedState.hasColorTransform = false; - } - - if (derivedState.paintType == VG_PAINT_TYPE_COLOR) - { - derivedState.paintTilingMode = PixelPipe::TILING_MODE_PAD; - derivedState.paintSampler = PixelPipe::SAMPLER_TYPE_NEAREST; - // \todo Opaque solid colors can benefit from simpler coverage-blending - // becase SRC_OVER == SRC. This information has to be present in - // the derivedState (and not just uniform). - } - - if (!derivedState.hasImage) - { - derivedState.imageMode = VG_DRAW_IMAGE_NORMAL; - derivedState.imageSampler = PixelPipe::SAMPLER_TYPE_NEAREST; - derivedState.imageGradientType = PixelPipe::GRADIENT_TYPE_INTEGER; - derivedState.imageDesc = Color::Descriptor::getDummyDescriptor(); - } else if (derivedState.imageMode == VG_DRAW_IMAGE_NORMAL) - { - // If paint is not generated, use a common enum - derivedState.paintType = VG_PAINT_TYPE_COLOR; - } - - if (derivedState.paintType != VG_PAINT_TYPE_PATTERN) - { - derivedState.patternDesc = Color::Descriptor::getDummyDescriptor(); - } - - if (!derivedState.isRenderToMask) - derivedState.maskOperation = VG_CLEAR_MASK; - - if (!derivedState.hasMasking) - { - derivedState.maskDesc = Color::Descriptor::getDummyDescriptor(); - } -} - - -/** - * \brief Determine per-scanconversion constant state. - * \todo NOTE! This also prepares the derived state at the moment. - */ -void PixelPipe::prepareSpanUniforms(bool aa) -{ - prepareSignatureState(); - - if (m_signatureState.hasColorTransform) - m_spanUniforms.colorTransformValues = m_iColorTransformValues; - - RI_ASSERT(m_drawable->getColorBuffer()); - - const Image* dst; - - if (!m_signatureState.isRenderToMask) - dst = m_drawable->getColorBuffer()->getImage(); - else - dst = m_drawable->getMaskBuffer()->getImage(); - - m_spanUniforms.dstPtr = dst->getData(); - m_spanUniforms.dstStride = dst->getStride(); - - if (m_drawable->getMaskBuffer()) - { - m_spanUniforms.maskPtr = m_drawable->getMaskBuffer()->m_image->getData(); - m_spanUniforms.maskStride = m_drawable->getMaskBuffer()->m_image->getStride(); - } - else - { - m_spanUniforms.maskPtr = NULL; - m_spanUniforms.maskStride = 0; - } - - if (!m_renderToMask) - { - VGImageFormat prefPaintFormat = getPreferredLUTFormat(); - - switch (getPaintType()) - { - case VG_PAINT_TYPE_COLOR: - prepareSolidFill(); - break; - case VG_PAINT_TYPE_LINEAR_GRADIENT: - m_paint->generateLUT(*this, prefPaintFormat); - prepareLinearGradient(); - break; - case VG_PAINT_TYPE_RADIAL_GRADIENT: - m_paint->generateLUT(*this, prefPaintFormat); - prepareRadialGradient(); - break; - default: - RI_ASSERT(getPaintType() == VG_PAINT_TYPE_PATTERN); - preparePattern(); - break; - } - } - else - { - prepareCoverageFill(); - } - - prepareImage(aa); - - // Must be done last: - determineDerivedState(m_derivedState, m_signatureState); -} - - -/*-------------------------------------------------------------------*//*! -* \brief Computes the linear gradient function at (x,y). -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ -void PixelPipe::linearGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const -{ - RI_ASSERT(m_paint); - Vector2 u = m_paint->m_linearGradientPoint1 - m_paint->m_linearGradientPoint0; - RIfloat usq = dot(u,u); - if( usq <= 0.0f ) - { //points are equal, gradient is always 1.0f - g = 1.0f; - rho = 0.0f; - return; - } - RIfloat oou = 1.0f / usq; - - Vector2 p(x, y); - p = affineTransform(m_surfaceToPaintMatrix, p); - p -= m_paint->m_linearGradientPoint0; - RI_ASSERT(usq >= 0.0f); - g = dot(p, u) * oou; - RIfloat dgdx = oou * u.x * m_surfaceToPaintMatrix[0][0] + oou * u.y * m_surfaceToPaintMatrix[1][0]; - RIfloat dgdy = oou * u.x * m_surfaceToPaintMatrix[0][1] + oou * u.y * m_surfaceToPaintMatrix[1][1]; - rho = (RIfloat)sqrt(dgdx*dgdx + dgdy*dgdy); - RI_ASSERT(rho >= 0.0f); -} - -/*-------------------------------------------------------------------*//*! -* \brief Computes the radial gradient function at (x,y). -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::radialGradient(RIfloat &g, RIfloat &rho, RIfloat x, RIfloat y) const -{ - RI_ASSERT(m_paint); - if( m_paint->m_radialGradientRadius <= 0.0f ) - { - g = 1.0f; - rho = 0.0f; - return; - } - - RIfloat r = m_paint->m_radialGradientRadius; - Vector2 c = m_paint->m_radialGradientCenter; - Vector2 f = m_paint->m_radialGradientFocalPoint; - Vector2 gx(m_surfaceToPaintMatrix[0][0], m_surfaceToPaintMatrix[1][0]); - Vector2 gy(m_surfaceToPaintMatrix[0][1], m_surfaceToPaintMatrix[1][1]); - - Vector2 fp = f - c; - - //clamp the focal point inside the gradient circle - RIfloat fpLen = fp.length(); - if( fpLen > 0.999f * r ) - fp *= 0.999f * r / fpLen; - - RIfloat D = -1.0f / (dot(fp,fp) - r*r); - Vector2 p(x, y); - p = affineTransform(m_surfaceToPaintMatrix, p) - c; - Vector2 d = p - fp; - RIfloat s = (RIfloat)sqrt(r*r*dot(d,d) - RI_SQR(p.x*fp.y - p.y*fp.x)); - g = (dot(fp,d) + s) * D; - if(RI_ISNAN(g)) - g = 0.0f; - RIfloat dgdx = D*dot(fp,gx) + (r*r*dot(d,gx) - (gx.x*fp.y - gx.y*fp.x)*(p.x*fp.y - p.y*fp.x)) * (D / s); - RIfloat dgdy = D*dot(fp,gy) + (r*r*dot(d,gy) - (gy.x*fp.y - gy.y*fp.x)*(p.x*fp.y - p.y*fp.x)) * (D / s); - rho = (RIfloat)sqrt(dgdx*dgdx + dgdy*dgdy); - if(RI_ISNAN(rho)) - rho = 0.0f; - RI_ASSERT(rho >= 0.0f); -} - -/*-------------------------------------------------------------------*//*! -* \brief Maps a gradient function value to a color. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Color PixelPipe::colorRamp(RIfloat gradient, RIfloat rho) const -{ - RI_ASSERT(m_paint); - RI_ASSERT(rho >= 0.0f); - - Color c(0,0,0,0,m_paint->m_colorRampPremultiplied ? Color::sRGBA_PRE : Color::sRGBA); - Color avg; - - if(rho == 0.0f) - { //filter size is zero or gradient is degenerate - switch(m_paint->m_colorRampSpreadMode) - { - case VG_COLOR_RAMP_SPREAD_PAD: - gradient = RI_CLAMP(gradient, 0.0f, 1.0f); - break; - case VG_COLOR_RAMP_SPREAD_REFLECT: - { - RIfloat g = RI_MOD(gradient, 2.0f); - gradient = (g < 1.0f) ? g : 2.0f - g; - break; - } - default: - RI_ASSERT(m_paint->m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT); - gradient = gradient - (RIfloat)floor(gradient); - break; - } - RI_ASSERT(gradient >= 0.0f && gradient <= 1.0f); - - for(int i=0;im_colorRampStops.size()-1;i++) - { - if(gradient >= m_paint->m_colorRampStops[i].offset && gradient < m_paint->m_colorRampStops[i+1].offset) - { - RIfloat s = m_paint->m_colorRampStops[i].offset; - RIfloat e = m_paint->m_colorRampStops[i+1].offset; - RI_ASSERT(s < e); - RIfloat g = RI_CLAMP((gradient - s) / (e - s), 0.0f, 1.0f); //clamp needed due to numerical inaccuracies - - Color sc = readStopColor(m_paint->m_colorRampStops, i, m_paint->m_colorRampPremultiplied); - Color ec = readStopColor(m_paint->m_colorRampStops, i+1, m_paint->m_colorRampPremultiplied); - return (1.0f-g) * sc + g * ec; //return interpolated value - } - } - return readStopColor(m_paint->m_colorRampStops, m_paint->m_colorRampStops.size()-1, m_paint->m_colorRampPremultiplied); - } - - RIfloat gmin = gradient - rho*0.5f; //filter starting from the gradient point (if starts earlier, radial gradient center will be an average of the first and the last stop, which doesn't look good) - RIfloat gmax = gradient + rho*0.5f; - - switch(m_paint->m_colorRampSpreadMode) - { - case VG_COLOR_RAMP_SPREAD_PAD: - { - if(gmin < 0.0f) - c += (RI_MIN(gmax, 0.0f) - gmin) * readStopColor(m_paint->m_colorRampStops, 0, m_paint->m_colorRampPremultiplied); - if(gmax > 1.0f) - c += (gmax - RI_MAX(gmin, 1.0f)) * readStopColor(m_paint->m_colorRampStops, m_paint->m_colorRampStops.size()-1, m_paint->m_colorRampPremultiplied); - gmin = RI_CLAMP(gmin, 0.0f, 1.0f); - gmax = RI_CLAMP(gmax, 0.0f, 1.0f); - c += m_paint->integrateColorRamp(gmin, gmax); - c *= 1.0f/rho; - c.clamp(); //clamp needed due to numerical inaccuracies - return c; - } - - case VG_COLOR_RAMP_SPREAD_REFLECT: - { - avg = m_paint->integrateColorRamp(0.0f, 1.0f); - RIfloat gmini = (RIfloat)floor(gmin); - RIfloat gmaxi = (RIfloat)floor(gmax); - c = (gmaxi + 1.0f - gmini) * avg; //full ramps - - //subtract beginning - if(((int)gmini) & 1) - c -= m_paint->integrateColorRamp(RI_CLAMP(1.0f - (gmin - gmini), 0.0f, 1.0f), 1.0f); - else - c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(gmin - gmini, 0.0f, 1.0f)); - - //subtract end - if(((int)gmaxi) & 1) - c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(1.0f - (gmax - gmaxi), 0.0f, 1.0f)); - else - c -= m_paint->integrateColorRamp(RI_CLAMP(gmax - gmaxi, 0.0f, 1.0f), 1.0f); - break; - } - - default: - { - RI_ASSERT(m_paint->m_colorRampSpreadMode == VG_COLOR_RAMP_SPREAD_REPEAT); - avg = m_paint->integrateColorRamp(0.0f, 1.0f); - RIfloat gmini = (RIfloat)floor(gmin); - RIfloat gmaxi = (RIfloat)floor(gmax); - c = (gmaxi + 1.0f - gmini) * avg; //full ramps - c -= m_paint->integrateColorRamp(0.0f, RI_CLAMP(gmin - gmini, 0.0f, 1.0f)); //subtract beginning - c -= m_paint->integrateColorRamp(RI_CLAMP(gmax - gmaxi, 0.0f, 1.0f), 1.0f); //subtract end - break; - } - } - - //divide color by the length of the range - c *= 1.0f / rho; - c.clamp(); //clamp needed due to numerical inaccuracies - - //hide aliasing by fading to the average color - const RIfloat fadeStart = 0.5f; - const RIfloat fadeMultiplier = 2.0f; //the larger, the earlier fade to average is done - - if(rho < fadeStart) - return c; - - RIfloat ratio = RI_MIN((rho - fadeStart) * fadeMultiplier, 1.0f); - return ratio * avg + (1.0f - ratio) * c; -} - -/*-------------------------------------------------------------------*//*! -* \brief Computes blend. -* \param -* \return -* \note premultiplied blending formulas - //src - a = asrc - r = rsrc - //src over - a = asrc + adst * (1-asrc) - r = rsrc + rdst * (1-asrc) - //dst over - a = asrc * (1-adst) + adst - r = rsrc * (1-adst) + adst - //src in - a = asrc * adst - r = rsrc * adst - //dst in - a = adst * asrc - r = rdst * asrc - //multiply - a = asrc + adst * (1-asrc) - r = rsrc * (1-adst) + rdst * (1-asrc) + rsrc * rdst - //screen - a = asrc + adst * (1-asrc) - r = rsrc + rdst - rsrc * rdst - //darken - a = asrc + adst * (1-asrc) - r = MIN(rsrc + rdst * (1-asrc), rdst + rsrc * (1-adst)) - //lighten - a = asrc + adst * (1-asrc) - r = MAX(rsrc + rdst * (1-asrc), rdst + rsrc * (1-adst)) - //additive - a = MIN(asrc+adst,1) - r = rsrc + rdst -*//*-------------------------------------------------------------------*/ - - - -Color PixelPipe::blend(const Color& s, RIfloat ar, RIfloat ag, RIfloat ab, const Color& d, VGBlendMode blendMode) const -{ - //apply blending in the premultiplied format - Color r(0,0,0,0,d.getInternalFormat()); - RI_ASSERT(s.a >= 0.0f && s.a <= 1.0f); - RI_ASSERT(s.r >= 0.0f && s.r <= s.a && s.r <= ar); - RI_ASSERT(s.g >= 0.0f && s.g <= s.a && s.g <= ag); - RI_ASSERT(s.b >= 0.0f && s.b <= s.a && s.b <= ab); - RI_ASSERT(d.a >= 0.0f && d.a <= 1.0f); - RI_ASSERT(d.r >= 0.0f && d.r <= d.a); - RI_ASSERT(d.g >= 0.0f && d.g <= d.a); - RI_ASSERT(d.b >= 0.0f && d.b <= d.a); - switch(blendMode) - { - case VG_BLEND_SRC: - r = s; - break; - - case VG_BLEND_SRC_OVER: - r.r = s.r + d.r * (1.0f - ar); - r.g = s.g + d.g * (1.0f - ag); - r.b = s.b + d.b * (1.0f - ab); - r.a = s.a + d.a * (1.0f - s.a); - break; - - case VG_BLEND_DST_OVER: - r.r = s.r * (1.0f - d.a) + d.r; - r.g = s.g * (1.0f - d.a) + d.g; - r.b = s.b * (1.0f - d.a) + d.b; - r.a = s.a * (1.0f - d.a) + d.a; - break; - - case VG_BLEND_SRC_IN: - r.r = s.r * d.a; - r.g = s.g * d.a; - r.b = s.b * d.a; - r.a = s.a * d.a; - break; - - case VG_BLEND_DST_IN: - r.r = d.r * ar; - r.g = d.g * ag; - r.b = d.b * ab; - r.a = d.a * s.a; - break; - - case VG_BLEND_MULTIPLY: - r.r = s.r * (1.0f - d.a + d.r) + d.r * (1.0f - ar); - r.g = s.g * (1.0f - d.a + d.g) + d.g * (1.0f - ag); - r.b = s.b * (1.0f - d.a + d.b) + d.b * (1.0f - ab); - r.a = s.a + d.a * (1.0f - s.a); - break; - - case VG_BLEND_SCREEN: - r.r = s.r + d.r * (1.0f - s.r); - r.g = s.g + d.g * (1.0f - s.g); - r.b = s.b + d.b * (1.0f - s.b); - r.a = s.a + d.a * (1.0f - s.a); - break; - - case VG_BLEND_DARKEN: - r.r = RI_MIN(s.r + d.r * (1.0f - ar), d.r + s.r * (1.0f - d.a)); - r.g = RI_MIN(s.g + d.g * (1.0f - ag), d.g + s.g * (1.0f - d.a)); - r.b = RI_MIN(s.b + d.b * (1.0f - ab), d.b + s.b * (1.0f - d.a)); - r.a = s.a + d.a * (1.0f - s.a); - break; - - case VG_BLEND_LIGHTEN: - r.r = RI_MAX(s.r + d.r * (1.0f - ar), d.r + s.r * (1.0f - d.a)); - r.g = RI_MAX(s.g + d.g * (1.0f - ag), d.g + s.g * (1.0f - d.a)); - r.b = RI_MAX(s.b + d.b * (1.0f - ab), d.b + s.b * (1.0f - d.a)); - //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a) - //in practice there can be a very slight difference because - //of the max operation in the blending formula that may cause color to exceed alpha. - //Because of this, we compute the result both ways and return the maximum. - r.a = RI_MAX(s.a + d.a * (1.0f - s.a), d.a + s.a * (1.0f - d.a)); - break; - - default: - RI_ASSERT(blendMode == VG_BLEND_ADDITIVE); - r.r = RI_MIN(s.r + d.r, 1.0f); - r.g = RI_MIN(s.g + d.g, 1.0f); - r.b = RI_MIN(s.b + d.b, 1.0f); - r.a = RI_MIN(s.a + d.a, 1.0f); - break; - } - return r; -} - -/*-------------------------------------------------------------------*//*! -* \brief Applies color transform. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void PixelPipe::colorTransform(Color& c) const -{ - if(m_colorTransform) - { - c.unpremultiply(); - c.luminanceToRGB(); - c.r = c.r * m_colorTransformValues[0] + m_colorTransformValues[4]; - c.g = c.g * m_colorTransformValues[1] + m_colorTransformValues[5]; - c.b = c.b * m_colorTransformValues[2] + m_colorTransformValues[6]; - c.a = c.a * m_colorTransformValues[3] + m_colorTransformValues[7]; - c.clamp(); - c.premultiply(); - } -} - -void PixelPipe::fillSpans(PPVariants& variants, const Span* spans, int nSpans) const -{ -#if 1 - PPCompiler& compiler = PPCompiler::getCompiler(); - - PPCompiler::PixelPipeHandle handle = compiler.compilePixelPipeline(m_derivedState); - if (handle) - { - PixelPipeFunction func = compiler.getPixelPipePtr(handle); - RI_ASSERT(func); - func(m_spanUniforms, variants, spans, nSpans); - compiler.releasePixelPipeline(handle); - } else -#endif - { - executePixelPipeline(m_derivedState, m_spanUniforms, variants, spans, nSpans); - } -} - -//======================================================================= - -} //namespace OpenVGRI - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riPixelPipe.h --- a/hostsupport/hostopenvg/src/src/riPixelPipe.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,428 +0,0 @@ -#ifndef __RIPIXELPIPE_H -#define __RIPIXELPIPE_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Paint and PixelPipe classes. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef __RIMATH_H -#include "riMath.h" -#endif - -#ifndef __RIIMAGE_H -#include "riImage.h" -#endif - -//======================================================================= - -namespace OpenVGRI -{ - -struct Span; -class PPCompiler; -class PixelPipe; - -/*-------------------------------------------------------------------*//*! -* \brief Storage and operations for VGPaint. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class Paint -{ -public: - enum { GRADIENT_LUT_BITS = 8 }; - enum { GRADIENT_LUT_COUNT = 1 << GRADIENT_LUT_BITS }; - enum { GRADIENT_LUT_MASK = (1<= 0); return m_referenceCount; } - void setColor(const Color& color) {m_paintColor = color; m_paintColor.clamp(); m_paintColor.premultiply(); } - void setGradientStops(Array& inputStops, Array& stops); - void generateLUT(PixelPipe& pipe, VGImageFormat targetFormat); - const IntegerColor* getGradientLUT() const { return m_gradientLUT; } - void setLinearGradient(const Vector2& p0, const Vector2& p1); - void setRadialGradient(const Vector2& c, const Vector2& f, VGfloat r); - bool linearDegenerate() const; - bool radialDegenerate() const; - Color getSolidColor() const; - - Color integrateColorRamp(RIfloat gmin, RIfloat gmax) const; // \todo Private after modifications. - -public: - VGPaintType m_paintType; - Color m_paintColor; - Color m_inputPaintColor; - VGColorRampSpreadMode m_colorRampSpreadMode; - Array m_colorRampStops; - Array m_inputColorRampStops; - VGboolean m_colorRampPremultiplied; - Vector2 m_inputLinearGradientPoint0; - Vector2 m_inputLinearGradientPoint1; - Vector2 m_inputRadialGradientCenter; - Vector2 m_inputRadialGradientFocalPoint; - RIfloat m_inputRadialGradientRadius; - Vector2 m_linearGradientPoint0; - Vector2 m_linearGradientPoint1; - Vector2 m_radialGradientCenter; - Vector2 m_radialGradientFocalPoint; - RIfloat m_radialGradientRadius; - VGTilingMode m_patternTilingMode; - Image* m_pattern; -private: - Paint(const Paint&); //!< Not allowed. - const Paint& operator=(const Paint&); //!< Not allowed. - - int m_referenceCount; - IntegerColor m_gradientLUT[GRADIENT_LUT_COUNT]; - VGImageFormat m_lutFormat; - bool m_gradientStopsChanged; - bool m_gradientDegenerate; -}; - -/*-------------------------------------------------------------------*//*! -* \brief Encapsulates all information needed for painting a pixel. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -#define RGRAD_FLOATS -#if defined(RGRAD_FLOATS) -typedef RIfloat RGScalar; -#else -typedef double RGScalar; -#endif - -class PixelPipe -{ -public: - enum SamplerType - { - SAMPLER_TYPE_NEAREST = 0, - SAMPLER_TYPE_LINEAR = 1, - SAMPLER_TYPE_SIZE - }; - - enum TilingMode - { - TILING_MODE_PAD = 0, - TILING_MODE_REPEAT = 1, - TILING_MODE_REFLECT = 2, - TILING_MODE_FILL = 3, - TILING_MODE_SIZE - }; - - // Span per-pixel variants: - struct PPVariants - { - void* dst; - void* src; - void* maskPtr; - int coverage; - - RIuint32 dstX; - - RIint32 sx; - RIint32 sy; - - RGScalar rx; - RGScalar ry; - - // \todo Image sampling coordinates will be in fixed point if transform is affine, - // in floating point if not. - RGScalar ix; - RGScalar iy; - - RIint32 iImageX; - RIint32 iImageY; - RIfloat fImageX; - RIfloat fImageY; - RIfloat fImageW; - }; - - // Uniform state per-pixel - // \todo Organize into sub-structures? - struct PPUniforms - { - // \todo Do not store pointers to classes, only atoms! It should make the - // dynamic compilation a lot easier. - void* srcPtr; - RIint32 srcStride; - void* dstPtr; - RIint32 dstStride; - void* maskPtr; - int maskStride; - void* imagePtr; - int imageStride; - void* patternPtr; - int patternStride; - const IntegerColor* gradientLookup; - const RIint32* colorTransformValues; - - // Linear gradient - RIint32 dgdx; - RIint32 dgdy; - RIint32 lgc; - - // Radial gradient - RGScalar rsqrp; - RGScalar rfxp; - RGScalar rfyp; - RGScalar rx0; - RGScalar ry0; - RGScalar rdxdx; - RGScalar rdxdy; - RGScalar rdydx; - RGScalar rdydy; - - // Pattern. Note that pattern and image may be used at the same time. - RIint32 paint_width; - RIint32 paint_height; - RIint32 paint_x0; - RIint32 paint_y0; - RIint32 paint_dxdx; - RIint32 paint_dxdy; - RIint32 paint_dydx; - RIint32 paint_dydy; - - // Image - RIint32 image_iWidth; - RIint32 image_iHeight; - RIint32 image_ix0; - RIint32 image_iy0; - RIint32 image_idxdx; - RIint32 image_idxdy; - RIint32 image_idydx; - RIint32 image_idydy; - - - RIfloat image_fWidth; - RIfloat image_fHeight; - RIfloat image_fx0; - RIfloat image_fy0; - RIfloat image_fw0; - RIfloat image_fdxdx; - RIfloat image_fdxdy; - RIfloat image_fdydx; - RIfloat image_fdydy; - RIfloat image_fdwdx; - RIfloat image_fdwdy; - - IntegerColor tileFillColor; - IntegerColor solidColor; - RIuint32 packedSolidColor; - }; - - enum ImageGradientType { - GRADIENT_TYPE_INTEGER = 0, - GRADIENT_TYPE_FIXED = 1, - GRADIENT_TYPE_FLOAT = 2, - GRADIENT_TYPE_SIZE - }; - - // Signature state contains all the information necessary to compile - // a pixel-pipeline. Note that some of these are actually derived. - // \note REMEMBER TO UPDATE THE COMPILER. For now, there is now - // automatic mechanism to propagate changes to that component! - struct SignatureState - { - VGBlendMode blendMode; - VGImageMode imageMode; - VGPaintType paintType; - VGMaskOperation maskOperation; - TilingMode paintTilingMode; - SamplerType paintSampler; - SamplerType imageSampler; - - ImageGradientType imageGradientType; - - Color::Descriptor dstDesc; - Color::Descriptor maskDesc; - Color::Descriptor imageDesc; - Color::Descriptor patternDesc; - - bool hasMasking; - bool hasImage; - bool hasColorTransform; - bool isRenderToMask; - bool fillColorTransparent; - // When using external data for rendering an image: This is the only case - // where the data can be invalid in the pixel-pipe. - bool unsafeImageInput; - - }; - -public: - PixelPipe(); //throws bad_alloc - ~PixelPipe(); - - void pixelPipe(int x, int y, RIuint32 coverage) const; //rasterizer calls this function for each pixel - void fillSolidSpan(int startX, int y, int nPixels) const; - void setDrawable(Drawable* drawable); - void setBlendMode(VGBlendMode blendMode); - RI_INLINE VGBlendMode getBlendMode() const { return m_blendMode; } - void setRenderToMask(bool renderToMask) { m_renderToMask = renderToMask; } - void setMaskOperation(VGMaskOperation maskOperation) { m_maskOperation = maskOperation; } - void setMask(bool masking); - void setImage(Image* image, VGImageMode imageMode); //image = NULL disables drawImage functionality - void setSurfaceToPaintMatrix(const Matrix3x3& surfaceToPaintMatrix); - void setSurfaceToImageMatrix(const Matrix3x3& surfaceToImageMatrix); - void setImageQuality(VGImageQuality imageQuality); - void setTileFillColor(const Color& c); - void setPaint(Paint* paint); - void setColorTransform(bool enable, RIfloat values[8]); - bool hasColorTransform() const { return m_colorTransform; } - RI_INLINE const SignatureState& getSignatureState() const { return m_signatureState; } - - // Functions that determine parts of derived state. - void prepareSpanUniforms(bool aa); - - RI_INLINE VGPaintType getPaintType() const; - RI_INLINE bool isMasking() const; - void fillSpans(PPVariants& variants, const Span* spans, int nSpans) const; - - void colorTransform(Color& c) const; - void setColorTransformChanged(bool changed) { m_colorTransformChanged = changed; } // make paint friend and this private! - bool colorTransformChanged() const { return m_colorTransformChanged; } - RI_INLINE VGImageMode getImageMode() const { return m_imageMode; } - - RI_INLINE static bool isImageOnly(const SignatureState& state); - -private: - - const Image* getRenderTargetImage() const; - VGImageFormat getPreferredLUTFormat() const; - - void prepareSolidFill(); - void prepareCoverageFill(); - void prepareLinearGradient(); - void prepareRadialGradient(); - void preparePattern(); - void prepareImage(bool aa); - void prepareSignatureState(); - void prepareRenderToMask(); - void linearGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const; - void radialGradient(RIfloat& g, RIfloat& rho, RIfloat x, RIfloat y) const; - Color colorRamp(RIfloat gradient, RIfloat rho) const; - Color blend(const Color& s, RIfloat ar, RIfloat ag, RIfloat ab, const Color& d, VGBlendMode blendMode) const; - - PixelPipe(const PixelPipe&); //!< Not allowed. - const PixelPipe& operator=(const PixelPipe&); //!< Not allowed. - - Drawable* m_drawable; - bool m_masking; - Image* m_image; - // \todo LUT within the paint class broke constness of paint. - Paint* m_paint; - Paint m_defaultPaint; - VGBlendMode m_blendMode; - VGImageMode m_imageMode; - VGImageQuality m_imageQuality; - Color m_tileFillColor; - bool m_colorTransform; - RIfloat m_colorTransformValues[8]; - RIint32 m_iColorTransformValues[8]; - Matrix3x3 m_surfaceToPaintMatrix; - Matrix3x3 m_surfaceToImageMatrix; - Matrix3x3 m_paintToSurfaceMatrix; - VGMaskOperation m_maskOperation; - bool m_renderToMask; - bool m_colorTransformChanged; - -public: - - enum { COLOR_TRANSFORM_BITS = 8 }; - enum { COLOR_TRANSFORM_ONE = (1<m_paintType == VG_PAINT_TYPE_COLOR) - return VG_PAINT_TYPE_COLOR; - - if (m_paint->m_paintType == VG_PAINT_TYPE_PATTERN && !m_paint->m_pattern) - return VG_PAINT_TYPE_COLOR; - - if (m_paint->m_paintType == VG_PAINT_TYPE_LINEAR_GRADIENT && m_paint->linearDegenerate()) - return VG_PAINT_TYPE_COLOR; - - if (m_paint->m_paintType == VG_PAINT_TYPE_RADIAL_GRADIENT && m_paint->radialDegenerate()) - return VG_PAINT_TYPE_COLOR; - - return m_paint->m_paintType; -} - -RI_INLINE bool PixelPipe::isMasking() const -{ - return m_masking; -} - -RI_INLINE /*static*/ bool PixelPipe::isImageOnly(const SignatureState& state) -{ - if (state.hasImage) - return (state.imageMode == VG_DRAW_IMAGE_NORMAL) ? true : false; - else - return false; -} - -//======================================================================= - -} //namespace OpenVGRI - -//======================================================================= - -#endif /* __RIPIXELPIPE_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riRasterizer.cpp --- a/hostsupport/hostopenvg/src/src/riRasterizer.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1073 +0,0 @@ -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementation of polygon rasterizer. - * \note - *//*-------------------------------------------------------------------*/ - -#include "riRasterizer.h" - -// TEMP! -#ifndef __SFCOMPILER_H -# include "sfCompiler.h" -#endif - - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief Rasterizer constructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Rasterizer::Rasterizer() : - m_covBuffer(NULL), - m_covBufferSz(0), - m_edges(), - m_scissorEdges(), - m_scissor(false), - m_aa(true), - m_vpx(0), - m_vpy(0), - m_vpwidth(0), - m_vpheight(0), - m_fillRule(VG_EVEN_ODD), - m_pixelPipe(NULL), - m_nSpans(0) -{} - -/*-------------------------------------------------------------------*//*! -* \brief Rasterizer destructor. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -Rasterizer::~Rasterizer() -{ - if(m_covBuffer) - RI_DELETE_ARRAY(m_covBuffer); -} - -/*-------------------------------------------------------------------*//*! -* \brief Removes all appended edges. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -#define EDGE_TERMINATOR 0xFFFFFFFFu - -void Rasterizer::clear() -{ - //m_edges.clear(); - for (int i = 0; i < m_edges.size(); i++) - m_edges[i] = EDGE_TERMINATOR; - - m_edgePool.clear(); - - m_edgeMin.set(0x7fffffffu, 0x7fffffffu); - m_edgeMax.set(0x80000000, 0x80000000); -} - -/*-------------------------------------------------------------------*//*! -* \brief Appends an edge to the rasterizer. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Rasterizer::addBBox(const IVector2& v) -{ - if(v.x < m_edgeMin.x) m_edgeMin.x = v.x; - if(v.y < m_edgeMin.y) m_edgeMin.y = v.y; - if(v.x > m_edgeMax.x) m_edgeMax.x = v.x; - if(v.y > m_edgeMax.y) m_edgeMax.y = v.y; -} - -void Rasterizer::pushEdge(const Edge& edge) -{ - addBBox(edge.v0); - addBBox(edge.v1); - - // Only add processed edges. - - RI_ASSERT(edge.v0.y >= 0); - RI_ASSERT(edge.v0.y < edge.v1.y); //horizontal edges should have been dropped already - - ActiveEdge ae; - ae.direction = edge.direction; - - // \todo Adjust for non-AA cases - // \todo verySteep is temporary. Either clip to right edge also, or validate that a proper slope can be - // calculated here. - const int slope = RI_SAT_SHL((edge.v1.x - edge.v0.x), RASTERIZER_BITS - X_BITS) / (edge.v1.y - edge.v0.y); - //const bool verySteep = RI_INT_ABS(edge.v1.x - edge.v0.x) > (1 << (30-RASTERIZER_BITS)) ? true : false; - //const int slope = verySteep ? 1 << 30 : RI_SHL((edge.v1.x - edge.v0.x), RASTERIZER_BITS - X_BITS) / (edge.v1.y - edge.v0.y); - // slope: SI.(RASTERIZER_BITS - Y_BITS) - const int yF = edge.v0.y & Y_MASK; - // \todo See verySteep note for this hack also. (Clip to right edge?) - const int xRef = RI_SAT_SHL(edge.v0.x, RASTERIZER_BITS - X_BITS) - (yF * slope); - //const int xRef = edge.v0.x > (1<<(30-RASTERIZER_BITS)) ? 1<<30 : RI_SHL(edge.v0.x, RASTERIZER_BITS - X_BITS) - (yF * slope); - - RI_ASSERT(RI_INT_ABS(edge.v0.y <= 32767)); - RI_ASSERT(RI_INT_ABS(edge.v1.y <= 32767)); - - ae.yStart = (RIint16)edge.v0.y; - ae.yEnd = (RIint16)edge.v1.y; - ae.xRef = xRef; - ae.slope = slope; - // Scanline range. - ae.minx = xRef >> RASTERIZER_BITS; - ae.maxx = (xRef + slope * (1<> RASTERIZER_BITS; - - if (ae.minx > ae.maxx) - RI_ANY_SWAP(ActiveEdge::XCoord, ae.minx, ae.maxx); - - if (ae.maxx < 0) - ae.minx = ae.maxx = LEFT_DISCARD_SHORT; - - if (m_edges[ae.yStart>>Y_BITS] == EDGE_TERMINATOR) - ae.next = EDGE_TERMINATOR; - else - ae.next = m_edges[ae.yStart>>Y_BITS]; - - m_edgePool.push_back(ae); //throws bad_alloc - - RI_ASSERT(m_edgePool.size() > 0); - m_edges[ae.yStart>>Y_BITS] = m_edgePool.size()-1; -} - -/** - * \brief Clips an edge and if something remains, adds it to the list of edges. - * \todo Enhance precision: Currently this just uses doubles and gets away with - * it in most cases. - */ -void Rasterizer::clipAndAddEdge(Edge& edge) -{ - //if (m_edges.size() > 48) - //return; - // Check y-clips - // \todo Reduce amount of clips. - bool outLeft[2] = {(edge.v0.x < m_vpMinx), (edge.v1.x < m_vpMinx)}; - bool outRight[2] = {(edge.v0.x > m_vpMaxx), (edge.v1.x > m_vpMaxx)}; - bool outTop[2] = {(edge.v0.y < m_vpMiny), (edge.v1.y < m_vpMiny)}; - bool outBottom[2] = {(edge.v0.y > m_vpMaxy), (edge.v1.y > m_vpMaxy)}; - - if (!(outLeft[0] || outLeft[1] || outRight[0] || outRight[1] || outTop[0] || outTop[1] || outBottom[0] || outBottom[1])) - { - pushEdge(edge); - return; - } - - // \todo Make sure that checking out-of-right works with the scanconverter. - if ((outBottom[0] && outBottom[1]) || (outTop[0] && outTop[1])) - return; // Out of bounds - - // \todo Clip to right edge of screen. - // \todo Make slope-calculation and signs consistent. - // - if (outTop[0] || outBottom[1]) - { - // Clip to top/bottom. - double slope = (double)(edge.v1.x - edge.v0.x)/(edge.v1.y - edge.v0.y); - - if (outTop[0]) - { - RI_ASSERT(-(RIint64)edge.v0.y >= 0); - RIint32 dx = RI_ROUND_TO_INT(-slope * edge.v0.y); - edge.v0.y = 0; - edge.v0.x += dx; - } - - if (outBottom[1]) - { - RIint32 dy = edge.v1.y - m_vpMaxy; - RI_ASSERT(dy >= 0); - RIint32 dx = -RI_ROUND_TO_INT(slope * dy); - edge.v1.y = m_vpMaxy; - edge.v1.x += dx; - } - - } - - if (edge.v0.y >= edge.v1.y) - return; - - // \todo Recheck left/right. - outLeft[0] = (edge.v0.x < m_vpMinx); outLeft[1] = (edge.v1.x < m_vpMinx); - outRight[1] = (edge.v0.x > m_vpMaxx); outRight[1] = (edge.v1.x > m_vpMaxx); - - if (outLeft[0] && outLeft[1]) - { - edge.v0.x = m_vpMinx; - edge.v1.x = m_vpMinx; - pushEdge(edge); - return; - } - if (outRight[0] && outRight[1]) - { - edge.v0.x = m_vpMaxx; - edge.v1.x = m_vpMaxx; - pushEdge(edge); - return; - } - - // From outside -> screen - if (outLeft[0] || outRight[1]) - { - // infinite slope? - double slope = (double)((RIint64)edge.v1.y - edge.v0.y)/((RIint64)edge.v1.x - edge.v0.x); - - if (outLeft[0]) - { - RIint32 dx = edge.v0.x; - //RI_ASSERT(dx >= 0); - // Note the sign. - RIint32 dy = RI_ROUND_TO_INT(-slope * dx); - - Edge vpart = edge; - vpart.v1.y = edge.v0.y + dy; - //vpart.v1.x = edge.v0.x; // = 0? - // \note This should be flagged instead of setting the smallest possible - // value because of extremely gentle slopes may cause bugs: - vpart.v1.x = vpart.v0.x = -0x100000; - - if (vpart.v1.y > vpart.v0.y) - pushEdge(vpart); - - edge.v0.y += dy; - edge.v0.x = 0; - } - } - // From screen -> outside - if (outLeft[1] || outRight[0]) - { - // infinite slope? - double slope = (double)((RIint64)edge.v1.y - edge.v0.y)/((RIint64)edge.v1.x - edge.v0.x); - - if (outLeft[1]) - { - RIint32 dx = edge.v0.x; - RI_ASSERT(dx >= 0); - RIint32 dy = RI_ROUND_TO_INT(-slope * dx); - - Edge vpart = edge; - vpart.v0.y = edge.v0.y + dy; - vpart.v1.x = vpart.v0.x = LEFT_DISCARD; - - if (vpart.v1.y > vpart.v0.y) - pushEdge(vpart); - - edge.v1.y = edge.v0.y + dy; - edge.v1.x = 0; - } - } - - if (edge.v0.y >= edge.v1.y) - return; - - // Finally, add the edge: - pushEdge(edge); -} - -void Rasterizer::addEdge(const Vector2& v0, const Vector2& v1) -{ - if( m_edges.size() >= RI_MAX_EDGES ) - throw std::bad_alloc(); //throw an out of memory error if there are too many edges - - Edge e; - - { - IVector2 i0(RI_ROUND_TO_INT(v0.x * (1<= 0 && vpheight >= 0); - RI_ASSERT(vpx + vpwidth >= vpx && vpy + vpheight >= vpy); - RI_ASSERT(fillRule == VG_EVEN_ODD || fillRule == VG_NON_ZERO); - RI_ASSERT(pixelPipe); - - clear(); - - m_vpx = vpx; - m_vpy = vpy; - m_vpwidth = vpwidth; - m_vpheight = vpheight; - - if (m_vpheight > m_edges.size()) - { - int os = m_edges.size(); - m_edges.resize(m_vpheight); - for (int i = os; i < m_edges.size(); i++) - m_edges[i] = EDGE_TERMINATOR; - } - - m_vpMinx = RI_SHL(vpx, X_BITS); - m_vpMiny = RI_SHL(vpy, Y_BITS); - m_vpMaxx = RI_SHL(vpx + vpwidth, X_BITS); - m_vpMaxy = RI_SHL(vpy + vpheight, Y_BITS); - - m_fillRule = fillRule; - - RIuint32 fillRuleMask = fillRule == VG_NON_ZERO ? 0xffffffffu : 1; - m_fillRuleMask = fillRuleMask; - - m_pixelPipe = pixelPipe; - m_covMinx = vpx+vpwidth; - m_covMiny = vpy+vpheight; - m_covMaxx = vpx; - m_covMaxy = vpy; -} - -/*-------------------------------------------------------------------*//*! -* \brief Sets scissor rectangles. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -void Rasterizer::setScissor(const Array& scissors) -{ - try - { - m_scissorEdges.clear(); - for(int i=0;i 0 && scissors[i].height > 0) - { - ScissorEdge e; - e.miny = scissors[i].y; - e.maxy = RI_INT_ADDSATURATE(scissors[i].y, scissors[i].height); - - e.x = scissors[i].x; - e.direction = 1; - m_scissorEdges.push_back(e); //throws bad_alloc - e.x = RI_INT_ADDSATURATE(scissors[i].x, scissors[i].width); - e.direction = -1; - m_scissorEdges.push_back(e); //throws bad_alloc - } - } - } - catch(std::bad_alloc) - { - m_scissorEdges.clear(); - throw; - } -} - -void Rasterizer::setScissoring(bool enabled) -{ - m_scissor = enabled; -} - -static RI_INLINE void small_memcpy32(void* dst, const void* src, size_t n) -{ - RIuint32 *d = (RIuint32*)dst; - const RIuint32 *s = (const RIuint32*)src; - while(n) - { - *d++ = *s++; - n-=4; - } -} - -// \todo Move this to some debug file or remove. -#if defined(USE_SSE2) && !defined(_WIN32) -RI_INLINE static void print128(__m128i ll) -{ -#if defined(RI_DEBUG) - unsigned long long v[2]; - _mm_storeu_pd((double*)v, (__m128d)ll); - RI_PRINTF("0x%016llx %016llx\n", v[0], v[1]); -#else - (void)ll; -#endif -} -#endif - -#if defined(USE_SSE2) -RI_INLINE static __m128i mm_mul4x32(const __m128i a, const __m128i b) { - __m128i res; -#if (_MSC_VER > 1400 ) - // \todo Simpler way to do this on intel? - __m128i m0 = _mm_mul_epu32(a, _mm_shuffle_epi32(b, _MM_SHUFFLE(1, 1, 0, 0))); - __m128i m1 = _mm_mul_epu32(a, _mm_shuffle_epi32(b, _MM_SHUFFLE(3, 3, 2, 2))); - - res = _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(m0), _mm_castsi128_ps(m1), _MM_SHUFFLE(2, 0, 2, 0))); -#else - __asm { - movdqa xmm1, a; - movdqa xmm2, b; - pshufd xmm3, xmm2, 80; - movdqa xmm0, xmm1; - - pshufd xmm2, xmm2, 250; - pmuludq xmm0, xmm3; - pmuludq xmm1, xmm2; - - shufps xmm0, xmm1, 136; - movdqa res, xmm0; - } -#endif - return res; -} -#endif - -#if defined(USE_SSE2) -RI_INLINE static void mm_get_xmasks(const __m128i& coords, const __m128i& sampleCoords, __m128i& slWindMask, __m128i& pxWindMask) -{ - const __m128i z = _mm_setzero_si128(); - const __m128i xMask = _mm_cmpeq_epi16(_mm_srai_epi16(coords, Rasterizer::RASTERIZER_BITS), z); - const __m128i sCmp = _mm_or_si128(_mm_cmpgt_epi16(sampleCoords, coords), _mm_cmpeq_epi16(sampleCoords, coords)); - //const __m128i sCmp = _mm_cmplt_epi16(coords, sampleCoords); - slWindMask = xMask; - pxWindMask = _mm_and_si128(xMask, sCmp); -} -#endif - -RI_INLINE static void getVerticalSubpixels(int iY, int yStart, int yEnd, int& py0, int& py1) -{ - const int cy = iY << Rasterizer::Y_BITS; - py0 = cy > yStart ? 0 : yStart & Rasterizer::Y_MASK; - py1 = (RI_INT_MIN(yEnd, cy + (1<= 4) - yMask = _mm_set1_epi8(-1); - else - yMask = _mm_set1_epi8(0); - - const __m128i dir = _mm_set1_epi16(currAe.direction); - - scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(yMask, dir)); - //scanline.sseWinding = _mm_add_epi32(scanline.sseWinding, dir); - -#else - RI_ASSERT(false); // Not implemented yet. -#endif -} - -RI_INLINE void calculateAEWinding(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& pixel, Rasterizer::Windings& scanline, int intY, int pixelX) -{ -#define QUEEN_COORD(Y) ((Y<<(Rasterizer::RASTERIZER_BITS - Rasterizer::SAMPLE_BITS)) + (1<<(Rasterizer::RASTERIZER_BITS-Rasterizer::SAMPLE_BITS-1))) - -#if !defined(USE_SSE2) - static const int queenCoords[(1<> Rasterizer::RASTERIZER_BITS; - const int cy = intY << Rasterizer::Y_BITS; - - const int py0 = cy > currAe.yStart ? 0 : currAe.yStart & Rasterizer::Y_MASK; - const int py1 = (RI_INT_MIN(currAe.yEnd, cy + (1<= py0); - - for (int s = py0; s <= py1; s++) - { - const int sampleX = pixelX + queenCoords[s]; - - //compute winding number by evaluating the edge functions of edges to the left of the sampling point - if(((edgeX >> Rasterizer::RASTERIZER_BITS) == ix)) - { - if (sampleX >= edgeX) - { - pixel.winding[s] += currAe.direction; - } - scanline.winding[s] += currAe.direction; - } - - edgeX += currAe.slope; - } -#else - - __m128i qCoords = _mm_set_epi16( - QUEEN_COORD(4), QUEEN_COORD(6), QUEEN_COORD(1), QUEEN_COORD(5), - QUEEN_COORD(2), QUEEN_COORD(0), QUEEN_COORD(7), QUEEN_COORD(3)); - - RI_ASSERT(Rasterizer::RASTERIZER_BITS <= 14); - - // TEROP: Optimize conditions. - int py0, py1; - getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1); - - const int cy = intY << Rasterizer::Y_BITS; - - const __m128i csteps0 = _mm_set_epi32(3,2,1,0); - const __m128i csteps1 = _mm_set_epi32(7,6,5,4); - - const __m128i ssePy0 = _mm_set1_epi32(py0-1); - const __m128i ssePy1 = _mm_set1_epi32(py1+1); - - const __m128i yMask0 = _mm_and_si128(_mm_cmpgt_epi32(csteps0, ssePy0), _mm_cmplt_epi32(csteps0, ssePy1)); - const __m128i yMask1 = _mm_and_si128(_mm_cmpgt_epi32(csteps1, ssePy0), _mm_cmplt_epi32(csteps1, ssePy1)); - - const int edgeX = currAe.xRef + (cy - (currAe.yStart & ~Rasterizer::Y_MASK)) * currAe.slope; - const __m128i xStart = _mm_set1_epi32(edgeX - pixelX); - - const __m128i xs0 = _mm_set1_epi32(currAe.slope); - - __m128i xAdd0 = mm_mul4x32(xs0, csteps0); - __m128i xAdd1 = mm_mul4x32(xs0, csteps1); - __m128i coords0 = _mm_add_epi32(xStart, xAdd0); - __m128i coords1 = _mm_add_epi32(xStart, xAdd1); - __m128i coords = _mm_packs_epi32(coords0, coords1); - - __m128i dir = _mm_set1_epi16(currAe.direction); - __m128i yMask = _mm_packs_epi32(yMask0, yMask1); - __m128i mDir = _mm_and_si128(dir, yMask); - - __m128i sampleCoords = qCoords; - - __m128i sw, pw; - mm_get_xmasks(coords, sampleCoords, sw, pw); - - pixel.sseWinding = _mm_add_epi16(pixel.sseWinding, _mm_and_si128(pw, mDir)); - scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(sw, mDir)); -#endif - -#undef QUEEN_COORD - -} - -/** - * \brief Calculate winding using one sample only. - * \note This uses most of the same code as the AA-case even though it is not - * necessary (one sample would be enough). - */ -RI_INLINE void calculateAEWindingNoAA(const Rasterizer::ActiveEdge& currAe, Rasterizer::Windings& pixel, Rasterizer::Windings& scanline, int intY, int pixelX) -{ -#if defined(USE_SSE2) - -#define QUEEN_COORD(Y) ((Y<<(Rasterizer::RASTERIZER_BITS - Rasterizer::SAMPLE_BITS)) + (1<<(Rasterizer::RASTERIZER_BITS-Rasterizer::SAMPLE_BITS-1))) - const int half = 1<<(Rasterizer::RASTERIZER_BITS-1); - - __m128i sampleCoords = _mm_set1_epi16(half); - - RI_ASSERT(Rasterizer::RASTERIZER_BITS <= 14); - - const int cy = intY << Rasterizer::Y_BITS; - - int py0, py1; - getVerticalSubpixels(intY, currAe.yStart, currAe.yEnd, py0, py1); - - __m128i yMask; - - if (py0 <= 4 && py1 >= 4) - yMask = _mm_set1_epi8(-1); - else - yMask = _mm_set1_epi8(0); - - const __m128i csteps0 = _mm_set_epi32(4,4,4,4); - const __m128i csteps1 = _mm_set_epi32(4,4,4,4); - - const int edgeX = currAe.xRef + (cy - (currAe.yStart & ~Rasterizer::Y_MASK)) * currAe.slope; - const __m128i xStart = _mm_set1_epi32(edgeX - pixelX); - - const __m128i xs0 = _mm_set1_epi32(currAe.slope); - - __m128i xAdd0 = mm_mul4x32(xs0, csteps0); - __m128i xAdd1 = mm_mul4x32(xs0, csteps1); - __m128i coords0 = _mm_add_epi32(xStart, xAdd0); - __m128i coords1 = _mm_add_epi32(xStart, xAdd1); - __m128i coords = _mm_packs_epi32(coords0, coords1); - - __m128i dir = _mm_set1_epi16(currAe.direction); - __m128i mDir = _mm_and_si128(dir, yMask); - //__m128i mDir = dir; - - __m128i sw, pw; - mm_get_xmasks(coords, sampleCoords, sw, pw); - - pixel.sseWinding = _mm_add_epi16(pixel.sseWinding, _mm_and_si128(pw, mDir)); - scanline.sseWinding = _mm_add_epi16(scanline.sseWinding, _mm_and_si128(sw, mDir)); - -#undef QUEEN_COORD - -#else - RI_ASSERT(false); // Not implemented. -#endif -} - -#if defined(USE_SSE2) -RI_INLINE static int mm_winding_to_coverage(const Rasterizer::Windings& pixel, int fillRuleMask) -{ - // This version uses SSE2 counters. - __m128i mask = _mm_set1_epi16(fillRuleMask); - __m128i t = _mm_and_si128(mask, pixel.sseWinding); - __m128i z = _mm_setzero_si128(); - __m128i isz = _mm_cmpeq_epi16(t, z); - __m128i ones = _mm_set1_epi16(1); - __m128i res = _mm_add_epi16(ones, isz); - __m128i add0 = _mm_add_epi16(res, _mm_shuffle_epi32(res, _MM_SHUFFLE(2, 3, 2, 3))); - __m128i add1 = _mm_add_epi16(add0, _mm_shuffle_epi32(add0, _MM_SHUFFLE(1, 1, 1, 1))); - __m128i add2 = _mm_add_epi16(add1, _mm_shufflelo_epi16(add1, _MM_SHUFFLE(1, 1, 1, 1))); - - int nSamples = _mm_cvtsi128_si32(add2) & 0xff; - return nSamples; -} -#endif - -#define RI_DEBUG -#if defined(RI_DEBUG) -void maybeDumpEdges(Array &edgePool) -{ - return; - // \note This gives an idea about the edges at the rasterization stage. - // Input edges must be output at a different stage. - RI_PRINTF("lines = []\n"); - for (int i = 0 ; i < edgePool.size(); i++) - { - const int slope = edgePool[i].slope; - int x0, x1, y0, y1; - y0 = edgePool[i].yStart; - y1 = edgePool[i].yEnd; - x0 = edgePool[i].xRef + (slope * (y0 & Rasterizer::Y_MASK)); - x1 = (edgePool[i].xRef + (slope * (y1 - (y0 & ~Rasterizer::Y_MASK))))>>(Rasterizer::RASTERIZER_BITS-Rasterizer::X_BITS); - RI_PRINTF("lines += [[%d, %d], [%d, %d]]\n",x0>>(Rasterizer::RASTERIZER_BITS-Rasterizer::X_BITS),y0,x1,y1); - } -} -#endif - -/*-------------------------------------------------------------------*//*! -* \brief Calls PixelPipe::pixelPipe for each pixel with coverage greater -* than zero. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ -void Rasterizer::fill() -{ - if(m_scissor && !m_scissorEdges.size()) - return; //scissoring is on, but there are no scissor rectangles => nothing is visible - - int firstAe = 0; - - //proceed scanline by scanline - //keep track of edges that can intersect the pixel filters of the current scanline (Active Edge Table) - //until all pixels of the scanline have been processed - // for all sampling points of the current pixel - // determine the winding number using edge functions - // add filter weight to coverage - // divide coverage by the number of samples - // determine a run of pixels with constant coverage - // call fill callback for each pixel of the run - - const int fillRuleMask = m_fillRuleMask; - - int bbminx = (m_edgeMin.x >> X_BITS); - int bbminy = (m_edgeMin.y >> Y_BITS); - int bbmaxx = (m_edgeMax.x >> X_BITS)+1; - int bbmaxy = (m_edgeMax.y >> Y_BITS)+1; - int sx = RI_INT_MAX(m_vpx, bbminx); - int ex = RI_INT_MIN(m_vpx+m_vpwidth, bbmaxx); - int sy = RI_INT_MAX(m_vpy, bbminy); - int ey = RI_INT_MIN(m_vpy+m_vpheight, bbmaxy); - if(sx < m_covMinx) m_covMinx = sx; - if(sy < m_covMiny) m_covMiny = sy; - if(ex > m_covMaxx) m_covMaxx = ex; - if(ey > m_covMaxy) m_covMaxy = ey; - -#if 0 - // Dump edges: - static bool dump = true; - if (dump) - { - RI_PRINTF("lines = []\n"); - for (int ie = 0; dump && ie < m_edgePool.size(); ie++) - { - RI_PRINTF("lines += [[%d, %d], [%d, %d]]\n",m_edgePool[ie].v0.x, m_edgePool[ie].v0.y, m_edgePool[ie].v1.x, m_edgePool[ie].v1.y); - } - dump = false; - } - -#endif - int debugMagic = 0; - - m_aet.clear(); - -#if defined(RI_DEBUG) - maybeDumpEdges(m_edgePool); -#endif - - //fill the screen - for(int j = sy; j < ey; j++) - { - Windings scanlineWinding; - const int cminy = j << Y_BITS; - - if (m_scissor) - { - // Gather scissor edges intersecting this scanline - // \todo Don't clear, remove unused instead! - m_scissorAet.clear(); - - for(int e = 0; e < m_scissorEdges.size(); e++) - { - const ScissorEdge& se = m_scissorEdges[e]; - - if(j >= se.miny && j < se.maxy) - m_scissorAet.push_back(m_scissorEdges[e]); //throws bad_alloc - } - - //sort scissor AET by edge x - if (m_scissor) - m_scissorAet.sort(); - } - - // Drop unused edges, update remaining. - // \todo Combine with full sweep. Use a sort-friendly edge-discard. - for (int iae = firstAe; iae < m_aet.size(); iae++) - { - ActiveEdge& ae = m_aet[iae]; - - if (cminy >= ae.yEnd) - { - m_aet[iae] = m_aet[firstAe]; - firstAe++; - continue; - } - - /* Update existing coordinates */ - // \todo AND instead of shift. See other places also. - const int y0 = (ae.yStart & ~Y_MASK); - const int x = ae.xRef + ((j << Y_BITS) - y0) * ae.slope; - ae.minx = x >> RASTERIZER_BITS; - ae.maxx = (x + ae.slope * (1<> RASTERIZER_BITS; - - if (ae.minx > ae.maxx) - RI_ANY_SWAP(ActiveEdge::XCoord, ae.minx, ae.maxx); - - // If the edge is not visible, "mark" it as immediately applicable - // \todo Verify that this is the correct procedure. - - if (ae.maxx < 0) - ae.minx = ae.maxx = LEFT_DISCARD_SHORT; - } - - /* Add new edges */ - - RIuint32 aeIndex = m_edges[j]; - while (aeIndex != EDGE_TERMINATOR) - { - const ActiveEdge& ae = m_edgePool[aeIndex]; - m_aet.push_back(ae); // \todo Just copy pointers? - aeIndex = ae.next; - } - - if (firstAe >= m_aet.size()) - { - RI_ASSERT(firstAe == m_aet.size()); - continue; //no edges on the whole scanline, skip it - } - - //sort AET by edge minx - m_aet.sort(firstAe, m_aet.size() - 1); - - // \todo Optimize adding and updating the edges? - if (m_scissor && !m_scissorAet.size()) - continue; // Scissoring is on, but there are no scissor rectangles on this scanline. - - //fill the scanline - int scissorWinding = m_scissor ? 0 : 1; //if scissoring is off, winding is always 1 - int scissorIndex = 0; - int aes = firstAe; - int aen = firstAe; - - RI_ASSERT(sx >= 0); - -#if 1 - if (m_aa) - { - while ((aen < m_aet.size()) && (m_aet[aen].maxx < 0)) - { - applyLeftEdge(m_aet[aen], scanlineWinding, j); - aen++; - } - } - else - { - while ((aen < m_aet.size()) && (m_aet[aen].maxx < 0)) - { - applyLeftEdgeNoAA(m_aet[aen], scanlineWinding, j); - aen++; - } - } - -#if defined(RI_DEBUG) - for (int a = aen; a < m_aet.size(); a++) - { - RI_ASSERT(m_aet[a].maxx >= 0); - } -#endif -#endif - - // \todo Combine this with the first check or reorganize the "clipping". - if (aen >= m_aet.size()) - continue; // No edges within viewport. Can happen atm. when all edges are "left". - - for(int i = sx; i < ex;) - { - //find edges that intersect or are to the left of the pixel antialiasing filter - while(aes < m_aet.size() && (i + 1) >= m_aet[aes].minx) - aes++; - //edges [0,aes[ may have an effect on winding, and need to be evaluated while sampling - - // RIint8 winding[SF_SAMPLES]; - Windings pixelWinding; - - pixelWinding = scanlineWinding; - - if (m_aa) - { - for(int e = aen; e < aes; e++) - { - const ActiveEdge& currAe = m_aet[e]; - calculateAEWinding(currAe, pixelWinding, scanlineWinding, j, i << RASTERIZER_BITS); - } - } - else - { - for(int e = aen; e < aes; e++) - { - const ActiveEdge& currAe = m_aet[e]; - calculateAEWindingNoAA(currAe, pixelWinding, scanlineWinding, j, i << RASTERIZER_BITS); - } - } - - //compute coverage - int coverageSamples = 0; -#if !defined(USE_SSE2) - - for (int s = 0; s < SF_SAMPLES; s++) - { - if(pixelWinding.winding[s]) - { - coverageSamples++; - } - } -#else - coverageSamples = mm_winding_to_coverage(pixelWinding, fillRuleMask); - _mm_empty(); -#endif - - //constant coverage optimization: - //scan AET from left to right and skip all the edges that are completely to the left of the pixel filter. - //since AET is sorted by minx, the edge we stop at is the leftmost of the edges we haven't passed yet. - //if that edge is to the right of this pixel, coverage is constant between this pixel and the start of the edge. - while(aen < m_aet.size() && m_aet[aen].maxx < i) - aen++; - - int endSpan = m_vpx + m_vpwidth; // endSpan is the first pixel NOT part of the span - - if(aen < m_aet.size()) - { - endSpan = RI_INT_MAX(i+1, RI_INT_MIN(endSpan, m_aet[aen].minx)); - } - - //fill a run of pixels with constant coverage - if(coverageSamples) - { - - if (!m_scissor) - { - int fillStartX = i; /* Inclusive */ - pushSpan(fillStartX, j, (endSpan - fillStartX), coverageSamples); - } - else // (scissor) - { - int fillStartX = i; - //update scissor winding number - - /* \todo Sort the scissor edges and skip unnecessary checks when scissors are used */ - while (scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x <= fillStartX) - { - scissorWinding += m_scissorAet[scissorIndex++].direction; - } - - while (!scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x < endSpan) - { - fillStartX = m_scissorAet[scissorIndex].x; - scissorWinding += m_scissorAet[scissorIndex++].direction; - RI_ASSERT(fillStartX >= i); - } - - RI_ASSERT(scissorWinding >= 0); - - int endScissorSpan = endSpan; - - while (scissorWinding && fillStartX < endSpan && (scissorIndex < m_scissorAet.size())) - { - - // Determine the end of renderable area: - while (scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x <= endSpan) - { - endScissorSpan = m_scissorAet[scissorIndex].x; - scissorWinding += m_scissorAet[scissorIndex++].direction; - } - - RI_ASSERT(fillStartX >= i); - RI_ASSERT(endScissorSpan <= endSpan); - - pushSpan(fillStartX, j, (endScissorSpan - fillStartX), coverageSamples); - fillStartX = endScissorSpan; - endScissorSpan = endSpan; - - // Skip until within drawable area - while (!scissorWinding && scissorIndex < m_scissorAet.size() && m_scissorAet[scissorIndex].x < endSpan) - { - fillStartX = m_scissorAet[scissorIndex].x; - scissorWinding += m_scissorAet[scissorIndex++].direction; - } - - } - } - } - i = endSpan; - } - } - commitSpans(); -#if defined(USE_SSE2) - _mm_empty(); -#endif - clear(); -} - -RI_INLINE void Rasterizer::commitSpans() -{ - if (!m_nSpans) - return; - - m_pixelPipe->fillSpans(m_ppVariants, m_spanCache, m_nSpans); - m_nSpans = 0; - -} - -RI_INLINE void Rasterizer::pushSpan(int x, int y, int len, int coverage) -{ - //printf("x: %d, y: %d, len: %d, coverage: %d\n", x, y, len, coverage); - // \todo Check what causes this with scissors - if (len <= 0) return; - //RI_ASSERT(len > 0); - - Span& span = m_spanCache[m_nSpans]; - - span.x0 = x; - span.y = y; - span.len = (RIuint16)len; - span.coverage = coverage; - - m_nSpans++; - - if (m_nSpans == N_CACHED_SPANS) - { - commitSpans(); - } -} - -//======================================================================= - -} //namespace OpenVGRI diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riRasterizer.h --- a/hostsupport/hostopenvg/src/src/riRasterizer.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,279 +0,0 @@ -#ifndef __RIRASTERIZER_H -#define __RIRASTERIZER_H - -/*------------------------------------------------------------------------ - * - * OpenVG 1.1 Reference Implementation - * ----------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Rasterizer class. - * \note - *//*-------------------------------------------------------------------*/ - -#ifndef __RIMATH_H -#include "riMath.h" -#endif - -#ifndef __RIARRAY_H -#include "riArray.h" -#endif - -#ifndef __RIPIXELPIPE_H -#include "riPixelPipe.h" -#endif - -// TESTING ONLY!! -#include "sfDynamicPixelPipe.h" - -#if defined(RI_DEBUG) -# include -#endif -// \todo SSE2 probably has everything necessary and matches the minimum platform requirements. -// SSE4 is probably too new. SSE3? -// \note This will cause the code to not compile on MSVC... -#define USE_SSE2 - -#if defined(USE_SSE2) -// \todo only the last include is needed: QT creator does not find types if others not included. -# include -# include -# include -#endif - -//======================================================================= - -namespace OpenVGRI -{ - -/*-------------------------------------------------------------------*//*! -* \brief Scalar and vector data types used by the rasterizer. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -typedef RIfloat RScalar; //change this if you want to have different precision for rasterizer scalars and RIfloat - -struct RVector2 -{ - RI_INLINE RVector2() { } - RI_INLINE RVector2(const Vector2& v) { x = v.x; y = v.y; } - RI_INLINE RVector2(RIfloat vx, RIfloat vy) { x = vx; y = vy; } - RI_INLINE void set(RIfloat vx, RIfloat vy) { x = vx; y = vy; } - RScalar x; - RScalar y; -}; - -struct IVector2 -{ - RI_INLINE IVector2() {} - RI_INLINE IVector2(const IVector2& v) { x = v.x; y = v.y; } - RI_INLINE IVector2(const Vector2& v) { x = (int)v.x; y = (int) v.y; } - RI_INLINE IVector2(int vx, int vy) { x = vx; y = vy; } - RI_INLINE void set(int vx, int vy) { x = vx; y = vy; } - int x; - int y; -}; - -struct Span -{ - RIuint16 x0; - RIuint16 y; - RIuint16 len; - RIuint8 coverage; - RIuint8 pad; // align to 8 bytes. \temp Use qualifiers instead? -}; - -/*-------------------------------------------------------------------*//*! -* \brief Converts a set of edges to coverage values for each pixel and -* calls PixelPipe::pixelPipe for painting a pixel. -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -class Rasterizer -{ -public: - Rasterizer(); //throws bad_alloc - ~Rasterizer(); - - void setup(int vpx, int vpy, int vpwidth, int vpheight, VGFillRule fillRule, const PixelPipe* pixelPipe); - void setScissor(const Array& scissors); //throws bad_alloc - void setScissoring(bool enabled); - - void clear(); - void addEdge(const Vector2& v0, const Vector2& v1); //throws bad_alloc - - RI_INLINE void setAntiAliasing(bool enable) { m_aa = enable; } - void fill(); //throws bad_alloc - - void getBBox(int& sx, int& sy, int& ex, int& ey) const { sx = m_covMinx; sy = m_covMiny; ex = m_covMaxx; ey = m_covMaxy; } - -public: - enum { SAMPLE_BITS = 3 }; - enum { Y_BITS = SAMPLE_BITS }; - enum { MAX_COVERAGE = 1< 64 bits == 2 32-bit uints - union - { - RIint8 winding[SF_SAMPLES]; - RIuint32 wd[SF_SAMPLES/4]; - unsigned long long wq; - }; -#else - Windings() { sseWinding = _mm_setzero_si128(); } - __m128i sseWinding; -#endif - }; - -private: - void pushEdge(const Edge& edge); - void clipAndAddEdge(Edge& edge); - void addBBox(const IVector2& v); - RI_INLINE void pushSpan(int x, int y, int len, int coverage); - RI_INLINE void commitSpans(); - - //RI_INLINE void calculateAEWinding(const ActiveEdge& currAe, Windings& pixel, Windings& scanline, int intY, int pixelX); - - Array m_edgePool; - Array m_edges; - Array m_scissorEdges; - Array m_aet; - Array m_scissorAet; - bool m_scissor; - - bool m_aa; - - IVector2 m_edgeMin; - IVector2 m_edgeMax; - int m_covMinx; - int m_covMiny; - int m_covMaxx; - int m_covMaxy; - int m_vpx; - int m_vpy; - int m_vpwidth; - int m_vpheight; - int m_vpMinx; - int m_vpMiny; - int m_vpMaxx; - int m_vpMaxy; - VGFillRule m_fillRule; - RIuint32 m_fillRuleMask; - - const PixelPipe* m_pixelPipe; - PixelPipe::PPVariants m_ppVariants; - - enum { N_CACHED_SPANS = 64 }; - Span m_spanCache[N_CACHED_SPANS]; - int m_nSpans; - -}; - -//======================================================================= - -} //namespace OpenVGRI - -//======================================================================= - -#endif /* __RIRASTERIZER_H */ diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riUtils.cpp --- a/hostsupport/hostopenvg/src/src/riUtils.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,240 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __RIUTILS_H_ -# include "riUtils.h" -#endif - -#include - -namespace OpenVGRI -{ - -/** - * \brief Sets mem areas to byte(s) in c. - * \param dst Destination pointer. - * \param c Data to set into dst. - * \param nElements Amount of elements to set. - * \param nBytesPerElement Amount of bytes for each element. - * \note This is moslty an image-settings support function. It is assumed that several - * bytes / elements can be set at once, especially in 3-byte case. - */ -void riMemSet32(void* dst, RIuint32 c, size_t nElements, size_t nBytesPerElement) -{ - // \todo This function should be called from a function that handles npot element sizes. - // \todo Investigate the status of (open) std::fill implementations. Some of that code - // did not _seem_ to bundle sets or use SSE, etc. - // \todo Use SSE instructions on Intel? - - RI_ASSERT(dst); - RI_ASSERT(nElements); - - switch(nBytesPerElement) - { - case 4: - { - RIuint32* ptr = (RIuint32*)dst; - do { - *ptr++ = c; - } while(--nElements); - break; - } - case 3: - { - // \todo Endianness. - RIuint8* ptr = (RIuint8*)dst; - RIuint8 b[3]; - b[0] = c & 0xff; - b[1] = (c >> 8)&0xff; - b[2] = (c >> 16)&0xff; - do { - *ptr++ = b[0]; - *ptr++ = b[1]; - *ptr++ = b[2]; - } while(--nElements); - break; - } - case 2: - { - size_t dws = nElements / 2; - if (dws) - { - RIuint32* ptr32 = (RIuint32*)dst; - dst = (void*)(((RIuint8*)dst + dws * 4)); - RIuint32 dw = c | (c<<16); - do { - *ptr32++ = dw; - } while(--dws); - nElements &= 0x01; - } - if (nElements) - { - RIuint16 *ptr16 = (RIuint16*)dst; - const RIuint16 w = (RIuint16)c; - do { - *ptr16++ = w; - } while(--nElements); - } - break; - } - default: - { - RI_ASSERT(nBytesPerElement == 1); - memset(dst, c, nElements); - break; - } - } - -} - -/** - * \brief Insert bits into an array of 32-bit integers. - * \param hashSize Size of array in bytes. - * \param bits Actual bits to insert. - * \param bitSize Amount of bits to insert (max 32). - * \param bitPtr Pointer to first bit to insert [0 .. (hashSize*8)-1] - */ -int riInsertBits32(RIuint32* hash, size_t hashSize, RIuint32 bits, RIuint32 bitSize, int bitPtr) -{ - RI_ASSERT(bitSize > 0 && bitSize <= 32); - RI_ASSERT(bits < (1u<> 5; - int ib = bitPtr - (idw << 5); - - if ((ib + bitSize) > 32) - { - int rb = ((ib + bitSize) - 32) + 1; - RI_ASSERT(rb > 0); - hash[idw] |= (bits << ib); - hash[idw] |= (bits >> rb); - } - else - { - int new_ib = (ib + bitSize) & 0x1f; - RI_ASSERT((ib + bitSize == 32) ? new_ib == 0 : true); - hash[idw] |= (bits << ib); - } - return bitPtr + bitSize; -} - -/** - * \brief Convert an image format to (internal) index. - */ -int riVGImageFormatToIndex(VGImageFormat format) -{ - switch(format) - { - /* RGB{A,X} channel ordering */ - case VG_sRGBX_8888: - return 0; - case VG_sRGBA_8888: - return 1; - case VG_sRGBA_8888_PRE: - return 2; - case VG_sRGB_565: - return 3; - case VG_sRGBA_5551: - return 4; - case VG_sRGBA_4444: - return 5; - case VG_sL_8: - return 6; - case VG_lRGBX_8888: - return 7; - case VG_lRGBA_8888: - return 8; - case VG_lRGBA_8888_PRE: - return 9; - case VG_lL_8: - return 10; - case VG_A_8: - return 11; - case VG_BW_1: - return 12; - case VG_A_1: - return 13; - case VG_A_4: - return 14; - - /* {A,X}RGB channel ordering */ - case VG_sXRGB_8888: - return 15; - case VG_sARGB_8888: - return 16; - case VG_sARGB_8888_PRE: - return 17; - case VG_sARGB_1555: - return 18; - case VG_sARGB_4444: - return 19; - case VG_lXRGB_8888: - return 20; - case VG_lARGB_8888: - return 21; - case VG_lARGB_8888_PRE: - return 22; - - /* BGR{A,X} channel ordering */ - case VG_sBGRX_8888: - return 23; - case VG_sBGRA_8888: - return 24; - case VG_sBGRA_8888_PRE: - return 25; - case VG_sBGR_565: - return 26; - case VG_sBGRA_5551: - return 27; - case VG_sBGRA_4444: - return 28; - case VG_lBGRX_8888: - return 29; - case VG_lBGRA_8888: - return 30; - case VG_lBGRA_8888_PRE: - return 31; - - /* {A,X}BGR channel ordering */ - case VG_sXBGR_8888: - return 32; - case VG_sABGR_8888: - return 33; - case VG_sABGR_8888_PRE: - return 34; - case VG_sABGR_1555: - return 35; - case VG_sABGR_4444: - return 36; - case VG_lXBGR_8888: - return 37; - case VG_lABGR_8888: - return 38; - default: - RI_ASSERT(format == VG_lABGR_8888_PRE); - return 39; - } -} - -} - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riUtils.h --- a/hostsupport/hostopenvg/src/src/riUtils.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,63 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __RIUTILS_H_ -#define __RIUTILS_H_ - -#ifndef __RIDEFS_H -# include "riDefs.h" -#endif - -#include "VG/openvg.h" -#include - -// This file contains "utility" functions that did not "fit" into existing RI files. -// Once more functionality is accumulated, the corresponding functions/classes should be -// moved to proper files asap. For example, the memcopy functions could go into file -// "riMemory.xxx". - -namespace OpenVGRI -{ - - void riMemSet32(void* dst, RIuint32 c, size_t nElements, size_t nBytesPerElement); -RI_INLINE void ri_memcpy(void* dst, const void* src, size_t n); - int riInsertBits32(RIuint32* hash, size_t hashSize, RIuint32 bits, RIuint32 bitSize, int bitPtr); - int riVGImageFormatToIndex(VGImageFormat format); - -RI_INLINE void ri_memcpy(void* dst, const void* src, size_t n) -{ -#if !defined(RI_DEBUG) - memcpy(dst, src, n); -#else - RIuint8 *p = (RIuint8*)dst; - RIuint8 *q = (RIuint8*)src; - for (size_t i = 0; i < n; i++, p++, q++) - { - *p = *q; - } -#endif -} - -} // namespace OpenVG - -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/riVGU.cpp --- a/hostsupport/hostopenvg/src/src/riVGU.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,476 +0,0 @@ -/*------------------------------------------------------------------------ - * - * VGU library for OpenVG 1.1 Reference Implementation - * --------------------------------------------------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Implementation of the VGU utility library for OpenVG - *//*-------------------------------------------------------------------*/ - -#include "vgu.h" -#include "openvg.h" -#include "riMath.h" - -using namespace OpenVGRI; - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -static void append(VGPath path, int numSegments, const VGubyte* segments, int numCoordinates, const VGfloat* coordinates) -{ - RI_ASSERT(numCoordinates <= 26); - - VGPathDatatype datatype = (VGPathDatatype)vgGetParameteri(path, VG_PATH_DATATYPE); - VGfloat scale = vgGetParameterf(path, VG_PATH_SCALE); - VGfloat bias = vgGetParameterf(path, VG_PATH_BIAS); - - switch(datatype) - { - case VG_PATH_DATATYPE_S_8: - { - RIint8 data[26]; - for(int i=0;i= 0.0f) - { - segments[0] = VG_SCCWARC_TO | VG_ABSOLUTE; - for(VGfloat a = startAngle + RI_PI;a < endAngle; a += RI_PI) - { - if ((a + RI_PI) == a) - return VGU_ILLEGAL_ARGUMENT_ERROR; - - data[3] = x + w * (VGfloat)cos(a); - data[4] = y + h * (VGfloat)sin(a); - append(path, 1, segments, 5, data); - } - } - else - { - segments[0] = VG_SCWARC_TO | VG_ABSOLUTE; - for(VGfloat a = startAngle - RI_PI;a > endAngle; a -= RI_PI) - { - if ((a - RI_PI) == a) - return VGU_ILLEGAL_ARGUMENT_ERROR; - - data[3] = x + w * (VGfloat)cos(a); - data[4] = y + h * (VGfloat)sin(a); - append(path, 1, segments, 5, data); - } - } - data[3] = x + w * (VGfloat)cos(endAngle); - data[4] = y + h * (VGfloat)sin(endAngle); - append(path, 1, segments, 5, data); - - if(arcType == VGU_ARC_CHORD) - { - segments[0] = VG_CLOSE_PATH; - append(path, 1, segments, 0, data); - } - else if(arcType == VGU_ARC_PIE) - { - segments[0] = VG_LINE_TO | VG_ABSOLUTE; - data[0] = x; - data[1] = y; - append(path, 1, segments, 2, data); - segments[0] = VG_CLOSE_PATH; - append(path, 1, segments, 0, data); - } - - error = vgGetError(); - if(error == VG_BAD_HANDLE_ERROR) - return VGU_BAD_HANDLE_ERROR; - else if(error == VG_PATH_CAPABILITY_ERROR) - return VGU_PATH_CAPABILITY_ERROR; - return VGU_NO_ERROR; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGUErrorCode RI_APIENTRY vguComputeWarpQuadToSquare(VGfloat sx0, VGfloat sy0, VGfloat sx1, VGfloat sy1, VGfloat sx2, VGfloat sy2, VGfloat sx3, VGfloat sy3, VGfloat * matrix) -{ - if(!matrix || ((RIuintptr)matrix) & 3) - return VGU_ILLEGAL_ARGUMENT_ERROR; - - VGfloat mat[9]; - VGUErrorCode ret = vguComputeWarpSquareToQuad(sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3, mat); - if(ret == VGU_BAD_WARP_ERROR) - return VGU_BAD_WARP_ERROR; - Matrix3x3 m(mat[0], mat[3], mat[6], - mat[1], mat[4], mat[7], - mat[2], mat[5], mat[8]); - bool nonsingular = m.invert(); - if(!nonsingular) - return VGU_BAD_WARP_ERROR; - matrix[0] = m[0][0]; - matrix[1] = m[1][0]; - matrix[2] = m[2][0]; - matrix[3] = m[0][1]; - matrix[4] = m[1][1]; - matrix[5] = m[2][1]; - matrix[6] = m[0][2]; - matrix[7] = m[1][2]; - matrix[8] = m[2][2]; - return VGU_NO_ERROR; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGUErrorCode RI_APIENTRY vguComputeWarpSquareToQuad(VGfloat dx0, VGfloat dy0, VGfloat dx1, VGfloat dy1, VGfloat dx2, VGfloat dy2, VGfloat dx3, VGfloat dy3, VGfloat * matrix) -{ - if(!matrix || ((RIuintptr)matrix) & 3) - return VGU_ILLEGAL_ARGUMENT_ERROR; - - //from Heckbert:Fundamentals of Texture Mapping and Image Warping - //Note that his mapping of vertices is different from OpenVG's - //(0,0) => (dx0,dy0) - //(1,0) => (dx1,dy1) - //(0,1) => (dx2,dy2) - //(1,1) => (dx3,dy3) - - VGfloat diffx1 = dx1 - dx3; - VGfloat diffy1 = dy1 - dy3; - VGfloat diffx2 = dx2 - dx3; - VGfloat diffy2 = dy2 - dy3; - - VGfloat det = diffx1*diffy2 - diffx2*diffy1; - if(det == 0.0f) - return VGU_BAD_WARP_ERROR; - - VGfloat sumx = dx0 - dx1 + dx3 - dx2; - VGfloat sumy = dy0 - dy1 + dy3 - dy2; - - if(sumx == 0.0f && sumy == 0.0f) - { //affine mapping - matrix[0] = dx1 - dx0; - matrix[1] = dy1 - dy0; - matrix[2] = 0.0f; - matrix[3] = dx3 - dx1; - matrix[4] = dy3 - dy1; - matrix[5] = 0.0f; - matrix[6] = dx0; - matrix[7] = dy0; - matrix[8] = 1.0f; - return VGU_NO_ERROR; - } - - VGfloat oodet = 1.0f / det; - VGfloat g = (sumx*diffy2 - diffx2*sumy) * oodet; - VGfloat h = (diffx1*sumy - sumx*diffy1) * oodet; - - matrix[0] = dx1-dx0+g*dx1; - matrix[1] = dy1-dy0+g*dy1; - matrix[2] = g; - matrix[3] = dx2-dx0+h*dx2; - matrix[4] = dy2-dy0+h*dy2; - matrix[5] = h; - matrix[6] = dx0; - matrix[7] = dy0; - matrix[8] = 1.0f; - return VGU_NO_ERROR; -} - -/*-------------------------------------------------------------------*//*! -* \brief -* \param -* \return -* \note -*//*-------------------------------------------------------------------*/ - -VGUErrorCode RI_APIENTRY vguComputeWarpQuadToQuad(VGfloat dx0, VGfloat dy0, VGfloat dx1, VGfloat dy1, VGfloat dx2, VGfloat dy2, VGfloat dx3, VGfloat dy3, VGfloat sx0, VGfloat sy0, VGfloat sx1, VGfloat sy1, VGfloat sx2, VGfloat sy2, VGfloat sx3, VGfloat sy3, VGfloat * matrix) -{ - if(!matrix || ((RIuintptr)matrix) & 3) - return VGU_ILLEGAL_ARGUMENT_ERROR; - - VGfloat qtos[9]; - VGUErrorCode ret1 = vguComputeWarpQuadToSquare(sx0, sy0, sx1, sy1, sx2, sy2, sx3, sy3, qtos); - if(ret1 == VGU_BAD_WARP_ERROR) - return VGU_BAD_WARP_ERROR; - - VGfloat stoq[9]; - VGUErrorCode ret2 = vguComputeWarpSquareToQuad(dx0, dy0, dx1, dy1, dx2, dy2, dx3, dy3, stoq); - if(ret2 == VGU_BAD_WARP_ERROR) - return VGU_BAD_WARP_ERROR; - - Matrix3x3 m1(qtos[0], qtos[3], qtos[6], - qtos[1], qtos[4], qtos[7], - qtos[2], qtos[5], qtos[8]); - Matrix3x3 m2(stoq[0], stoq[3], stoq[6], - stoq[1], stoq[4], stoq[7], - stoq[2], stoq[5], stoq[8]); - Matrix3x3 r = m2 * m1; - - matrix[0] = r[0][0]; - matrix[1] = r[1][0]; - matrix[2] = r[2][0]; - matrix[3] = r[0][1]; - matrix[4] = r[1][1]; - matrix[5] = r[2][1]; - matrix[6] = r[0][2]; - matrix[7] = r[1][2]; - matrix[8] = r[2][2]; - return VGU_NO_ERROR; -} diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfAlphaRcp.h --- a/hostsupport/hostopenvg/src/src/sfAlphaRcp.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,66 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef _SFALPHARCP_H_ -#define _SFALPHARCP_H_ - -#include "riDefs.h" - -namespace OpenVGRI { -enum { ALPHA_RCP_BITS = 8}; -static const RIuint16 sc_alphaRcp[256] = { - 0xff00, 0xff00, 0x7f80, 0x5500, 0x3fc0, 0x3300, 0x2a80, 0x246e, - 0x1fe0, 0x1c55, 0x1980, 0x172f, 0x1540, 0x139e, 0x1237, 0x1100, - 0xff0, 0xf00, 0xe2b, 0xd6c, 0xcc0, 0xc25, 0xb97, 0xb16, - 0xaa0, 0xa33, 0x9cf, 0x972, 0x91b, 0x8cb, 0x880, 0x83a, - 0x7f8, 0x7ba, 0x780, 0x749, 0x715, 0x6e4, 0x6b6, 0x68a, - 0x660, 0x638, 0x612, 0x5ee, 0x5cc, 0x5ab, 0x58b, 0x56d, - 0x550, 0x534, 0x51a, 0x500, 0x4e7, 0x4d0, 0x4b9, 0x4a3, - 0x48e, 0x479, 0x466, 0x452, 0x440, 0x42e, 0x41d, 0x40c, - 0x3fc, 0x3ec, 0x3dd, 0x3ce, 0x3c0, 0x3b2, 0x3a5, 0x397, - 0x38b, 0x37e, 0x372, 0x366, 0x35b, 0x350, 0x345, 0x33a, - 0x330, 0x326, 0x31c, 0x313, 0x309, 0x300, 0x2f7, 0x2ee, - 0x2e6, 0x2dd, 0x2d5, 0x2cd, 0x2c6, 0x2be, 0x2b6, 0x2af, - 0x2a8, 0x2a1, 0x29a, 0x293, 0x28d, 0x286, 0x280, 0x27a, - 0x274, 0x26e, 0x268, 0x262, 0x25c, 0x257, 0x251, 0x24c, - 0x247, 0x242, 0x23d, 0x238, 0x233, 0x22e, 0x229, 0x225, - 0x220, 0x21c, 0x217, 0x213, 0x20e, 0x20a, 0x206, 0x202, - 0x1fe, 0x1fa, 0x1f6, 0x1f2, 0x1ef, 0x1eb, 0x1e7, 0x1e4, - 0x1e0, 0x1dc, 0x1d9, 0x1d6, 0x1d2, 0x1cf, 0x1cc, 0x1c9, - 0x1c5, 0x1c2, 0x1bf, 0x1bc, 0x1b9, 0x1b6, 0x1b3, 0x1b0, - 0x1ad, 0x1ab, 0x1a8, 0x1a5, 0x1a2, 0x1a0, 0x19d, 0x19b, - 0x198, 0x195, 0x193, 0x190, 0x18e, 0x18c, 0x189, 0x187, - 0x185, 0x182, 0x180, 0x17e, 0x17c, 0x179, 0x177, 0x175, - 0x173, 0x171, 0x16f, 0x16d, 0x16b, 0x169, 0x167, 0x165, - 0x163, 0x161, 0x15f, 0x15d, 0x15b, 0x159, 0x158, 0x156, - 0x154, 0x152, 0x150, 0x14f, 0x14d, 0x14b, 0x14a, 0x148, - 0x146, 0x145, 0x143, 0x142, 0x140, 0x13e, 0x13d, 0x13b, - 0x13a, 0x138, 0x137, 0x135, 0x134, 0x132, 0x131, 0x130, - 0x12e, 0x12d, 0x12b, 0x12a, 0x129, 0x127, 0x126, 0x125, - 0x123, 0x122, 0x121, 0x120, 0x11e, 0x11d, 0x11c, 0x11b, - 0x119, 0x118, 0x117, 0x116, 0x115, 0x113, 0x112, 0x111, - 0x110, 0x10f, 0x10e, 0x10d, 0x10c, 0x10a, 0x109, 0x108, - 0x107, 0x106, 0x105, 0x104, 0x103, 0x102, 0x101, 0x100, -}; -} -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfBlitter.cpp --- a/hostsupport/hostopenvg/src/src/sfBlitter.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,132 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#include "sfBlitter.h" - -#include "sfCompiler.h" - -namespace OpenVGRI { - -DynamicBlitter::DynamicBlitter() : - m_maskOperation(VG_SET_MASK), - m_isMaskOperation(false), - m_fillColor(), - m_isFill(false), - - m_signatureState(), - m_uniforms() -{ -} - -DynamicBlitter::~DynamicBlitter() -{ -} - -/*static*/ void DynamicBlitter::calculateHash(BlitterHash& hash, const BlitSignatureState& state) -{ - const RIuint32 descBits = 10; - const RIuint32 maskOperationBits = 3; - const RIuint32 boolBits = 1; - - RIuint32 srcFormat = (RIuint32)(state.srcDesc.toIndex()); - RIuint32 dstFormat = (RIuint32)(state.dstDesc.toIndex()); - RIuint32 maskOperation = ((RIuint32)(state.maskOperation - VG_CLEAR_MASK)); - RIuint32 incompatibleStride = ((RIuint32)state.incompatibleStrides); - RIuint32 isMaskOperation = ((RIuint32)state.isMaskOperation); - RIuint32 unsafeInput = (RIuint32)state.unsafeInput; - - int b = 0; - - b = riInsertBits32(hash.value, sizeof(hash.value), srcFormat, descBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), dstFormat, descBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), maskOperation, maskOperationBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), incompatibleStride, boolBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), isMaskOperation, boolBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), unsafeInput, boolBits, b); -} - -/** - * \brief Blit a region. The input coordinates and dimensions must be validated outside - * the blitter currently. - * \note The user must also apply the storage offset to the image(s). - */ -void DynamicBlitter::prepareBlit(Image* dst, const Image* src, int sx, int sy, int dx, int dy, int w, int h) -{ - //const Image *srcImage = src->getImage(); - //Image* dstImage = dst->m_image; - - // \todo Move these to derivation of the state? - m_signatureState.srcDesc = src->getDescriptor(); - m_signatureState.dstDesc = dst->getDescriptor(); - m_signatureState.isMaskOperation = m_isMaskOperation; - m_signatureState.maskOperation = m_isMaskOperation ? m_maskOperation : VG_CLEAR_MASK; - m_signatureState.incompatibleStrides = false; - m_signatureState.unsafeInput = false; - - m_uniforms.src = src->getData(); - m_uniforms.dst = dst->getData(); - m_uniforms.srcX = sx; - m_uniforms.srcY = sy; - m_uniforms.dstX = dx; - m_uniforms.dstY = dy; - m_uniforms.width = w; - m_uniforms.height = h; - m_uniforms.srcStride = src->getStride(); - m_uniforms.dstStride = dst->getStride(); - - if (m_signatureState.srcDesc.isZeroConversion(m_signatureState.dstDesc)) - { - const int fullCopyStride = Image::descriptorToStride(m_signatureState.srcDesc, m_uniforms.width); - - if ((m_uniforms.dstStride != m_uniforms.srcStride) || (fullCopyStride != m_uniforms.srcStride)) - m_signatureState.incompatibleStrides = true; - } - - if (src->isUnsafe()) - m_signatureState.unsafeInput = true; - -} - -void DynamicBlitter::blit() -{ -#if 1 - bool compiledBlitter = false; - { - PPCompiler& compiler = PPCompiler::getCompiler(); - PPCompiler::BlitterHandle blitterHandle = compiler.compileBlitter(getSignatureState()); - if (blitterHandle) - { - compiledBlitter = true; - BlitterFunction func = compiler.getBlitterPtr(blitterHandle); - func(getUniforms()); - compiler.releaseBlitter(blitterHandle); - } - } - - if (!compiledBlitter) -#endif - { - executeBlitter(getSignatureState(), getUniforms()); - } -} - -} diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfBlitter.h --- a/hostsupport/hostopenvg/src/src/sfBlitter.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,104 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __SFBLITTER_H -#define __SFBLITTER_H - -#ifndef __RIDEFS_H -# include "riDefs.h" -#endif - -#ifndef __RIIMAGE_H -# include "riImage.h" -#endif - -#include "VG/openvg.h" - -namespace OpenVGRI { - -class PPCompiler; - -struct BlitterHash { - BlitterHash() {value[0] = 0; } - bool operator==(const BlitterHash& rhs) const { return value[0] == rhs.value[0]; } - RIuint32 value[1]; -}; - -// \todo Rename to just "Blitter" and move out of the same compilation unit. -class DynamicBlitter { -public: - struct BlitSignatureState { - VGMaskOperation maskOperation; - - bool incompatibleStrides; - bool isMaskOperation; - bool unsafeInput; - - // Derived: - Color::Descriptor srcDesc; - Color::Descriptor dstDesc; - }; - - struct BlitUniforms { - void* dst; - const void* src; - RIuint32 srcX; - RIuint32 srcY; - RIuint32 dstX; - RIuint32 dstY; - RIuint32 width; - RIuint32 height; - RIint32 srcStride; - RIint32 dstStride; - }; - -public: - DynamicBlitter(); - ~DynamicBlitter(); - - static void calculateHash(BlitterHash& hash, const BlitSignatureState& state); - - void setMaskOperation(VGMaskOperation maskOperation) { m_maskOperation = maskOperation; } - void enableMaskOperation(bool isMaskOperation) { m_isMaskOperation = isMaskOperation; } - void setFillColor(const Color& fillColor) { m_fillColor = fillColor; } - void enableFill(bool isFill) { m_isFill = isFill; } - - void prepareBlit(Image* dst, const Image* src, int sx, int sy, int dx, int dy, int w, int h); - void blit(); - - const BlitSignatureState& getSignatureState() { return m_signatureState; } - const BlitUniforms& getUniforms() { return m_uniforms; } - -private: - - VGMaskOperation m_maskOperation; - bool m_isMaskOperation; - Color m_fillColor; - bool m_isFill; - - BlitSignatureState m_signatureState; - BlitUniforms m_uniforms; -}; -} - -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfCompiler.cpp --- a/hostsupport/hostopenvg/src/src/sfCompiler.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,512 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __SFCOMPILER_H -# include "sfCompiler.h" -#endif - -#ifndef __RIPIXELPIPE_H -# include "riPixelPipe.h" -#endif - -#include -#include -#include - -#include "llvm/LLVMContext.h" -#include "llvm/Module.h" -#include "llvm/Bitcode/ReaderWriter.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Type.h" -#include "llvm/Value.h" -#include "llvm/Constant.h" -#include "llvm/Constants.h" -#include "llvm/Argument.h" -#include "llvm/Transforms/Utils/Cloning.h" - -#include "llvm/Pass.h" -#include "llvm/PassManager.h" -#include "llvm/Support/StandardPasses.h" -#include "llvm/Transforms/Utils/BasicInliner.h" - -#include "llvm/ExecutionEngine/JIT.h" -#include "llvm/ExecutionEngine/ExecutionEngine.h" -#include "llvm/Target/TargetSelect.h" -#include "llvm/Support/ManagedStatic.h" - -// This file is found as an output of compilation (in the binary directory). -// Rationale for this is that the output is somewhat platform dependent. -#include "binaryPixelPipe.h" -#include "binaryBlitter.h" - -namespace OpenVGRI { - -static bool single_compiler = true; - -PPCompiler* PPCompiler::s_compiler = NULL; - -PPCompiler::PPCompiler() : - m_executionEngine(NULL), - m_ppCache(NUM_CACHED_PIXELPIPES), - m_blitterCache(NUM_CACHED_BLITTERS), - m_llvmContext() -{ - // \todo Make this class into a singleton? - RI_ASSERT(single_compiler); - - if (single_compiler) - single_compiler = false; - - ::llvm::InitializeNativeTarget(); - init(); -} - -PPCompiler::~PPCompiler() -{ - if (m_executionEngine) - delete m_executionEngine; -} - -PPCompiler::PPCompilerContext::PPCompilerContext() : - module(NULL), - llvmFunction(NULL) -{ -} - -PPCompiler::PPCompilerContext::~PPCompilerContext() -{ - // All the other objects should be owned by the executionengine, and - // that is owned by the PPCompiler, so do nothing here. - -} - -bool PPCompiler::initPPContext( - PPCompilerContext& context, - const unsigned char* data, - size_t dataSize, - const char* functionName) -{ - try { - std::string err; - - const char *byteCodeStart = (const char*)data; - const char *byteCodeEnd = (const char*)(data + dataSize); - - ::llvm::MemoryBuffer* memBuffer = ::llvm::MemoryBuffer::getMemBufferCopy(byteCodeStart, byteCodeEnd); - - llvmCheckPtrError((void*)memBuffer, err); - - // Make sure the module is fully read: - //::llvm::Module* ppModule = moduleProvider->materializeModule(&err); - ::llvm::Module* ppModule = ::llvm::getLazyBitcodeModule(memBuffer, getLLVMContext(), &err); - ppModule->MaterializeAll(); - - llvmCheckPtrError(ppModule, err); - context.module = ppModule; - //ppModule->dump(); - - if (!m_executionEngine) - { - m_executionEngine = ::llvm::ExecutionEngine::createJIT(ppModule, &err, NULL, ::llvm::CodeGenOpt::Aggressive); - llvmCheckPtrError(m_executionEngine, err); - } - else - m_executionEngine->addModule(ppModule); - - //m_executionEngine->runStaticConstructorsDestructors(false); - - ::llvm::Function* originalFunc = findFunctionWithString(ppModule, functionName); - - llvmCheckPtrError((const void*)originalFunc, err); - context.llvmFunction = originalFunc; - //originalFunc->dump(); - } catch (int err) - { - (void)err; - std::cerr << "*** Failed to initialize a pixelpipeline module." << std::endl; - return false; - } - - return true; -} - - -/** - * \brief Loads the modules this compiler supports. - */ -bool PPCompiler::init() -{ - if (!initPPContext(m_ppContext, integerPixelPipe_binary, sizeof(integerPixelPipe_binary), "executePixelPipeline")) - return false; - - if (!initPPContext(m_blitterContext, integerBlitter_binary, sizeof(integerBlitter_binary), "executeBlitter")) - return false; - - m_ppCache.setLLVMInterface(m_executionEngine, m_ppContext.module); - m_blitterCache.setLLVMInterface(m_executionEngine, m_blitterContext.module); - - return true; -} - -// Helps cast void* to function pointers (may be platform dependent, usually works): -union FuncCaster { - void* ptr; - PixelPipeFunction pipeFunc; - BlitterFunction blitFunc; -}; - -PPCompiler::PartialEvalFunc PPCompiler::compilePixelPipeline(::llvm::LLVMContext& llvmContext, PPCompilerContext& compilerContext, ConstantGenFunc constGenFunc, const void* state, const std::string& newFunctionName) -{ - // Get the constant state argument (must be the first in the list): - ::llvm::Function::arg_iterator argit = compilerContext.llvmFunction->arg_begin(); - ::llvm::Argument& arg = *argit; - //arg.getType()->dump(); - - ::llvm::Constant* constantState = constGenFunc(state, llvmContext, arg.getType()->getContainedType(0)); - - RI_ASSERT(constantState); - - //constantState->dump(); - - // \todo Even though this variable could be automatically cleaned up by the optimizations, - // it should be stored in the cache and destroyed along with the function when - // the cache-entry is dropped out. - ::llvm::GlobalVariable* constantStateVariable = new ::llvm::GlobalVariable( - *compilerContext.module, constantState->getType(), true, ::llvm::GlobalValue::PrivateLinkage, constantState, newFunctionName + "_constState"); - - // When to delete the global variable? - // -> When the pixel-pipe is removed from the cache. Also, when the compiler is deleted. - - ::llvm::DenseMap valueMap; - std::pair valueReplacement((::llvm::Value*)&arg, constantStateVariable); - valueMap.insert(valueReplacement); - - ::llvm::Function* specializedFunc = ::llvm::CloneFunction(compilerContext.llvmFunction, valueMap, NULL); - specializedFunc->setName(newFunctionName); - //specializedFunc->dump(); - - compilerContext.module->getFunctionList().push_back(specializedFunc); - - // \note Currently this creates the pass manager every time a pipeline is compiled... - ::llvm::PassManager pm; - // \todo Seems like the greater the threshold, the more the pass will inline: - // In practice, everything should be inlineed into the resulting pipe. - ::llvm::Pass* inliningPass = ::llvm::createFunctionInliningPass(100000); - ::llvm::createStandardModulePasses(&pm, 3, false, true, true, true, false, inliningPass); - pm.run(*compilerContext.module); - - //ppModule->dump(); - - //compilerContext.llvmFunction->dump(); - PartialEvalFunc ret = {specializedFunc, constantStateVariable}; - return ret; -} - -/** - * \brief Compile a pipeline if necessary. If the pipeline is cached, return a - * handle to it. - * \return NULL handle if operation was not successful, otherwise a handle to the pipeline. - * \todo For deferred JITting, it might make sense to return a special value - * to indicate that the pipeline is under compilation. - * \note LLVM compilation should be thread-safe internally. - */ -PPCompiler::PixelPipeHandle PPCompiler::compilePixelPipeline(const PixelPipe::SignatureState& state) -{ - PixelPipeHash hash; - calculatePPHash(hash, state); - - PixelPipeEntryHandle entry = m_ppCache.findCachedItemByHash(hash); - - if (!entry) - { - PartialEvalFunc pf; - std::string funcName = "compiledPPFunc_" + PPCompiler::stringOfArray(hash.value, sizeof(hash.value)/sizeof(hash.value[0])); - pf = compilePixelPipeline(getLLVMContext(), m_ppContext, createPPConstant, (const void*)&state, funcName.c_str()); - entry = m_ppCache.cacheFunction(hash, pf.llvmFunc, pf.llvmConst); -#if defined(RI_DEBUG) && 0 - pf.llvmFunc->dump(); -#endif - } - - if (!entry) - { - RI_ASSERT(false); - // Release the function! - } - - return (PixelPipeHandle)entry; -} - -PPCompiler::BlitterHandle PPCompiler::compileBlitter(const DynamicBlitter::BlitSignatureState& state) -{ - // \todo This function is almost the same as compilePixelPipeline. - BlitterHash hash; - DynamicBlitter::calculateHash(hash, state); - - BlitterEntryHandle entry = m_blitterCache.findCachedItemByHash(hash); - - if (!entry) - { - PartialEvalFunc pf; - std::string funcName = "compiledBlitterFunc_" + PPCompiler::stringOfArray(hash.value, sizeof(hash.value)/sizeof(hash.value[0])); - pf = compilePixelPipeline(getLLVMContext(), m_blitterContext, createBlitterConstant, (const void*)&state, funcName.c_str()); - entry = m_blitterCache.cacheFunction(hash, pf.llvmFunc, pf.llvmConst); - } - - if (!entry) - { - RI_ASSERT(false); - // Release the function! - } - - RI_ASSERT(entry); - - return (BlitterHandle)entry; -} - -PixelPipeFunction PPCompiler::getPixelPipePtr(PixelPipeHandle handle) -{ - PixelPipeEntryHandle entryHandle = (PixelPipeEntryHandle)handle; - ::llvm::Function* function = m_ppCache.getFunction(entryHandle); - - FuncCaster c; - c.ptr = m_executionEngine->getPointerToFunction(function); - return c.pipeFunc; -} - -BlitterFunction PPCompiler::getBlitterPtr(BlitterHandle handle) -{ - BlitterEntryHandle entryHandle = (BlitterEntryHandle)handle; - ::llvm::Function* function = m_blitterCache.getFunction(entryHandle); - - FuncCaster c; - c.ptr = m_executionEngine->getPointerToFunction(function); - return c.blitFunc; -} - -// Release a reference to a pixel-pipeline handle. -void PPCompiler::releasePixelPipeline(PixelPipeHandle handle) -{ - PixelPipeEntryHandle entryHandle = (PixelPipeEntryHandle)handle; - m_ppCache.releaseEntry(entryHandle); -} - -// Release a reference to a blitter handle. -void PPCompiler::releaseBlitter(BlitterHandle handle) -{ - BlitterEntryHandle entryHandle = (BlitterEntryHandle)handle; - m_blitterCache.releaseEntry(entryHandle); -} - -#if 0 -// \todo Complete this and make it fully recursive: this way all the C-structs -// can be converted to corresponding LLVM classes at runtime. -::llvm::Constant* PPCompiler::createConstantStruct(const void* structure, size_t structSize, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType) const -{ - // Only copies integer-values (int, bools) - RIuint8* bytePtr = (RIuint8*)structure; - ::llvm::Type::subtype_iterator subtypeBegin, subtypeEnd; - - subtypeBegin = structType->subtype_begin(); - subtypeEnd = structType->subtype_end(); - - for(::llvm::Type::subtype_iterator it = subtypeBegin; it != subtypeEnd; ++it) - { - ::llvm::Type* elementType = *it; - RI_ASSERT(elementType->isSized()); - unsigned int elementBitSize = elementType->getPrimitiveSizeInBits(); - RI_ASSERT((elementBitSize % 8) == 0); - unsigned int elementSize = elementBitSize / 8; - RI_ASSERT(elementSize > 0 && elementSize <= 4); - - bytePtr += elementSize; - } -} -#endif -/** - * \brief Creates a LLVM constant from a color descriptor. - * \todo Create global constants from these for every possible color format! - */ -RI_INLINE static ::llvm::Constant* createDescConstant(const Color::Descriptor& desc, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType) -{ - ::llvm::Constant* constants[] = { - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.redBits, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.redShift, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.greenBits, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.greenShift, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.blueBits, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.blueShift, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.alphaBits, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.alphaShift, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.luminanceBits, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.luminanceShift, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.shape, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.vgFormat, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.internalFormat, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.bitsPerPixel, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.bytesPerPixel, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.maskBits, true), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), desc.maskShift, true), - }; - - std::vector< ::llvm::Constant*> structConsts; - - for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++) - { - structConsts.push_back(constants[i]); - } - - ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts); - - return constStruct; -} - -::llvm::Constant* PPCompiler::createPPConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType) -{ - // Get the actual object. This is a messy way to abstract setting the structure, but - // there is little sense in making more classes/adapters/whatever at this point. - const PixelPipe::SignatureState& state = *(const PixelPipe::SignatureState*)signatureState; - // \todo There seems to be no way to track the structure member names once - // LLVM has generated the bitcode (only offsets and references to those - // offsets remain). Means to track proper setting of struct members in - // DEBUG build must be implemented in some other way. - // - // For now, the state and this function must be kept carefully in sync! - - const int cDescriptorElementIndex = 8; - const ::llvm::Type* descType = structType->getContainedType(cDescriptorElementIndex); - - ::llvm::Constant* constants[] = { - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.blendMode, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageMode, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintType, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.maskOperation, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintTilingMode, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.paintSampler, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageSampler, false), - - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.imageGradientType, false), - - createDescConstant(state.dstDesc, llvmContext, descType), - createDescConstant(state.maskDesc, llvmContext, descType), - createDescConstant(state.imageDesc, llvmContext, descType), - createDescConstant(state.patternDesc, llvmContext, descType), - - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasMasking, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasImage, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.hasColorTransform, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.isRenderToMask, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.fillColorTransparent, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.unsafeImageInput, false), - }; - - std::vector< ::llvm::Constant*> structConsts; - - for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++) - { - structConsts.push_back(constants[i]); - } - - ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts); - - return constStruct; -} - -::llvm::Constant* PPCompiler::createBlitterConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType) -{ - const DynamicBlitter::BlitSignatureState& state = *(const DynamicBlitter::BlitSignatureState*)signatureState; - - const int cDescriptorElementIndex = 4; - const ::llvm::Type* descType = structType->getContainedType(cDescriptorElementIndex); - - ::llvm::Constant* constants[] = { - ::llvm::ConstantInt::get(::llvm::Type::getInt32Ty(llvmContext), state.maskOperation, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.incompatibleStrides, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.isMaskOperation, false), - ::llvm::ConstantInt::get(::llvm::Type::getInt8Ty(llvmContext), state.unsafeInput, false), - - createDescConstant(state.srcDesc, llvmContext, descType), - createDescConstant(state.dstDesc, llvmContext, descType), - }; - - std::vector< ::llvm::Constant*> structConsts; - - for (size_t i = 0; i < sizeof(constants)/sizeof(constants[0]); i++) - { - structConsts.push_back(constants[i]); - } - - ::llvm::Constant* constStruct = ::llvm::ConstantStruct::get((::llvm::StructType*)structType, structConsts); - - return constStruct; -} - -/** - * \brief Find a function whose name containst ``namepart''. Useful for finding c++ - * decorated names from modules (if they are unique). - * \note Maybe should use C-functions only in the final product. - */ -::llvm::Function* PPCompiler::findFunctionWithString(::llvm::Module* module, const char* namepart) -{ - // Find a function whose name contains 'namepart' - llvm::Module::iterator it, end; - it = module->begin(); - end = module->end(); - for (; it != end; ++it) - { - if (!it->isDeclaration()) - if (it->getNameStr().find(namepart) != std::string::npos) - return it; - } - return NULL; -} - -void PPCompiler::llvmCheckPtrError(const void* ptr, std::string& err) -{ -#if defined(RI_DEBUG) - (void)err; - //std::cout << "LLVM returned: " << ptr << ". Error string: \"" << err << "\"" << std::endl; -#else - (void)err; -#endif - if (!ptr) - throw(-1); -} - -/*static*/ std::string PPCompiler::stringOfArray(const RIuint32* arr, int nElems) -{ - char tempBuffer[9]; - std::stringstream out; - // Ambiquities resolved by using a constant width: - RI_ASSERT(nElems > 0); - int i = nElems-1; - do { - snprintf(tempBuffer, sizeof(tempBuffer), "%08x", arr[i]); - out << tempBuffer; - i--; - } while(i >= 0); - - return out.str(); -} - -} - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfCompiler.h --- a/hostsupport/hostopenvg/src/src/sfCompiler.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,156 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __SFCOMPILER_H -#define __SFCOMPILER_H - -#include - -#ifndef __SFDYNAMICPIXELPIPE_H -# include "sfDynamicPixelPipe.h" -#endif - -#ifndef __SFDYNAMICBLITTER_H -# include "sfDynamicBlitter.h" -#endif - -#ifndef __RIPIXELPIPE_H -# include "riPixelPipe.h" -#endif - -#ifndef __SFFUNCTIONCACHE_H -# include "sfFunctionCache.h" -#endif - -#include "llvm/LLVMContext.h" - -// \note PPCompiler class also caches a certain amount of compiled functions. -// It may make sense to move the cache into a separate container. - -// LLVM forward declarations -namespace llvm { - class Type; - class Constant; - class Function; - class Module; - class ExecutionEngine; -} - -namespace OpenVGRI { - -// Pixel-pipeline function with constant state removed: -typedef void (*PixelPipeFunction)(const PixelPipe::PPUniforms&, PixelPipe::PPVariants&, const Span*, int); -// Image-blitting function with constant state removed: -typedef void (*BlitterFunction)(const DynamicBlitter::BlitUniforms&); - -class PPCompiler -{ -public: - typedef int PixelPipeHandle; - typedef int BlitterHandle; -private: - // Function that generates LLVM-constant from a pixel-pipeline: - typedef ::llvm::Constant* (*ConstantGenFunc)(const void* structure, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType); - - struct PPCompilerContext { - PPCompilerContext(); - ~PPCompilerContext(); - // Stores persistent objects related to each component (pixelpipe or blitter). - // Note that the execution engine must be a per-process singleton for LLVM before - // version 2.7! - ::llvm::Module* module; - ::llvm::Function* llvmFunction; - }; - - struct PartialEvalFunc - { - ::llvm::Function* llvmFunc; - ::llvm::GlobalVariable* llvmConst; - }; - -public: - PPCompiler(); - ~PPCompiler(); - - static PartialEvalFunc compilePixelPipeline(::llvm::LLVMContext& llvmContext, PPCompilerContext& compilerContext, ConstantGenFunc constGenFunc, const void* state, const std::string& newFuntionName); - - // These functions get an reserve a handle to a pixelpipe/blitter. MUST use release - // after done with the function. - PixelPipeHandle compilePixelPipeline(const PixelPipe::SignatureState& state); - BlitterHandle compileBlitter(const DynamicBlitter::BlitSignatureState& state); - - PixelPipeFunction getPixelPipePtr(PixelPipeHandle handle); - BlitterFunction getBlitterPtr(BlitterHandle handle); - - void releasePixelPipeline(PixelPipeHandle handle); - void releaseBlitter(BlitterHandle handle); - - bool init(); - - // It seems that under VS, the static init order is not correct so the compiler has to be created - // during run-time. - static PPCompiler& getCompiler() { if(!s_compiler) { s_compiler = new PPCompiler(); } return *s_compiler; } - -private: - bool initPPContext(PPCompilerContext& context, const unsigned char* data, size_t dataSize, const char* functionName); - //void* compileRenderingFunction(const void* signatureState, RenderingFunctionType type); - - static ::llvm::Constant* createConstantStruct(const void* structure, size_t structureSize, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType); - static ::llvm::Constant* createPPConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType); - static ::llvm::Constant* createBlitterConstant(const void* signatureState, ::llvm::LLVMContext& llvmContext, const ::llvm::Type* structType); - static ::llvm::Function* findFunctionWithString(::llvm::Module* module, const char* namepart); - static void llvmCheckPtrError(const void* ptr, std::string& err); - - static std::string stringOfArray(const RIuint32* arr, int nElems); - -private: - //::llvm::LLVMContext& getLLVMContext() { return ::llvm::getGlobalContext(); } - ::llvm::LLVMContext& getLLVMContext() { return m_llvmContext; } - - // The order is important atm. because llvm context must be destroyed last: - //::llvm::LLVMContext& m_llvmContext; - PPCompilerContext m_blitterContext; - PPCompilerContext m_ppContext; - ::llvm::ExecutionEngine* m_executionEngine; - - // \note Loading a system with LLVM already consumes a lot of memory, so - // the amount of cached functions can be grown substantially depending on - // requirements. - enum { NUM_CACHED_PIXELPIPES = 64 }; - enum { NUM_CACHED_BLITTERS = NUM_CACHED_PIXELPIPES }; - - FunctionCache m_ppCache; - FunctionCache m_blitterCache; - typedef FunctionCache::EntryHandle PixelPipeEntryHandle; - typedef FunctionCache::EntryHandle BlitterEntryHandle; - //std::vector > blitterCache; - - ::llvm::LLVMContext m_llvmContext; - - static PPCompiler* s_compiler; -}; - -} - - -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfDynamicBlitter.cpp --- a/hostsupport/hostopenvg/src/src/sfDynamicBlitter.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,217 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#include "sfDynamicBlitter.h" - -#ifndef __SFBLITTER_H -# include "sfBlitter.h" -#endif - -#ifndef __SFMASK_H -# include "sfMask.h" -#endif - -namespace OpenVGRI { - -RI_INLINE static bool maskOperationRequiresLoad(VGMaskOperation op) -{ - switch(op) - { - case VG_CLEAR_MASK: - case VG_FILL_MASK: - case VG_SET_MASK: - return false; - default: - RI_ASSERT(op == VG_UNION_MASK || op == VG_INTERSECT_MASK || op == VG_SUBTRACT_MASK); - return true; - } -} - -/** - * \brief Blit rectangular areas between similar or different color format buffers. - * \note Implementation is structured so that the per-pixel branches are minimized - * even if dynamic compilation is not in use. - * \todo For some reason the completely generic integer conversion does not optimize - * fully run-time. Check what causes this! - */ -void executeBlitter(const DynamicBlitter::BlitSignatureState& state, const DynamicBlitter::BlitUniforms& uniforms) -{ - const void* srcPtr = Image::calculateAddress( - uniforms.src, state.srcDesc.bitsPerPixel, uniforms.srcX, uniforms.srcY, uniforms.srcStride); - void* dstPtr = Image::calculateAddress( - uniforms.dst, state.dstDesc.bitsPerPixel, uniforms.dstX, uniforms.dstY, uniforms.dstStride); - - // The following flag is useful for debugging. Enabling it will hurt performance. -//#define ALWAYS_FORCE_FULL_CONVERSION - - // Currently the data must be byte-aligned for memcpy optimizations: - const int minBpp = RI_INT_MIN(state.srcDesc.bitsPerPixel, state.dstDesc.bitsPerPixel); - const bool byteCopy = minBpp >= 8 ? true : false; - const bool forceFullConversion = state.isMaskOperation || state.unsafeInput || !byteCopy; - -#if !defined(ALWAYS_FORCE_FULL_CONVERSION) - if (state.srcDesc.isZeroConversion(state.dstDesc) && !forceFullConversion) - { - const int fullCopyStride = Image::descriptorToStride(state.srcDesc, uniforms.width); - - if ((uniforms.dstStride != uniforms.srcStride) || (fullCopyStride != uniforms.srcStride)) - { - // memcpy individual scanlines. - const size_t scanLength = (size_t)RI_INT_ABS(Image::descriptorToStride(state.srcDesc, uniforms.width)); - for (RIuint32 i = 0; i < uniforms.height; i++) - { - memcpy(dstPtr, srcPtr, scanLength); - dstPtr = (void*)((RIuint8*)dstPtr + uniforms.dstStride); - srcPtr = (void*)((RIuint8*)srcPtr + uniforms.srcStride); - } - } else - { - // memcpy the whole area - memcpy(dstPtr, srcPtr, uniforms.srcStride * uniforms.height); - } - } else if (state.srcDesc.isShiftConversion(state.dstDesc) && !forceFullConversion) - { - // \todo Separate to function? Replace with pointer read/write & advance. - if (state.srcDesc.isShiftConversionToLower(state.dstDesc)) - { - // Components can be immediately shifted down to lower bit-depth. - for (RIuint32 j = 0; j < uniforms.height; j++) - { - RIuint8* srcStart = (RIuint8*)srcPtr; - RIuint8* dstStart = (RIuint8*)dstPtr; - RIuint32 srcX = uniforms.srcX; - RIuint32 dstX = uniforms.dstX; - for (RIuint32 i = 0; i < uniforms.width; i++) - { - RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX); // \todo srcX! - RIuint32 dc = Color::Descriptor::crossConvertToLower(c, state.srcDesc, state.dstDesc); - Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc); - - srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX); - dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); - - srcX++; - dstX++; - } - srcPtr = (void*)(srcStart + uniforms.srcStride); - dstPtr = (void*)(dstStart + uniforms.dstStride); - } - } - else - { - // Color components require expansion before shifting to destination color-format */ - for (RIuint32 j = 0; j < uniforms.height; j++) - { - RIuint8* srcStart = (RIuint8*)srcPtr; - RIuint8* dstStart = (RIuint8*)dstPtr; - RIuint32 srcX = uniforms.srcX; - RIuint32 dstX = uniforms.dstX; - for (RIuint32 i = 0; i < uniforms.width; i++) - { - RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX); - IntegerColor ic = IntegerColor(c, state.srcDesc); - ic.expandColor(state.srcDesc); - ic.truncateColor(state.dstDesc); - RIuint32 dc = ic.getPackedColor(state.dstDesc); - Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc); - - srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX); - dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); - - srcX++; - dstX++; - } - srcPtr = (void*)(srcStart + uniforms.srcStride); - dstPtr = (void*)(dstStart + uniforms.dstStride); - } - } - } else -#endif - { - /* This block should handle the rest (and all) of the color-conversion cases. */ - for (RIuint32 j = 0; j < uniforms.height; j++) - { - RIuint8* srcStart = (RIuint8*)srcPtr; - RIuint8* dstStart = (RIuint8*)dstPtr; - RIuint32 srcX = uniforms.srcX; - RIuint32 dstX = uniforms.dstX; - for (RIuint32 i = 0; i < uniforms.width; i++) - { - RIuint32 c = Image::readPackedPixelFromAddress(srcPtr, state.srcDesc.bitsPerPixel, srcX); - IntegerColor ic; - RIuint32 dc; - - if (!state.isMaskOperation) - { - ic = IntegerColor(c, state.srcDesc); - if (state.unsafeInput) - ic.clampToAlpha(); - - ic.convertToFrom(state.dstDesc, state.srcDesc, false); - dc = ic.getPackedColor(state.dstDesc); - } - else - { - // Apply the given mask operation between two surfaces. - IntegerColor id; - - if (maskOperationRequiresLoad(state.maskOperation)) - { - ic.fromPackedMask(c, state.srcDesc); - ic.expandMask(state.srcDesc); - - IntegerColor id; - - RIuint32 d = Image::readPackedPixelFromAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX); - id.fromPackedMask(d, state.dstDesc); - id.expandColor(state.dstDesc); - - RIuint32 coverage = ic.a + (ic.a >> 7); - ic = intMaskOperation(coverage, id, state.maskOperation); - } - else - { - // Other ops handled with memset, not blitter - RI_ASSERT(state.maskOperation == VG_SET_MASK); - ic.fromPackedMask(c, state.srcDesc); - //ic.expandMask(state.srcDesc); - ic.convertToFrom(state.dstDesc, state.srcDesc, true); - } - dc = ic.getPackedMaskColor(state.dstDesc); - } - - Image::writePackedPixelToAddress(dstPtr, state.dstDesc.bitsPerPixel, dstX, dc); - - srcPtr = Image::incrementPointer(srcPtr, state.srcDesc.bitsPerPixel, srcX); - dstPtr = (void*)Image::incrementPointer(dstPtr, state.dstDesc.bitsPerPixel, dstX); - - srcX++; - dstX++; - } - srcPtr = (void*)(srcStart + uniforms.srcStride); - dstPtr = (void*)(dstStart + uniforms.dstStride); - } - } -} - -} - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfDynamicBlitter.h --- a/hostsupport/hostopenvg/src/src/sfDynamicBlitter.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,38 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __SFDYNAMICBLITTER_H -#define __SFDYNAMICBLITTER_H - -#ifndef __SFBLITTER_H -# include "sfBlitter.h" -#endif - -namespace OpenVGRI { - -// Blitter function (may be statically compiled also) -void executeBlitter(const DynamicBlitter::BlitSignatureState& state, const DynamicBlitter::BlitUniforms& uniforms); - -} - -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfDynamicPixelPipe.cpp --- a/hostsupport/hostopenvg/src/src/sfDynamicPixelPipe.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1533 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -// This file contains the generated pixel-pipeline code and provides -// interface to compile and run them. - -#ifndef __RIRASTERIZER_H -# include "riRasterizer.h" -#endif - -#ifndef __RIPIXELPIPE_H -# include "riPixelPipe.h" -#endif - -#ifndef __SFDYNAMICPIXELPIPE_H -# include "sfDynamicPixelPipe.h" -#endif - -#ifndef __RIUTILS_H -# include "riUtils.h" -#endif - -#ifndef __SFMASK_H -# include "sfMask.h" -#endif - -#ifndef __RIIMAGE_H -# include "riImage.h" -#endif - -#if defined(RI_DEBUG) -# include -#endif - -namespace OpenVGRI { - -RI_INLINE static bool alwaysLoadDst(const PixelPipe::SignatureState& state) -{ - if (!state.isRenderToMask) - { - if (state.hasImage) - return true; - - VGBlendMode bm = state.blendMode; - - if (bm == VG_BLEND_SRC_IN || - bm == VG_BLEND_DST_OVER || - bm == VG_BLEND_DST_IN || - bm == VG_BLEND_ADDITIVE || - bm == VG_BLEND_MULTIPLY || - bm == VG_BLEND_SCREEN || - bm == VG_BLEND_DARKEN || - bm == VG_BLEND_LIGHTEN) - { - return true; - } else - { - return false; - } - } - else - { - switch (state.maskOperation) - { - case VG_SET_MASK: - return false; - default: - return true; - } - } -} - -RI_INLINE static bool canSolidFill(const PixelPipe::SignatureState& state) -{ - if (state.isRenderToMask) - { - if (state.maskOperation == VG_SET_MASK || - state.maskOperation == VG_UNION_MASK) - return true; - // \note SUBTRACT is also possible. - return false; - } - - if (state.paintType != VG_PAINT_TYPE_COLOR) - return false; - - if (state.hasImage) - return false; - - // Some blendmodes can use dst color even if coverage == 1.0 - if (state.blendMode != VG_BLEND_SRC && state.blendMode != VG_BLEND_SRC_OVER) - return false; - - if (state.hasMasking) - return false; - - if (state.fillColorTransparent) - return false; - - if (state.hasColorTransform) - return false; // \todo Trace solid color alpha -> 1.0 - - return true; -} - -RI_INLINE static int intReflectRepeat(int n, int bits) -{ - const int mask = (1<> 31)) & mask; -} - -RI_INLINE static void applyGradientRepeat(int& sx0, int& sx1, PixelPipe::TilingMode sm) -{ - switch (sm) - { - case PixelPipe::TILING_MODE_PAD: - sx0 = RI_INT_CLAMP(sx0, 0, PixelPipe::SAMPLE_MASK); - sx1 = RI_INT_CLAMP(sx1, 0, PixelPipe::SAMPLE_MASK); - break; - case PixelPipe::TILING_MODE_REFLECT: - sx0 = intReflectRepeat(sx0, PixelPipe::SAMPLE_BITS); - sx1 = intReflectRepeat(sx1, PixelPipe::SAMPLE_BITS); - break; - default: - RI_ASSERT(sm == PixelPipe::TILING_MODE_REPEAT); - - sx0 = sx0 & PixelPipe::SAMPLE_MASK; - sx1 = sx1 & PixelPipe::SAMPLE_MASK; - break; - } - - RI_ASSERT(sx0 >= 0 && sx0 < (1<= 0 && sx1 < (1<= 0 && i <= Paint::GRADIENT_LUT_MASK); - return uniforms.gradientLookup[i]; -} - - -/** - * \brief Sample linear gradient using integer-arithmetic. - * \note The actual gradient computation is done piecewise within the - * pixel-pipeline. - */ -RI_INLINE static IntegerColor intLinearGradient(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v) -{ - RIint32 sx0 = v.sx >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS); - RIint32 sx1 = sx0 + 1; - - applyGradientRepeat(sx0, sx1, state.paintTilingMode); - - IntegerColor ic0 = readLUTColor(u, sx0 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS)); - - if (true) - { - return ic0; - } else - { - // bilinear interpolation - //RIint32 f1 = sx0; - readLUTColor(u, sx1 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS)); - RI_ASSERT(false); - return IntegerColor(0,0,0,0); - } -} - -/** - * \brief Radial gradient implementation for the integer-pipeline. Will use float at least - * for the square-root. Will return integer-color always. - */ -RI_INLINE static IntegerColor intRadialGradient(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v) -{ - RGScalar a = (v.rx * u.rfxp) + (v.ry * u.rfyp); - RGScalar b = u.rsqrp * (RI_SQR(v.rx) + RI_SQR(v.ry)); - RGScalar c = RI_SQR((v.rx * u.rfyp) - (v.ry * u.rfxp)); - RGScalar d = b - c; - RI_ASSERT(!RI_ISNAN(d) ? d >= 0.0f : true); - RGScalar g = (a + sqrtf(d)); - - int sx0 = RI_FLOAT_TO_FX(g, PixelPipe::SAMPLE_BITS); - int sx1 = sx0 + 1; - - applyGradientRepeat(sx0, sx1, state.paintTilingMode); - - IntegerColor ic0 = readLUTColor(u, sx0 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS)); - RI_ASSERT(ic0.r <= 255); - RI_ASSERT(ic0.g <= 255); - RI_ASSERT(ic0.b <= 255); - RI_ASSERT(ic0.a <= 255); - - if (false) - { - // Linear interpolation of 2 gradient samples. - IntegerColor ic1 = readLUTColor(u, sx1 >> (PixelPipe::SAMPLE_BITS - Paint::GRADIENT_LUT_BITS)); - //int fx0 = sx0 & PixelPipe::SAMPLE_MASK; - //int fx1 = PixelPipe::SAMPLE_MASK - fx0; - - } - - return ic0; -} - -RI_INLINE static bool applyPatternRepeat(int &x, int &y, PixelPipe::TilingMode tilingMode) -{ - switch (tilingMode) - { - case PixelPipe::TILING_MODE_PAD: - x = RI_INT_CLAMP(x, 0, PixelPipe::GRADIENT_MASK); - y = RI_INT_CLAMP(y, 0, PixelPipe::GRADIENT_MASK); - break; - case PixelPipe::TILING_MODE_REPEAT: - x = x & PixelPipe::GRADIENT_MASK; - y = y & PixelPipe::GRADIENT_MASK; - break; - case PixelPipe::TILING_MODE_REFLECT: - x = intReflectRepeat(x, PixelPipe::GRADIENT_BITS); - y = intReflectRepeat(y, PixelPipe::GRADIENT_BITS); - break; - default: - RI_ASSERT(tilingMode == PixelPipe::TILING_MODE_FILL); - // Do nothing -> Fill is checked on integer coordinates. - break; - } - return false; -} - -/** - * \brief Same as applyPatternRepeat, but with pattern-space integer coordinates without - * fractional part. - * \note Assumes that the coordinate is in range [0,width or height]. - */ -RI_INLINE static bool applyPatternSampleRepeat(int &x, int &y, int w, int h, PixelPipe::TilingMode tilingMode) -{ - - switch (tilingMode) - { - case PixelPipe::TILING_MODE_PAD: - RI_ASSERT(x >= 0 && x <= w); - RI_ASSERT(y >= 0 && y <= h); - if (x >= w) x = w-1; - if (y >= h) y = h-1; - break; - case PixelPipe::TILING_MODE_REPEAT: - RI_ASSERT(x >= 0 && x <= w); - RI_ASSERT(y >= 0 && y <= h); - if (x >= w) x = 0; - if (y >= h) y = 0; - break; - case PixelPipe::TILING_MODE_REFLECT: - RI_ASSERT(x >= 0 && x <= w); - RI_ASSERT(y >= 0 && y <= h); - if (x >= w) x = w-1; // w-2? - if (y >= h) y = h-1; // h-2? - break; - default: - RI_ASSERT(tilingMode == PixelPipe::TILING_MODE_FILL); - if (x < 0 || x >= w) return true; - if (y < 0 || y >= h) return true; - break; - } - - return false; -} - -RI_INLINE IntegerColor readPattern(const void* basePtr, int stride, const Color::Descriptor& desc, int ix, int iy, const IntegerColor* fillColor, bool fill) -{ - const void* ptr = Image::calculateAddress(basePtr, desc.bitsPerPixel, ix, iy, stride); - - if (!fill) - return IntegerColor(Image::readPackedPixelFromAddress(ptr, desc.bitsPerPixel, ix), desc); - else - { - RI_ASSERT(fillColor); - return *fillColor; - } - -} - -/** - * \brief Rescale the result of bilinear interpolation. - * \todo See if this or individual shifts and rounds are faster on x86 - */ -RI_INLINE static RIuint32 bilinearDiv(unsigned int c) -{ - RIuint32 rcp = 33026; - - RIuint64 m = (RIuint64)c * rcp; - RIuint32 d = (RIuint32)(m >> 30); - return (d >> 1) + (d & 1); -} - -/** - * \brief Read an optionally filtered sample from an image. For multiple samples, apply repeat - * for all the generated sampling points. This only implements a simple sampling: nearest - * or Linear filtering and is much simpler than the original RI. - * \param image Image to sample from - * \param sx0 Sample x in .8 fixed point. MUST be within the image except for FILL. - * \param sy0 Sample y in .8 fixed point. MUST be within the image except for FILL. - * \param samplerType Type of the sampler used. - * \param tilingMode Tiling mode for generated sample points, if required. - * \param fillColor Color to use for TILING_MODE_FILL - * \todo Where should we determine if a NN-sample needs to be unpacked? - * -> It is also easy to just read that sample separately. - */ -RI_INLINE static IntegerColor intSampleImage( - const void* ptr, - int stride, - int w, - int h, - const Color::Descriptor& desc, - RIint32 sx0, - RIint32 sy0, - PixelPipe::SamplerType samplerType, - PixelPipe::TilingMode tilingMode, - const IntegerColor* fillColor) -{ - RI_ASSERT(fillColor || (tilingMode != PixelPipe::TILING_MODE_FILL)); - - // \todo The following code is between low- and high-level representation of sampling. - // It should probably be modified to appear fully as low-level, since we want as many - // optimizations as possible. - - const bool bilinear = samplerType == PixelPipe::SAMPLER_TYPE_LINEAR; - - IntegerColor retColor; - bool maybeFill = tilingMode == PixelPipe::TILING_MODE_FILL; - bool fillSample = false; - - RIint32 ix, iy; - - IntegerColor ic00; - - RIint32 fx = sx0 & 0xff; - RIint32 fy = sy0 & 0xff; - - ix = sx0 >> PixelPipe::SAMPLE_BITS; - iy = sy0 >> PixelPipe::SAMPLE_BITS; - - if (maybeFill) - { - if (ix < 0 || ix >= w) - fillSample = true; - if (iy < 0 || iy >= h) - fillSample = true; - } - - ic00 = readPattern(ptr, stride, desc, ix, iy, fillColor, fillSample); - - if (!bilinear) - { - retColor = ic00; - retColor.expandColor(desc); // \todo Handling of bilinear? - } - else - { - // Bilinear filtering. - - IntegerColor ic01, ic10, ic11; - IntegerColor t0, t1; - - int xs = ix + 1; - int ys = iy; - - fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode); - ic01 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample); - - t0 = IntegerColor::linearBlendNS(ic00, ic01, fx); - - xs = ix; - ys = iy+1; - fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode); - ic10 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample); - - xs = ix+1; - ys = iy+1; - fillSample = applyPatternSampleRepeat(xs, ys, w, h, tilingMode); - ic11 = readPattern(ptr, stride, desc, xs, ys, fillColor, fillSample); - - t1 = IntegerColor::linearBlendNS(ic10, ic11, fx); - - retColor = IntegerColor::linearBlendNS(t0, t1, fy); - - retColor.r = bilinearDiv(retColor.r); - retColor.g = bilinearDiv(retColor.g); - retColor.b = bilinearDiv(retColor.b); - retColor.a = bilinearDiv(retColor.a); - - return retColor; - } - - return retColor; -} - -RI_INLINE static RIint32 gradientToFixedCoords(RIint32 gradCoord, RIint32 dim) -{ - return (RIint32)(((RIint64)dim * gradCoord) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS)); -} - - -RI_INLINE static IntegerColor intPattern(const PixelPipe::SignatureState &state, const PixelPipe::PPUniforms& u, const PixelPipe::PPVariants& v) -{ - // \todo The following code is between low- and high-level representation of sampling. - // It should probably be modified to appear fully as low-level, since we want as many - // optimizations as possible. - - // "External" variables - const PixelPipe::TilingMode tilingMode = state.paintTilingMode; - const IntegerColor fillColor = u.tileFillColor; - const int w = u.paint_width; - const int h = u.paint_height; - - IntegerColor retColor; - - RIint32 sx0 = v.sx; - RIint32 sy0 = v.sy; - - IntegerColor ic00; - - applyPatternRepeat(sx0, sy0, tilingMode); - sx0 = gradientToFixedCoords(sx0, w); - sy0 = gradientToFixedCoords(sy0, h); - //sx0 = (RIint32)(((RIint64)w * sx0) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS)); - //sy0 = (RIint32)(((RIint64)h * sy0) >> (PixelPipe::GRADIENT_BITS - PixelPipe::SAMPLE_BITS)); - - const void* ptr = u.patternPtr; - const int stride = u.patternStride; - const Color::Descriptor& desc = state.patternDesc; - - return intSampleImage(ptr, stride, w, h, desc, sx0, sy0, state.paintSampler, tilingMode, &fillColor); -} - -RI_INLINE static bool formatPremultipliedAfterSampling(const Color::Descriptor& desc, PixelPipe::SamplerType samplerType, PixelPipe::ImageGradientType gradientType) -{ - // Sampled at pixel centers -> no processing of colors -> does not get premultiplied - if (gradientType == PixelPipe::GRADIENT_TYPE_INTEGER) - return desc.isPremultiplied(); - - if (samplerType != PixelPipe::SAMPLER_TYPE_NEAREST) - return true; - - return desc.isPremultiplied(); -} - -RI_INLINE static bool imagePremultipliedAfterSampling(const PixelPipe::SignatureState& state) -{ - RI_ASSERT(state.hasImage); - - return formatPremultipliedAfterSampling(state.imageDesc, state.imageSampler, state.imageGradientType); -} - -RI_INLINE static bool gradientPremultipliedAfterSampling(const PixelPipe::SignatureState& state) -{ - if (state.paintSampler != PixelPipe::SAMPLER_TYPE_NEAREST) - return true; - - return true; - - // Otherwise, the gradient value is a single sample, and should be in the destination - // color-space: - //return state.dstDesc.isPremultiplied(); -} - -RI_INLINE static bool patternPremultipliedAfterSampling(const PixelPipe::SignatureState& state) -{ - RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN); - - return formatPremultipliedAfterSampling(state.patternDesc, state.paintSampler, PixelPipe::GRADIENT_TYPE_FIXED); -} - -/** - * \brief Returns true if generated paint will be in RGB, false if luminance. - */ -RI_INLINE static bool paintInRGB(const PixelPipe::SignatureState& state) -{ - if (state.paintType != VG_PAINT_TYPE_PATTERN) - return true; - - return !state.patternDesc.isLuminance(); -} - - -/** - * \brief Applies color transform to input color - * \param isNonlinear "true" if input is nonlinear. This only affects luminance -> RGB conversion, - * other conversions happen in the input color-space. - * \note Leaves the color unpremultiplied, in source color-space and converts luminance to RGB - * \todo isNonlinear is not needed. It can be deduced from the state information! - */ -RI_INLINE static IntegerColor maybeColorTransform(const PixelPipe::SignatureState& state, const IntegerColor& c, const RIint32* colorTransformValues, bool isNonlinear) -{ - if (!state.hasColorTransform) - return c; - - RI_ASSERT(state.hasImage || state.paintType == VG_PAINT_TYPE_PATTERN); - - IntegerColor r = c; - - if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY) - { - r.unpremultiply(); - } - else if (state.imageMode == VG_DRAW_IMAGE_STENCIL || state.paintType == VG_PAINT_TYPE_PATTERN) - { - // -> Check pattern - if (patternPremultipliedAfterSampling(state)) - r.unpremultiply(); - } - else - { - // -> Check image - if (imagePremultipliedAfterSampling(state)) - r.unpremultiply(); - } - - // Check if it is necessary to convert to RGB: - if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY) - { - if (state.imageDesc.isLuminance() && !paintInRGB(state)) - { - r.fullLuminanceToRGB(false, isNonlinear, false, isNonlinear); - } - } - else if (state.imageMode == VG_DRAW_IMAGE_STENCIL) - { - if (state.patternDesc.isLuminance()) - r.fullLuminanceToRGB(false, isNonlinear, false, isNonlinear); - } - - // \todo Use lookup-tables in some cases? - r.r = (((RIint32)r.r * colorTransformValues[0]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[4]; - r.g = (((RIint32)r.g * colorTransformValues[1]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[5]; - r.b = (((RIint32)r.b * colorTransformValues[2]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[6]; - r.a = (((RIint32)r.a * colorTransformValues[3]) >> PixelPipe::COLOR_TRANSFORM_BITS) + colorTransformValues[7]; - - // Clamp (integerColor?) - r.r = (RIuint32)RI_INT_CLAMP((int)r.r, 0, 255); - r.g = (RIuint32)RI_INT_CLAMP((int)r.g, 0, 255); - r.b = (RIuint32)RI_INT_CLAMP((int)r.b, 0, 255); - r.a = (RIuint32)RI_INT_CLAMP((int)r.a, 0, 255); - - - return r; -} - -/// Some rounding multiplications for blends: - -/** - * \brief Multiply with rounding. - */ -RI_INLINE static RIuint32 rMul2(RIuint32 c0, RIuint32 c1, RIuint32 k0, RIuint32 k1) -{ - RIuint32 t = c0 * k0 + c1 * k1; - //RIuint32 r = (t + (t>>9)) >> 8; - RIuint32 r = (t + (1>>7))>>8; - RI_ASSERT(r <= 255); - return r; -} - -/** - * \brief Returns rounding color-multiplication: c0 + c1 * k - */ -RI_INLINE static RIuint32 rMul1(RIuint32 c0, RIuint32 c1, RIuint32 k) -{ - RIuint32 t = c1 * k; - RIuint32 r = c0 + ((t + (t >> 7)) >> 8); - RI_ASSERT(r <= 255); - return r; -} - -/** - * \brief Fixed-point multiplication - */ -RI_INLINE static RIuint32 rMul(RIuint32 c0, RIuint32 f) -{ - RIuint32 t = c0 * f; - return (t + (1<<7))>>8; -} - -/** - * \brief Multiply two colors [0, 255] - */ -RI_INLINE static RIuint32 cMul(RIuint32 c0, RIuint32 c1) -{ - RIuint32 t = c0 * c1; - RIuint32 r = (t + (t >> 9)) >> 8; - //RIuint32 t = c0 * c1; - //RIuint32 r = (t + (t >> 7))>>8; - RI_ASSERT(r <= 255); - return r; -} - -// \todo Are signed versions required? -RI_INLINE static RIuint32 cMin(RIuint32 c0, RIuint32 c1) -{ - return c0 <= c1 ? c0 : c1; -} - -RI_INLINE static RIuint32 cMax(RIuint32 c0, RIuint32 c1) -{ - return c0 >= c1 ? c0 : c1; -} - -/** - * \brief Blends two integer colors. Only considers the alpha-channels within - * the colors themselves. There should be a separate function to do - * blending with individual channel-alphas. - * \note It is also possible that LLVM is able to detect, whether individual alpha- - * channels contain a single/multi alpha - * \todo Overall, check how much and how fast LLVM is able to optimize out unused - * expressions. - */ -RI_INLINE static IntegerColor blendIntegerColors(const IntegerColor& s, const IntegerColor& d, VGBlendMode blendMode) -{ - IntegerColor r; - - switch(blendMode) - { - case VG_BLEND_SRC: - r = s; - break; - - case VG_BLEND_SRC_OVER: - { - RIuint32 ia = 255 - s.a; - r.r = rMul1(s.r, d.r, ia); - r.g = rMul1(s.g, d.g, ia); - r.b = rMul1(s.b, d.b, ia); - r.a = rMul1(s.a, d.a, ia); - break; - } - case VG_BLEND_DST_OVER: - { - RIuint32 ia = 255 - d.a; - r.r = rMul1(d.r, s.r, ia); - r.g = rMul1(d.g, s.g, ia); - r.b = rMul1(d.b, s.b, ia); - r.a = rMul1(d.a, s.a, ia); - break; - } - case VG_BLEND_SRC_IN: - { - r.r = cMul(s.r, d.a); - r.g = cMul(s.g, d.a); - r.b = cMul(s.b, d.a); - r.a = cMul(s.a, d.a); - break; - } - case VG_BLEND_DST_IN: - { - r.r = cMul(d.r, s.a); - r.g = cMul(d.g, s.a); - r.b = cMul(d.b, s.a); - r.a = cMul(d.a, s.a); - break; - } - case VG_BLEND_MULTIPLY: - { - RIuint32 iasrc, iadst; - iasrc = 255 - s.a; - iadst = 255 - d.a; - r.r = rMul2(s.r, d.r, iadst + d.r, iasrc); - r.g = rMul2(s.g, d.g, iadst + d.g, iasrc); - r.b = rMul2(s.b, d.b, iadst + d.b, iasrc); - r.a = rMul1(s.a, d.a, iasrc); - break; - } - case VG_BLEND_SCREEN: - { - r.r = rMul1(s.r, d.r, 255 - s.r); - r.g = rMul1(s.g, d.g, 255 - s.g); - r.b = rMul1(s.b, d.b, 255 - s.b); - r.a = rMul1(s.a, d.a, 255 - s.a); - break; - } - case VG_BLEND_DARKEN: - { - RIuint32 iasrc = 255 - s.a; - RIuint32 iadst = 255 - d.a; - r.r = cMin(rMul1(s.r, d.r, iasrc), rMul1(d.r, s.r, iadst)); - r.g = cMin(rMul1(s.g, d.g, iasrc), rMul1(d.g, s.g, iadst)); - r.b = cMin(rMul1(s.b, d.b, iasrc), rMul1(d.b, s.b, iadst)); - r.a = rMul1(s.a, d.a, iasrc); - break; - } - case VG_BLEND_LIGHTEN: - { - // \todo Compact darken w/r lighten? - RIuint32 iasrc = 255 - s.a; - RIuint32 iadst = 255 - d.a; - r.r = cMax(rMul1(s.r, d.r, iasrc), rMul1(d.r, s.r, iadst)); - r.g = cMax(rMul1(s.g, d.g, iasrc), rMul1(d.g, s.g, iadst)); - r.b = cMax(rMul1(s.b, d.b, iasrc), rMul1(d.b, s.b, iadst)); - //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a) - //in practice there can be a very slight difference because - //of the max operation in the blending formula that may cause color to exceed alpha. - //Because of this, we compute the result both ways and return the maximum. - r.a = cMax(rMul1(s.a, d.a, iasrc), rMul1(d.a, s.a, iadst)); - break; - } - default: - { - RI_ASSERT(blendMode == VG_BLEND_ADDITIVE); - r.r = cMin(s.r + d.r, 255); - r.g = cMin(s.g + d.g, 255); - r.b = cMin(s.b + d.b, 255); - r.a = cMin(s.a + d.a, 255); - break; - } - } - return r; - -} - -RI_INLINE static IntegerColor blendIntegerStencil(const IntegerColor& s, const IntegerColor& im, const IntegerColor& d, VGBlendMode blendMode) -{ - IntegerColor r; - - switch(blendMode) - { - case VG_BLEND_SRC: - r = s; - break; - - case VG_BLEND_SRC_OVER: - { - r.r = rMul1(s.r, d.r, 255 - im.r); - r.g = rMul1(s.g, d.g, 255 - im.g); - r.b = rMul1(s.b, d.b, 255 - im.b); - r.a = rMul1(s.a, d.a, 255 - s.a); - break; - } - case VG_BLEND_DST_OVER: - { - r = blendIntegerColors(s, d, blendMode); - break; - } - case VG_BLEND_SRC_IN: - { - r = blendIntegerColors(s, d, blendMode); - break; - } - case VG_BLEND_DST_IN: - { - r.r = cMul(d.r, im.r); - r.g = cMul(d.g, im.g); - r.b = cMul(d.b, im.b); - r.a = cMul(d.a, s.a); - break; - } - case VG_BLEND_MULTIPLY: - { - RIuint32 iadst; - iadst = 255 - d.a; - r.r = rMul2(s.r, d.r, iadst + d.r, 255 - im.r); - r.g = rMul2(s.g, d.g, iadst + d.g, 255 - im.g); - r.b = rMul2(s.b, d.b, iadst + d.b, 255 - im.b); - r.a = rMul1(s.a, d.a, 255 - s.a); - break; - } - case VG_BLEND_SCREEN: - { - r = blendIntegerColors(s, d, blendMode); - break; - } - case VG_BLEND_DARKEN: - { - RIuint32 iadst = 255 - d.a; - r.r = cMin(rMul1(s.r, d.r, 255 - im.r), rMul1(d.r, s.r, iadst)); - r.g = cMin(rMul1(s.g, d.g, 255 - im.g), rMul1(d.g, s.g, iadst)); - r.b = cMin(rMul1(s.b, d.b, 255 - im.b), rMul1(d.b, s.b, iadst)); - r.a = rMul1(s.a, d.a, 255 - s.a); - break; - } - case VG_BLEND_LIGHTEN: - { - // \todo Compact darken w/r lighten? - RIuint32 iadst = 255 - d.a; - r.r = cMax(rMul1(s.r, d.r, 255 - im.r), rMul1(d.r, s.r, iadst)); - r.g = cMax(rMul1(s.g, d.g, 255 - im.g), rMul1(d.g, s.g, iadst)); - r.b = cMax(rMul1(s.b, d.b, 255 - im.b), rMul1(d.b, s.b, iadst)); - //although the statement below is equivalent to r.a = s.a + d.a * (1.0f - s.a) - //in practice there can be a very slight difference because - //of the max operation in the blending formula that may cause color to exceed alpha. - //Because of this, we compute the result both ways and return the maximum. - r.a = cMax(rMul1(s.a, d.a, 255 - s.a), rMul1(d.a, s.a, iadst)); - break; - } - default: - { - RI_ASSERT(blendMode == VG_BLEND_ADDITIVE); - return blendIntegerColors(s, d, blendMode); - break; - } - } - return r; - -} - -/** - * \brief Perform SRC_OVER and apply coverage in a single operation. - * \note It is possible to do optimizations like this for other blending operations, - * but they are not as widely used -> optimize if there is a requirement. - * \note Prints are included because GDB is confused about the value of r. - */ -static RI_INLINE IntegerColor srcOverCoverage(const IntegerColor& s, const IntegerColor& d, RIuint32 cov) -{ - IntegerColor r; - RIuint32 ac = ((s.a + (s.a>>7)) * cov); - ac = (ac + (1<<7))>>8; - RIuint32 ia = 256 - ac; - - r.r = rMul2(s.r, d.r, cov, ia); - r.g = rMul2(s.g, d.g, cov, ia); - r.b = rMul2(s.b, d.b, cov, ia); - r.a = rMul2(s.a, d.a, cov, ia); - //r.r = (s.r * cov + d.r * ia) >> 8; - //r.g = (s.g * cov + d.g * ia) >> 8; - //r.b = (s.b * cov + d.b * ia) >> 8; - //r.a = (s.a * cov + d.a * ia) >> 8; - -#if defined(RI_DEBUG) - if (!(r.r <= r.a && r.g <= r.a && r.b <= r.a && r.a <= 255)) - { - printf("r: %d, g: %d, b: %d, a: %d\n",r.r,r.g,r.b,r.a); - RI_ASSERT(false); - } - //RI_ASSERT(r.r <= 255 && r.g <= 255 && r.b <= 255 && r.a <= 255); -#endif - - return r; -} - -/** - * \brief Check if converting between two color formats requires a gamma-conversion. - * \todo Move this to descriptor class. - */ -static RI_INLINE bool needGammaConvert(const Color::Descriptor& srcDesc, const Color::Descriptor& dstDesc) -{ - //if ((!srcDesc.isAlphaOnly()) && (srcDesc.isNonlinear() != dstDesc.isNonlinear())) - //return true; - if ((srcDesc.isNonlinear() != dstDesc.isNonlinear())) - return true; - - return false; -} - - -RI_INLINE static bool preBlendPremultiplication(const PixelPipe::SignatureState& state) -{ - // \todo Simplify the rules (see the corresponding places in the pixelpipe - const bool colorTransform = state.hasColorTransform; - - if (PixelPipe::isImageOnly(state)) - { - if (colorTransform) - return true; - - // Gamma conversion will leave the result premultiplied - if (needGammaConvert(state.imageDesc, state.dstDesc)) - return true; - //if (state.imageDesc.isAlphaOnly()) - //return false; - - return !imagePremultipliedAfterSampling(state); - } - - if (state.hasImage) - { - if (state.imageMode == VG_DRAW_IMAGE_NORMAL) - return !imagePremultipliedAfterSampling(state); - // Image color has been combined with the paint color and that requires premultiplication - if (state.imageMode == VG_DRAW_IMAGE_MULTIPLY) - return false; // Always results in a premultiplied output color - - return false; // ? - } - - if (state.paintType == VG_PAINT_TYPE_COLOR) - return false; - - if (state.paintType != VG_PAINT_TYPE_PATTERN) - return !gradientPremultipliedAfterSampling(state); - - // Must be pattern - RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN); - - if (state.hasColorTransform) - return true; - - if (needGammaConvert(state.patternDesc, state.dstDesc)) - return true; - - return !patternPremultipliedAfterSampling(state); -} - -/** - * \brief Apply coverage [0 .. 256] on color - * \note This is actually "just coverage". - */ -RI_INLINE static IntegerColor srcCoverage(const IntegerColor& s, const IntegerColor& d, RIuint32 cov) -{ - IntegerColor r; - RIuint32 icov = 256-cov; - // Make function for multiplication between fixed point values (coverage is - // a proper [0 .. 1] value. - r.r = (s.r * cov + d.r * icov) >> 8; - r.g = (s.g * cov + d.g * icov) >> 8; - r.b = (s.b * cov + d.b * icov) >> 8; - r.a = (s.a * cov + d.a * icov) >> 8; - - RI_ASSERT(r.r <= 255 && r.g <= 255 && r.b <= 255 && r.a <= 255); - - return r; -} - -/** - * \brief Converts color gamma only. Care must be taken concerning luminance color formats. - * \return Converted color in "color". This will always be unpremultiplied if gamma conversion - * takes place, i.e, tries to minimize the amount of further conversions. - */ -RI_INLINE static void maybeGammaConvert(const Color::Descriptor& srcDesc, const Color::Descriptor& dstDesc, IntegerColor& color, bool inputPremultiplied) -{ - if (needGammaConvert(srcDesc, dstDesc)) - { - if (inputPremultiplied) - color.unpremultiply(); - //color.unpremultiply(srcDesc.isLuminance()); - - if (dstDesc.isNonlinear()) - color.linearToGamma(); - else - color.gammaToLinear(); - } - // Output always unpremultiplied if gamma conversion takes place -} - -/** - * \brief Integer pixel-pipeline. - * \note See internal_formats.txt for info on how the data is passed within the pipeline - */ -RI_INLINE static void intPixelPipe(const PixelPipe::SignatureState& signatureState, const PixelPipe::PPUniforms &uniforms, PixelPipe::PPVariants& variants) -{ - const RIuint32 ppMaxCoverage = Rasterizer::MAX_COVERAGE << (8 - Rasterizer::SAMPLE_BITS); - RIuint32 coverage = variants.coverage << (8 - Rasterizer::SAMPLE_BITS); - IntegerColor out; - IntegerColor imageColor; // imagemode != normal - const Color::Descriptor& dstDesc = signatureState.dstDesc; - const Color::Descriptor& patternDesc = signatureState.patternDesc; - const Color::Descriptor& imageDesc = signatureState.imageDesc; - - if (!PixelPipe::isImageOnly(signatureState)) - { - switch(signatureState.paintType) - { - case VG_PAINT_TYPE_COLOR: - out = uniforms.solidColor; - break; - case VG_PAINT_TYPE_LINEAR_GRADIENT: - out = intLinearGradient(signatureState, uniforms, variants); - variants.sx += uniforms.dgdx; - // \todo Optimize this so that the lookup is in premultiplied dst format! - // How about image-operations? - if ((signatureState.imageMode != VG_DRAW_IMAGE_MULTIPLY) && dstDesc.isLuminance()) - { - out.fullRGBToLuminance(true, dstDesc.isNonlinear(), true, dstDesc.isNonlinear()); - } - break; - case VG_PAINT_TYPE_RADIAL_GRADIENT: - out = intRadialGradient(signatureState, uniforms, variants); - variants.rx += uniforms.rdxdx; - variants.ry += uniforms.rdydx; - - // \todo Optimize this so that the lookup is in premultiplied dst format! - if ((signatureState.imageMode != VG_DRAW_IMAGE_MULTIPLY) && dstDesc.isLuminance()) - { - out.fullRGBToLuminance(true, dstDesc.isNonlinear(), true, dstDesc.isNonlinear()); - } - break; - default: - RI_ASSERT(signatureState.paintType == VG_PAINT_TYPE_PATTERN); - out = intPattern(signatureState, uniforms, variants); - // color-space == pattern color-space, not always premultiplied, expanded - // - // \todo Only increment the proper pixel-counters. This requires detecting the - // transform type before generating the pixel-pipeline. - // \note Implement fastpaths for at least identity transform with image edges coinciding - // with the pixel edges. <- This has been done for images. - variants.sx += uniforms.paint_dxdx; - variants.sy += uniforms.paint_dydx; - - if (!patternDesc.hasAlpha()) - out.a = 255; - - if (!signatureState.hasImage) - { - out = maybeColorTransform(signatureState, out, uniforms.colorTransformValues, patternDesc.isNonlinear()); - const bool tmpPre = patternPremultipliedAfterSampling(signatureState) && !signatureState.hasColorTransform; - const bool outLuminance = !signatureState.hasColorTransform && imageDesc.isLuminance(); - - if (outLuminance != dstDesc.isLuminance()) - { - if (outLuminance) - out.fullLuminanceToRGB(tmpPre, patternDesc.isNonlinear(), tmpPre, patternDesc.isNonlinear()); - else - out.fullRGBToLuminance(tmpPre, patternDesc.isNonlinear(), tmpPre, patternDesc.isNonlinear()); - } - maybeGammaConvert(patternDesc, dstDesc, out, tmpPre); - } - - break; - } - } - - if (signatureState.hasImage) - { - switch (signatureState.imageGradientType) - { - case PixelPipe::GRADIENT_TYPE_INTEGER: - { - void* addr = Image::calculateAddress(uniforms.imagePtr, imageDesc.bitsPerPixel, variants.iImageX, variants.iImageY, uniforms.imageStride); - RIuint32 packedImageColor = Image::readPackedPixelFromAddress(addr, imageDesc.bitsPerPixel, variants.iImageX); - imageColor.fromPackedColor(packedImageColor, imageDesc); - imageColor.expandColor(imageDesc); - // color-space == image color-space, not always premultiplied, expanded - - // Only integer image-gradient can have unsafe image data as an input at the moment. - if (signatureState.unsafeImageInput) - { - if (imageDesc.hasAlpha() && imageDesc.isPremultiplied()) - imageColor.clampToAlpha(); - } - - variants.iImageX += uniforms.image_idxdx; - variants.iImageY += uniforms.image_idydx; - break; - } - case PixelPipe::GRADIENT_TYPE_FIXED: - { - RI_ASSERT(!signatureState.unsafeImageInput); - - RIint32 sx, sy; - sx = variants.iImageX; - sy = variants.iImageY; - applyPatternRepeat(sx, sy, PixelPipe::TILING_MODE_PAD); - sx = gradientToFixedCoords(sx, uniforms.image_iWidth); - sy = gradientToFixedCoords(sy, uniforms.image_iHeight); - imageColor = intSampleImage( - uniforms.imagePtr, - uniforms.imageStride, - uniforms.image_iWidth, - uniforms.image_iHeight, - imageDesc, - sx, sy, signatureState.imageSampler, PixelPipe::TILING_MODE_PAD, NULL); - - variants.iImageX += uniforms.image_idxdx; - variants.iImageY += uniforms.image_idydx; - break; - } - default: - { - RI_ASSERT(signatureState.imageGradientType == PixelPipe::GRADIENT_TYPE_FLOAT); - RI_ASSERT(!signatureState.unsafeImageInput); - - RIfloat fx, fy, fw, rw; - fx = variants.fImageX; - fy = variants.fImageY; - fw = variants.fImageW; - rw = 1.0f / fw; - RIint32 sx0, sy0; - fx = RI_CLAMP(fx * rw, 0.0f, uniforms.image_fWidth - 1.0f); // \todo fImageMaxX - fy = RI_CLAMP(fy * rw, 0.0f, uniforms.image_fHeight - 1.0f); - sx0 = RI_ROUND_TO_INT(fx * (1<> 7); - coverage = (coverage * maskCoverage) >> 8; - - variants.maskPtr = (void*)Image::incrementPointer(variants.maskPtr, maskBpp, variants.dstX); - } - -#if defined(RI_DEBUG) - IntegerColor preblend = out; -#endif - // \todo Coverage check for pixelpipes != solid color with solid output colors? - - IntegerColor d(0,0,0,0); - - // All operations that depend on DST are done next. Keep it organized like that. - if ((coverage < ppMaxCoverage) || (out.a < 255) || alwaysLoadDst(signatureState)) - { - d = IntegerColor(Image::readPackedPixelFromAddress( - variants.dst, dstDesc.bitsPerPixel, variants.dstX), dstDesc); - d.expandColor(dstDesc); - - if (!dstDesc.isPremultiplied()) - { - d.premultiply(); - } - - // Premultiply output -#if 0 - if (!PixelPipe::isImageOnly(signatureState)) - { - if (signatureState.paintType == VG_PAINT_TYPE_PATTERN && !patternPremultipliedAfterSampling(signatureState)) - out.premultiply(); - else if (signatureState.hasImage && !imagePremultipliedAfterSampling(signatureState)) - out.premultiply(); - } -#endif - - if (!signatureState.isRenderToMask) - { - VGBlendMode bm = signatureState.blendMode; - - // Currently SRC requires premultiplication even when only applying coverage. - //if (bm != VG_BLEND_SRC) - { - // If the src color has not been premultiplied before, now's the time. - // \todo Fast path for src alpha == 255 and SRC_OVER? Others? - if (preBlendPremultiplication(signatureState)) - out.premultiply(); - } - - if (signatureState.hasImage && signatureState.imageMode == VG_DRAW_IMAGE_STENCIL) - { - out = blendIntegerStencil(out, imageColor, d, bm); - } - else - { - switch(bm) - { - case VG_BLEND_SRC_OVER: - out = srcOverCoverage(out, d, coverage); - break; - case VG_BLEND_SRC: - out = srcCoverage(out, d, coverage); - break; - default: - out = blendIntegerColors(out, d, bm); - out = srcCoverage(out, d, coverage); - break; - } - } - -#if defined(RI_DEBUG) - if (dstDesc.isPremultiplied()) - { - RI_ASSERT(out.r <= out.a); - RI_ASSERT(out.g <= out.a); - RI_ASSERT(out.b <= out.a); - } -#endif - - } - else - { - // Mask operation - out = intMaskOperation(coverage, d, signatureState.maskOperation); - } - - // out is always premultiplied at this point. Must be in destination color-space - if (!dstDesc.isPremultiplied()) - { - // Unpremultiply if output is not premultiplied - out.unpremultiply(); - } - } - else - { - // Unpremultiply, ... - if (!dstDesc.isPremultiplied()) - out.unpremultiply(); - } - - // VG_SET_MASK does not require dst load: - if (signatureState.isRenderToMask && signatureState.maskOperation == VG_SET_MASK) - out = intMaskOperation(coverage, d, VG_SET_MASK); - - out.truncateColor(dstDesc); - Image::writePackedPixelToAddress( - variants.dst, dstDesc.bitsPerPixel, variants.dstX, out.getPackedColor(dstDesc)); - - // \todo X for bpp < 8 - variants.dst = (void*)Image::incrementPointer(variants.dst, dstDesc.bitsPerPixel, variants.dstX); - //variants.dst = colorBuffer->advancePointer(variants.dst); - variants.dstX++; -} - -RI_INLINE static void fillSolidSpan(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, int startX, int y, int nPixels, RIuint32 packedColor) -{ - Image::fillPackedPixels((void*)uniforms.dstPtr, state.dstDesc.bitsPerPixel, startX, y, uniforms.dstStride, nPixels, packedColor); -} - -/** - * \brief This will calculate all the pixel-pipeline variants that need to be updated per-pixel. - * \note There may be a need for a different, faster function for image rendering, where - * there are faster methods of updating the variants. - */ -RI_INLINE static void prepareSpanVariants(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, const Span& span, PixelPipe::PPVariants& variants) -{ - //variants.dst = uniforms.dst->calculateAddress(span.x0, span.y); - variants.dst = Image::calculateAddress(uniforms.dstPtr, state.dstDesc.bitsPerPixel, span.x0, span.y, uniforms.dstStride); - variants.dstX = span.x0; - variants.coverage = span.coverage; - - if (state.paintType != VG_PAINT_TYPE_COLOR) - { - if (state.paintType == VG_PAINT_TYPE_LINEAR_GRADIENT) - { - // \todo Adjust pixel-center. - int x = uniforms.dgdx * span.x0 + uniforms.dgdy * span.y + uniforms.lgc; - variants.sx = x; - } - else if (state.paintType == VG_PAINT_TYPE_RADIAL_GRADIENT) - { - RGScalar x = uniforms.rdxdx * (RGScalar)span.x0 + uniforms.rdxdy * (RGScalar)span.y; - RGScalar y = uniforms.rdydy * (RGScalar)span.y + uniforms.rdydx * (RGScalar)span.x0; - - variants.rx = x + uniforms.rx0; - variants.ry = y + uniforms.ry0; - } - else - { - RI_ASSERT(state.paintType == VG_PAINT_TYPE_PATTERN); - variants.sx = uniforms.paint_dxdx * span.x0 + uniforms.paint_dxdy * span.y + uniforms.paint_x0; - variants.sy = uniforms.paint_dydy * span.y + uniforms.paint_dydx * span.x0 + uniforms.paint_y0; - } - } - - if (state.hasMasking) - { - variants.maskPtr = Image::calculateAddress(uniforms.maskPtr, state.maskDesc.bitsPerPixel, span.x0, span.y, uniforms.maskStride); - } - - if (state.hasImage) - { - switch (state.imageGradientType) - { - case PixelPipe::GRADIENT_TYPE_INTEGER: - case PixelPipe::GRADIENT_TYPE_FIXED: - variants.iImageX = uniforms.image_ix0 + span.x0 * uniforms.image_idxdx + span.y * uniforms.image_idxdy; - variants.iImageY = uniforms.image_iy0 + span.y * uniforms.image_idydy + span.x0 * uniforms.image_idydx; - break; - default: - RI_ASSERT(state.imageGradientType == PixelPipe::GRADIENT_TYPE_FLOAT); - variants.fImageX = uniforms.image_fx0 + span.x0 * uniforms.image_fdxdx + span.y * uniforms.image_fdxdy; - variants.fImageY = uniforms.image_fy0 + span.y * uniforms.image_fdydy + span.x0 * uniforms.image_fdydx; - variants.fImageW = uniforms.image_fw0 + span.x0 * uniforms.image_fdwdx + span.y * uniforms.image_fdwdy; - break; - } - } -} - -void executePixelPipeline(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans) -{ - RI_ASSERT(nSpans > 0); - for (int i = 0; i < nSpans; i++) - { - const Span& s = spans[i]; - - if (s.coverage != Rasterizer::MAX_COVERAGE || !canSolidFill(state)) - { - int n = s.len; - RI_ASSERT(n); - prepareSpanVariants(state, uniforms, s, variants); - - do { - intPixelPipe(state, uniforms, variants); - } while (--n); - } else - { - fillSolidSpan(state, uniforms, s.x0, s.y, s.len, uniforms.packedSolidColor); - } - } - -} - -void calculatePPHash(PixelPipeHash& hash, const PixelPipe::SignatureState& derivedState) -{ - const RIuint32 blendModeBits = 4; - const RIuint32 imageModeBits = 2; - const RIuint32 paintTypeBits = 2; - const RIuint32 tilingModeBits = 2; - const RIuint32 samplerBits = 1; - const RIuint32 imageGradientTypeBits = 2; - const RIuint32 boolBits = 1; - const RIuint32 descBits = 10; - const RIuint32 maskOperationBits = 3; - - RIuint32 blendMode = ((RIuint32)derivedState.blendMode) - ((RIuint32)VG_BLEND_SRC); - RIuint32 imageMode = ((RIuint32)derivedState.imageMode) - ((RIuint32)VG_DRAW_IMAGE_NORMAL); - RIuint32 paintType = ((RIuint32)derivedState.paintType) - ((RIuint32)VG_PAINT_TYPE_COLOR); - RIuint32 maskOperation = ((RIuint32)derivedState.maskOperation) - ((RIuint32)VG_CLEAR_MASK); - RIuint32 paintTilingMode = ((RIuint32)derivedState.paintTilingMode); - RIuint32 paintSampler = ((RIuint32)derivedState.paintSampler); - RIuint32 imageSampler = ((RIuint32)derivedState.imageSampler); - - RIuint32 imageGradientType = ((RIuint32)derivedState.imageGradientType); - - RIuint32 dstFormat = (RIuint32)(derivedState.dstDesc.toIndex()); - RIuint32 maskFormat = (RIuint32)(derivedState.maskDesc.toIndex()); - RIuint32 imageFormat = (RIuint32)(derivedState.imageDesc.toIndex()); - RIuint32 patternFormat = (RIuint32)(derivedState.patternDesc.toIndex()); - - RIuint32 hasMasking = derivedState.hasMasking ? 1 : 0; - RIuint32 hasImage = derivedState.hasImage ? 1 : 0; - RIuint32 hasColorTransform = derivedState.hasColorTransform ? 1 : 0; - RIuint32 isMaskOperation = derivedState.isRenderToMask ? 1 : 0; - RIuint32 fillColorTransparent = derivedState.fillColorTransparent ? 1 : 0; - RIuint32 unsafeImageInput = derivedState.unsafeImageInput ? 1 : 0; - - // Modify hashes according to relevant state: - int b = 0; - b = riInsertBits32(hash.value, sizeof(hash.value), blendMode, blendModeBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), imageMode, imageModeBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), paintType, paintTypeBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), maskOperation, maskOperationBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), paintTilingMode, tilingModeBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), paintSampler, samplerBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), imageSampler, samplerBits, b); - - b = riInsertBits32(hash.value, sizeof(hash.value), imageGradientType, imageGradientTypeBits, b); - - b = riInsertBits32(hash.value, sizeof(hash.value), dstFormat, descBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), maskFormat, descBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), imageFormat, descBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), patternFormat, descBits, b); - - b = riInsertBits32(hash.value, sizeof(hash.value), hasMasking, boolBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), hasImage, boolBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), hasColorTransform, boolBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), isMaskOperation, boolBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), fillColorTransparent, boolBits, b); - b = riInsertBits32(hash.value, sizeof(hash.value), unsafeImageInput, boolBits, b); -} - -} - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfDynamicPixelPipe.h --- a/hostsupport/hostopenvg/src/src/sfDynamicPixelPipe.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,50 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __SFDYNAMICPIXELPIPE_H -#define __SFDYNAMICPIXELPIPE_H - -#ifndef __RIPIXELPIPE_H -# include "riPixelPipe.h" -#endif - -namespace OpenVGRI { - - -struct PixelPipeHash -{ - PixelPipeHash() {value[0] = 0; value[1] = 0;} - bool operator==(const PixelPipeHash& rhs) const { return value[0] == rhs.value[0] && value[1] == rhs.value[1]; } - - RIuint32 value[2]; -}; -// Interface to compiler? -void pixelPipelineCall(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans); -// Interface to rasterizer -void executePixelPipeline(const PixelPipe::SignatureState& state, const PixelPipe::PPUniforms& uniforms, PixelPipe::PPVariants& variants, const Span* spans, int nSpans); - -void calculatePPHash(PixelPipeHash& hash, const PixelPipe::SignatureState& state); - -} - -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfEGLInterface.cpp --- a/hostsupport/hostopenvg/src/src/sfEGLInterface.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,470 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#include "SurfaceDescriptor.h" -#include "BufferContainer.h" - -#include "sfEGLInterface.h" -#include "riContext.h" -#include "riPath.h" -#include "vgext.h" -#include "riImage.h" - -namespace - { - EGLtoVGInterface g_EGLtoVGInterface; - } - -IEGLtoVGInterface* getVGInterface(void) -{ - return &g_EGLtoVGInterface; -} - -EGLtoVGInterface::EGLtoVGInterface() : - m_egl(NULL) -{ - m_contexts.reserve(4); -} - -EGLtoVGInterface::~EGLtoVGInterface() -{ - for(int i = 0; i < m_contexts.size(); i++) - { - RI_ASSERT(m_contexts[i]); - RI_DELETE(m_contexts[i]); - } -} - -void EGLtoVGInterface::SetEGLInterface( IVGtoEGLInterface* egl ) -{ - RI_ASSERT(!m_egl); - m_egl = egl; -} - -int EGLtoVGInterface::findContext(OpenVGRI::VGContext* contextPtr) -{ - return m_contexts.findIndex(contextPtr); -} - -bool EGLtoVGInterface::isValidImage(void* image) - { - bool ret = false; - for(int i = 0; i < m_contexts.size() && !ret; i++) - { - ret = m_contexts[i]->isValidImage((VGImage)image); - } - return ret; - } - -void* EGLtoVGInterface::CreateContext( void* shareContext ) -{ - if (shareContext) - { - if (findContext((OpenVGRI::VGContext*)shareContext) < 0) - return NULL; - } - - OpenVGRI::VGContext* newContext = NULL; - - try - { - newContext = RI_NEW(OpenVGRI::VGContext, ((OpenVGRI::VGContext*)shareContext)); - m_contexts.push_back(newContext); - } - catch (std::bad_alloc) - { - if (newContext) - delete newContext; - - newContext = NULL; - } - - return newContext; -} - -bool EGLtoVGInterface::ReleaseContext( void* context ) -{ - int contextIndex = findContext((OpenVGRI::VGContext*)context); - - if (contextIndex < 0) - return false; - - OpenVGRI::VGContext* ctx = (OpenVGRI::VGContext*)context; - if( !m_contexts.remove(ctx) ) - return false; - - RI_DELETE(ctx); - - return true; -} - -OpenVGRI::Color::Descriptor EGLtoVGInterface::vgDescriptorFromSurfaceDescriptor(const SurfaceDescriptor* sdesc) -{ - const CColorDescriptor& scdesc = sdesc->m_colorDescriptor; - OpenVGRI::Color::Descriptor vdesc; - unsigned int formatBits = 0; - - // VG formats are built favoring the first ones in the enum (RGBA, RGBX, etc.) - - // Padded alpha (RGBX, etc.) must be handled. For example: - // if (vdesc.bitsPerPixel < sdesc.bitsPerPixel) - // alphabits = 0, alphashift = 8 - vdesc.bitsPerPixel = scdesc.m_bpp; - vdesc.bytesPerPixel = vdesc.bitsPerPixel >> 3; - - vdesc.alphaBits = scdesc.m_alphaSize; - vdesc.alphaShift = sdesc->m_alphaShift; - vdesc.redBits = scdesc.m_redSize; - vdesc.redShift = sdesc->m_redShift; - vdesc.greenBits = scdesc.m_greenSize; - vdesc.greenShift = sdesc->m_greenShift; - vdesc.blueBits = scdesc.m_blueSize; - vdesc.blueShift = sdesc->m_blueShift; - vdesc.luminanceBits = scdesc.m_luminanceSize; - vdesc.luminanceShift = sdesc->m_luminanceShift; - - if(scdesc.isLuminance()) - formatBits |= OpenVGRI::Color::LUMINANCE; - - // \note Could be copied if LUMINANCE == LUMINANCE, etc. - if (scdesc.isPremultiplied()) - formatBits |= OpenVGRI::Color::PREMULTIPLIED; - - if (scdesc.isNonlinear()) - formatBits |= OpenVGRI::Color::NONLINEAR; - - vdesc.internalFormat = (OpenVGRI::Color::InternalFormat)formatBits; - // \todo format - vdesc.vgFormat = (VGImageFormat)-1; // Not necessarily any VG image format - vdesc.shape = vdesc.getShape(); - - return vdesc; -} - -bool EGLtoVGInterface::CreateSurface(const SurfaceDescriptor* desc, BufferContainer* buffers, void* image) -{ - RI_ASSERT( buffers ); - OpenVGRI::Color::Descriptor vgColorDescriptor; - OpenVGRI::Image* newImage = NULL; - if(image) - { - if(!isValidImage(image)) - return false; - newImage = (OpenVGRI::Image*)image; - vgColorDescriptor = newImage->getDescriptor(); - } - else - { - vgColorDescriptor = vgDescriptorFromSurfaceDescriptor(desc); - } - OpenVGRI::Drawable* newDrawable = NULL; - - //VGImageQuality quality = VG_IMAGE_QUALITY_BETTER; - - int w = desc->m_width; - int h = desc->m_height; - int stride = OpenVGRI::Image::descriptorToStride(vgColorDescriptor, w); - size_t bufSize = h * stride; - - OpenVGRI::RIuint8* dataPtr = NULL; - - try - { - int maskBits = 0; - if( !newImage ) - { - newImage = RI_NEW(OpenVGRI::Image,(vgColorDescriptor, w, h, VG_IMAGE_QUALITY_BETTER)); - maskBits = desc->m_maskSize; - } - else - { - dataPtr = newImage->getData(); - maskBits = newImage->getDescriptor().maskBits; - } - newDrawable = RI_NEW(OpenVGRI::Drawable, (newImage, maskBits)); - newDrawable->addReference(); - } - catch (std::bad_alloc) - { - if (dataPtr) RI_DELETE_ARRAY(dataPtr); - if (newImage) RI_DELETE(newImage); - if (newDrawable) RI_DELETE(newDrawable); - - return false; - } - buffers->m_clientSurface = newDrawable; - buffers->m_colorBuffer = newDrawable->getColorBuffer()->getImage()->getData(); - buffers->m_maskBuffer = newDrawable->getMaskBuffer(); - return true; -} - -bool EGLtoVGInterface::ReleaseSurface(void* surface) -{ - RI_ASSERT(surface); - - OpenVGRI::Drawable *drawable = (OpenVGRI::Drawable*)surface; - - if (!drawable->removeReference()) - RI_DELETE(drawable); - - return true; -} - -bool EGLtoVGInterface::SetCurrentSurface( void* context, void* surface ) -{ - OpenVGRI::Drawable* drawable = (OpenVGRI::Drawable*)surface; - OpenVGRI::VGContext *ctx = (OpenVGRI::VGContext*)context; - - int i = findContext(ctx); - - if (i < 0) - return false; - - ctx->setDefaultDrawable(drawable); - - return true; -} - -bool EGLtoVGInterface::ResizeSurface( void* context, void* surface, int width, int height, BufferContainer* buffers ) - { - OpenVGRI::Drawable* drawable = (OpenVGRI::Drawable*)surface; - OpenVGRI::VGContext *ctx = (OpenVGRI::VGContext*)context; - int i = findContext(ctx); - if(i < 0) - return false; - - try - { - drawable->resize( ctx, width, height ); - } - catch (std::bad_alloc) - { - return false; - } - buffers->m_clientSurface = drawable; - buffers->m_colorBuffer = drawable->getColorBuffer()->getImage()->getData(); - buffers->m_maskBuffer = drawable->getMaskBuffer(); - return true; - } - -bool EGLtoVGInterface::IsValidImage( void* image, CColorDescriptor* colorDesc, int* width, int* height ) -{ - bool ret = isValidImage(image); - if(ret) - { - *width = ((OpenVGRI::Image*)image)->getWidth(); - *height = ((OpenVGRI::Image*)image)->getHeight(); - const OpenVGRI::Color::Descriptor& desc = ((OpenVGRI::Image*)image)->getDescriptor(); - colorDesc->m_bpp = desc.bitsPerPixel; - colorDesc->m_redSize = desc.redBits; - colorDesc->m_greenSize = desc.greenBits; - colorDesc->m_blueSize = desc.blueBits; - colorDesc->m_alphaSize = desc.alphaBits; - colorDesc->m_luminanceSize = desc.luminanceBits; - colorDesc->m_alphaMaskSize = desc.maskBits; - colorDesc->m_format = (CColorDescriptor::ColorFormat)desc.internalFormat; - } - - return ret; -} - -bool EGLtoVGInterface::IsImageInUse( void* image ) -{ - bool ret = false; - if(image && isValidImage(image)) - { - ret = ((OpenVGRI::Image*)image)->isInUse(); - } - return ret; -} - -void* EGLtoVGInterface::CreateImage() -{ - RI_ASSERT(false); - return NULL; -} - -bool EGLtoVGInterface::ReleaseImage() -{ - RI_ASSERT(false); - return false; -} - -void EGLtoVGInterface::Flush() -{ - vgFlush(); -} - -void EGLtoVGInterface::Finish() -{ - vgFinish(); -} - -fpVGProc EGLtoVGInterface::GetVGProcAddress( const char *procname ) -{ - fpVGProc ret = NULL; - if(strcmp(procname, "vgePathCoordsSizeInBytes") == 0) - { - ret = (fpVGProc)vgePathCoordsSizeInBytes; - } - return ret; -} - -void EGLtoVGInterface::CopyBuffers( void* buffer, int stride, void* surface ) - { - OpenVGRI::Drawable *drawable = (OpenVGRI::Drawable*)surface; - int width = drawable->getColorBuffer()->getWidth(); - int height = drawable->getColorBuffer()->getHeight(); - // \todo Pixel format. - VGImageFormat format = VG_sARGB_8888_PRE; - vgReadPixels( buffer, stride, format, 0, 0, width, height ); - } - -void EGLtoVGInterface::UpdateBuffers( void* buffer, int stride, const SurfaceDescriptor* desc ) - { - // \todo format, errors - VGImageFormat format = VG_sARGB_8888_PRE; - vgWritePixels( buffer, stride, format, 0, 0, desc->m_width, desc->m_height ); - } - -bool EGLtoVGInterface::IsRootImage( void* image ) - { - if( !image ) return false; - if ( vgGetParent( (VGImage)image ) ) - { - // if vgGetParent returns not NULL image it is not parent image - // , only child image has parent image, and this should return false - return false; - } - // vgGetParent is NULL and image is parent image - return true; - } - -void EGLtoVGInterface::GetImageData( void* image, SurfaceDescriptor& desc, void* data ) - { - OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image; - if( !image ) - { - return; - } - desc.m_height = vgimage->getHeight(); - desc.m_width = vgimage->getWidth(); - int bufSize; - - OpenVGRI::Color::Descriptor colorDesc = vgimage->getDescriptor(); - VGImageFormat vgFormat; - // Convert some formats into more GL-friendly formats. - if( colorDesc.vgFormat == VG_BW_1 ) - { - vgFormat = VG_lL_8; - } - else if( colorDesc.vgFormat == VG_A_1 || colorDesc.vgFormat == VG_A_4 ) - { - vgFormat = VG_A_8; - } - else - { - vgFormat = colorDesc.vgFormat; - } - desc.m_colorDescriptor.m_format = (CColorDescriptor::ColorFormat)colorDesc.internalFormat; - desc.m_alphaShift = colorDesc.alphaShift; - desc.m_blueShift = colorDesc.blueShift; - desc.m_greenShift = colorDesc.greenShift; - desc.m_redShift = colorDesc.redShift; - desc.m_luminanceShift = colorDesc.luminanceShift; - desc.m_stride = vgimage->getStride(); - - bufSize = (desc.m_stride * desc.m_height); - // Allocate data from memory. - data = RI_NEW_ARRAY(OpenVGRI::RIuint8, bufSize); - // Get data from VG - vgGetImageSubData( (VGImage)vgimage, data, vgimage->getStride(), vgFormat, 0, 0, vgimage->getWidth(), vgimage->getWidth() ); - - } - -void EGLtoVGInterface::AddRef( void* image ) - { - OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image; - if( !image ) - { - return; - } - vgimage->addReference(); - } - -void EGLtoVGInterface::RemoveRef( void* image ) - { - OpenVGRI::Image* vgimage = (OpenVGRI::Image*)image; - if( !image ) - { - return; - } - vgimage->removeReference(); - } - -/*static*/ IVGtoEGLInterface* EGLtoVGInterface::GetEGLInterface() -{ - return g_EGLtoVGInterface.m_egl; -} - -void* OpenVGRI::eglvgGetCurrentVGContext(void) -{ - return EGLtoVGInterface::GetEGLInterface()->GetVGContext(); -} - -bool OpenVGRI::eglvgIsInUse(void* image) -{ - return EGLtoVGInterface::GetEGLInterface()->IsImageInUse(image); -} - -bool OpenVGRI::eglvgLockSurface(bool read, bool write) -{ - return EGLtoVGInterface::GetEGLInterface()->LockVGSurface(read, write); -} - -bool OpenVGRI::eglvgUnlockSurface() -{ - return EGLtoVGInterface::GetEGLInterface()->UnlockVGSurface(); -} - -void OpenVGRI::OSAcquireMutex(void) -{ -} - -void OpenVGRI::OSReleaseMutex(void) -{ -} - -void OpenVGRI::eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride ) - { - SurfaceDescriptor surfDesc; - EGLtoVGInterface::GetEGLInterface()->GetDescForImage( image, surfDesc ); - desc = EGLtoVGInterface::vgDescriptorFromSurfaceDescriptor( &surfDesc ); - width = surfDesc.m_width; - height = surfDesc.m_height; - stride = surfDesc.m_stride; - } - -void* OpenVGRI::eglvgGetImageData( void* image ) - { - return EGLtoVGInterface::GetEGLInterface()->GetDataForImage( image ); - } diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfEGLInterface.h --- a/hostsupport/hostopenvg/src/src/sfEGLInterface.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,89 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef _SFEGLINTERFACE_H_ -#define _SFEGLINTERFACE_H_ - -#include "riImage.h" -#include "VGInterface.h" - - -// Get pointer to global interface object. -extern "C" { RI_API_CALL IEGLtoVGInterface* getVGInterface(void); } -extern "C" { RI_API_CALL VGErrorCode vgPlatsimGetError(void); } - -namespace OpenVGRI -{ - void* eglvgGetCurrentVGContext(void); - bool eglvgIsInUse(void* image); - bool eglvgLockSurface(bool read, bool write); - bool eglvgUnlockSurface(); - void OSAcquireMutex(void); - void OSReleaseMutex(void); - void eglvgGetImageDescriptor( void* image, Color::Descriptor &desc, int &width, int &height, int &stride ); - void* eglvgGetImageData( void* image ); -} - -// Services from OpenVG to EGL -class EGLtoVGInterface : public IEGLtoVGInterface -{ -public: - EGLtoVGInterface(); - ~EGLtoVGInterface(); - - void SetEGLInterface( IVGtoEGLInterface* egl ); - void* CreateContext( void* shareContext ); - bool ReleaseContext( void* context ); - bool CreateSurface( const SurfaceDescriptor* desc, BufferContainer* buffers, void* image ); - bool ReleaseSurface(void* surface); - bool SetCurrentSurface( void* context, void* surface ); - bool ResizeSurface( void* context, void* surface, int width, int height, BufferContainer* buffers ); - bool IsValidImage( void* image, CColorDescriptor* colorDesc, int* width, int* height ); - bool IsImageInUse( void* image ); - void* CreateImage(); - bool ReleaseImage(); - void Flush(); - void Finish(); - fpVGProc GetVGProcAddress( const char *procname ); - void CopyBuffers( void* buffer, int stride, void* surface ); - void UpdateBuffers( void* buffer, int stride, const SurfaceDescriptor* desc ); - bool IsRootImage( void* buffer ); - void GetImageData( void* image, SurfaceDescriptor& desc, void* data ); - void AddRef( void* image ); - void RemoveRef( void* image ); - - // Methods for local OpenVG-implementation. To be called only from OpenVG internals. - static IVGtoEGLInterface* GetEGLInterface(); - static OpenVGRI::Color::Descriptor vgDescriptorFromSurfaceDescriptor(const SurfaceDescriptor* sdesc); // \todo static - -private: - int findContext(OpenVGRI::VGContext* contextPtr); - bool isValidImage(void* image); - -private: - OpenVGRI::Array m_contexts; - IVGtoEGLInterface* m_egl; - -}; - -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfFunctionCache.h --- a/hostsupport/hostopenvg/src/src/sfFunctionCache.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,310 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __SFFUNCTIONCACHE_H -#define __SFFUNCTIONCACHE_H - -// (LRU) Cache for compiled pixelpipe functions. Never takes ownership of -// any of the objects. -// \todo LRU might not be the best strategy or the best strategy might -// depend on the use-case -> create more of these. - -#include "riArray.h" - -#if defined(__unix__) -# include -#else -# include -#endif - -#include "llvm/ExecutionEngine/ExecutionEngine.h" -#include "llvm/Module.h" - -namespace llvm { - class Function; -} - -namespace OpenVGRI { - -template class FunctionCache -{ -private: - enum { IMPLEMENTATION_MAX_CACHE_ENTRIES = 1024 }; - //enum { MAX_GLOBAL_TIME = 10000}; - enum { MAX_GLOBAL_TIME = RI_UINT32_MAX }; - - struct CacheEntry - { - CacheEntry() : refCount(1) {} - CacheEntry(HashClass aHash, ::llvm::Function* aFunc, ::llvm::GlobalVariable* aConst, RIuint32 theUT) : refCount(1) {hash = aHash; llvmFunction = aFunc; llvmConstant = aConst; ut = theUT;} - bool operator==(const CacheEntry& rhs) const { return hash == rhs.hash; } - bool operator<(const CacheEntry& rhs) const { return ut < rhs.ut; } // Sort by time of usage. - - HashClass hash; - ::llvm::Function* llvmFunction; - ::llvm::GlobalVariable* llvmConstant; - RIuint32 ut; - RIint32 refCount; - }; - -public: - typedef CacheEntry* EntryHandle; - -public: - FunctionCache(int nMaxEntries) : - m_time(0) - { - // Limit so that if the cache is too large, you must optimize the implementation. - // Also note that the optimized pixel pipes are most likely small, so it would - // be better to have a fast cache and a lot of entries! - // \note A simple optimization is to sort the usage time sort order and remove the last - // item in the array (instead of the first). - RI_ASSERT(nMaxEntries > 0 && nMaxEntries < IMPLEMENTATION_MAX_CACHE_ENTRIES); - m_nMaxEntries = nMaxEntries; - m_entries.reserve(nMaxEntries); - } - - ~FunctionCache() - { - for (int i = 0; i < m_entries.size(); i++) - { - clearEntry(m_entries[i]); - } - } - - // This info is needed for the module to remove functions and deallocate executable - // functions: - void setLLVMInterface(::llvm::ExecutionEngine* ee, ::llvm::Module* module) - { - m_executionEngine = ee; - m_module = module; - } - - // \todo If we never need the entry index, the locking can be - // simplified a lot. - // Must lock the cache during this operation! - EntryHandle findCachedItemByHash(const HashClass& hash) - { - acquireMutex(); - int i = findCachedItemIndexByHash(hash, true); - if (i == -1) - { - releaseMutex(); - return NULL; - } - EntryHandle handle = &m_entries[i]; - releaseMutex(); - - return handle; - } - - /** - * \brief Caches a function. Sets the reference count to 1 - * \return EntryHandle != NULL on success. - * \todo The cache must be locked during the operation. - */ - EntryHandle cacheFunction(HashClass hash, ::llvm::Function* function, ::llvm::GlobalVariable* constant) - { - acquireMutex(); - RI_ASSERT(findCachedItemIndexByHash(hash) == -1); - - if (m_entries.size() == m_nMaxEntries) - { - if (!removeLRU()) - { - releaseMutex(); - return NULL; - } - } - - m_entries.push_back(CacheEntry(hash, function, constant, m_time)); - - RI_ASSERT(m_entries.size() > 0); - EntryHandle ret = &m_entries[m_entries.size()-1]; - incrementGlobalTime(); - - releaseMutex(); - return ret; - } - - ::llvm::Function* getFunction(EntryHandle handle) - { - return handle->llvmFunction; - } - - // \note Does not remove the function from cache! - void releaseEntry(EntryHandle handle) - { - RI_ASSERT(handle->refCount > 0); - handle->refCount--; - } - -private: - void incrementGlobalTime() - { - m_time++; - if (m_time == MAX_GLOBAL_TIME) - rebaseUsageTime(); - } - - void incrementAccessTime(CacheEntry &entry) - { - entry.ut = m_time; - incrementGlobalTime(); - } - - int findCachedItemIndexByHash(const HashClass& hash, bool reserve = false) - { - // \note Could just overload operator== from entry and use the Array.find function. - for (int i = 0; i < m_entries.size(); i++) - { - if (m_entries[i].hash == hash) - { - if (reserve) - { - incrementAccessTime(m_entries[i]); - m_entries[i].refCount++; - } - return i; - } - } - return -1; - } - - void clearEntry(CacheEntry& entry) - { - m_executionEngine->freeMachineCodeForFunction(entry.llvmFunction); - entry.llvmFunction->eraseFromParent(); - //entry.llvmConstant->eraseFromParent(); - } - - /** - * \return true if LRU item was successfully removed, false otherwise. - * \note Could try other pipes, but it is unlikely that the cache gets filled - * so soon that the blit for the least recently used blit has not been - * released. - * \todo Implement drop of other cache-entries? - */ - bool removeLRU() - { - // \note This is pretty inefficient for many cache size: - // After first LRU removal, the cache is almost sorted anyway, so - // more efficient solution should be implemented. - // - m_entries.sort(); - - if (m_entries[0].refCount > 0) - return false; - - clearEntry(m_entries[0]); - m_entries.remove(m_entries[0]); - - return true; - } - - void rebaseUsageTime() - { - RIuint32 i; - m_entries.sort(); - RI_ASSERT(m_entries.size() > 0); - for(i = 0; i < (RIuint32)m_entries.size(); i++) - { - m_entries[i].ut = i; - }; - m_time = i; - } - - static void acquireMutex(); - static void releaseMutex(); - -private: - ::llvm::Module *m_module; - ::llvm::ExecutionEngine *m_executionEngine; - - RIuint32 m_time; - Array m_entries; - int m_nMaxEntries; - - static bool s_mutexInitialized; -#if defined(__unix__) - static pthread_mutex_t s_mutex; -#else - static CRITICAL_SECTION s_mutex; -#endif -}; - -template -bool FunctionCache::s_mutexInitialized = false; - -#if defined(__unix__) -template -pthread_mutex_t FunctionCache::s_mutex; -#else -template -CRITICAL_SECTION FunctionCache::s_mutex; -#endif - -template -void FunctionCache::acquireMutex() -{ - if (!s_mutexInitialized) - { -#if defined(__unix__) - int ret; - pthread_mutexattr_t attr; - ret = pthread_mutexattr_init(&attr); //initially not locked - RI_ASSERT(!ret); //check that there aren't any errors - ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); //count the number of recursive locks - RI_ASSERT(!ret); //check that there aren't any errors - ret = pthread_mutex_init(&s_mutex, &attr); - pthread_mutexattr_destroy(&attr); - RI_ASSERT(!ret); //check that there aren't more errors -#else - ::InitializeCriticalSection(&s_mutex); -#endif - s_mutexInitialized = true; - } -#if defined(__unix__) - int ret = pthread_mutex_lock(&s_mutex); - RI_ASSERT(!ret); -#else - ::EnterCriticalSection(&s_mutex); -#endif -} - -template -void FunctionCache::releaseMutex() -{ - RI_ASSERT(s_mutexInitialized); -#if defined(__unix__) - int ret = pthread_mutex_unlock(&s_mutex); - RI_ASSERT(!ret); -#else - ::LeaveCriticalSection(&s_mutex); -#endif -} - -} - - -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfGammaLUT.h --- a/hostsupport/hostopenvg/src/src/sfGammaLUT.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,100 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef _SFGAMMARCP_H_ -#define _SFGAMMARCP_H_ - -#include "riDefs.h" - -namespace OpenVGRI { -static const RIuint8 sc_sRGB_to_lRGB[256] = { - 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, - 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, - 0x1, 0x1, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, - 0x2, 0x2, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, - 0x4, 0x4, 0x4, 0x4, 0x5, 0x5, 0x5, 0x5, - 0x5, 0x6, 0x6, 0x6, 0x6, 0x7, 0x7, 0x7, - 0x8, 0x8, 0x8, 0x8, 0x9, 0x9, 0x9, 0xa, - 0xa, 0xa, 0xb, 0xb, 0xc, 0xc, 0xc, 0xd, - 0xd, 0xe, 0xe, 0xe, 0xf, 0xf, 0x10, 0x10, - 0x11, 0x11, 0x12, 0x12, 0x12, 0x13, 0x13, 0x14, - 0x15, 0x15, 0x16, 0x16, 0x17, 0x17, 0x18, 0x18, - 0x19, 0x1a, 0x1a, 0x1b, 0x1b, 0x1c, 0x1d, 0x1d, - 0x1e, 0x1f, 0x1f, 0x20, 0x21, 0x21, 0x22, 0x23, - 0x23, 0x24, 0x25, 0x26, 0x26, 0x27, 0x28, 0x29, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2d, 0x2e, 0x2f, - 0x30, 0x31, 0x32, 0x33, 0x33, 0x34, 0x35, 0x36, - 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, - 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, - 0x47, 0x48, 0x49, 0x4a, 0x4c, 0x4d, 0x4e, 0x4f, - 0x50, 0x51, 0x52, 0x54, 0x55, 0x56, 0x57, 0x58, - 0x5a, 0x5b, 0x5c, 0x5d, 0x5f, 0x60, 0x61, 0x63, - 0x64, 0x65, 0x67, 0x68, 0x69, 0x6b, 0x6c, 0x6d, - 0x6f, 0x70, 0x72, 0x73, 0x74, 0x76, 0x77, 0x79, - 0x7a, 0x7c, 0x7d, 0x7f, 0x80, 0x82, 0x83, 0x85, - 0x86, 0x88, 0x8a, 0x8b, 0x8d, 0x8e, 0x90, 0x92, - 0x93, 0x95, 0x97, 0x98, 0x9a, 0x9c, 0x9d, 0x9f, - 0xa1, 0xa3, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xad, - 0xaf, 0xb1, 0xb3, 0xb5, 0xb7, 0xb8, 0xba, 0xbc, - 0xbe, 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, - 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, - 0xde, 0xe0, 0xe2, 0xe5, 0xe7, 0xe9, 0xeb, 0xed, - 0xef, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfd, 0xff, -}; - -static const RIuint8 sc_lRGB_to_sRGB[256] = { - 0x0, 0xd, 0x16, 0x1c, 0x21, 0x26, 0x2a, 0x2e, - 0x31, 0x35, 0x38, 0x3a, 0x3d, 0x40, 0x42, 0x44, - 0x47, 0x49, 0x4b, 0x4d, 0x4f, 0x51, 0x53, 0x55, - 0x56, 0x58, 0x5a, 0x5b, 0x5d, 0x5f, 0x60, 0x62, - 0x63, 0x65, 0x66, 0x67, 0x69, 0x6a, 0x6c, 0x6d, - 0x6e, 0x70, 0x71, 0x72, 0x73, 0x74, 0x76, 0x77, - 0x78, 0x79, 0x7a, 0x7b, 0x7d, 0x7e, 0x7f, 0x80, - 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, - 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, - 0x91, 0x92, 0x93, 0x93, 0x94, 0x95, 0x96, 0x97, - 0x98, 0x99, 0x9a, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, - 0x9f, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa3, 0xa4, - 0xa5, 0xa6, 0xa7, 0xa7, 0xa8, 0xa9, 0xaa, 0xaa, - 0xab, 0xac, 0xad, 0xad, 0xae, 0xaf, 0xaf, 0xb0, - 0xb1, 0xb2, 0xb2, 0xb3, 0xb4, 0xb4, 0xb5, 0xb6, - 0xb6, 0xb7, 0xb8, 0xb8, 0xb9, 0xba, 0xba, 0xbb, - 0xbc, 0xbc, 0xbd, 0xbe, 0xbe, 0xbf, 0xc0, 0xc0, - 0xc1, 0xc2, 0xc2, 0xc3, 0xc3, 0xc4, 0xc5, 0xc5, - 0xc6, 0xc7, 0xc7, 0xc8, 0xc8, 0xc9, 0xca, 0xca, - 0xcb, 0xcb, 0xcc, 0xcd, 0xcd, 0xce, 0xce, 0xcf, - 0xcf, 0xd0, 0xd1, 0xd1, 0xd2, 0xd2, 0xd3, 0xd3, - 0xd4, 0xd5, 0xd5, 0xd6, 0xd6, 0xd7, 0xd7, 0xd8, - 0xd8, 0xd9, 0xda, 0xda, 0xdb, 0xdb, 0xdc, 0xdc, - 0xdd, 0xdd, 0xde, 0xde, 0xdf, 0xdf, 0xe0, 0xe0, - 0xe1, 0xe2, 0xe2, 0xe3, 0xe3, 0xe4, 0xe4, 0xe5, - 0xe5, 0xe6, 0xe6, 0xe7, 0xe7, 0xe8, 0xe8, 0xe9, - 0xe9, 0xea, 0xea, 0xeb, 0xeb, 0xec, 0xec, 0xed, - 0xed, 0xed, 0xee, 0xee, 0xef, 0xef, 0xf0, 0xf0, - 0xf1, 0xf1, 0xf2, 0xf2, 0xf3, 0xf3, 0xf4, 0xf4, - 0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf8, - 0xf8, 0xf9, 0xf9, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb, - 0xfc, 0xfc, 0xfd, 0xfd, 0xfe, 0xfe, 0xff, 0xff, -}; -} -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/sfMask.h --- a/hostsupport/hostopenvg/src/src/sfMask.h Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,85 +0,0 @@ -/* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - */ - -#ifndef __SFMASK_H -#define __SFMASK_H - -#include "VG/openvg.h" - -#ifndef __RIDEFS_H -# include "riDefs.h" -#endif - -#ifndef __RIIMAGE_H -# include "riImage.h" -#endif - -// Contains implementations of some mask operations that are needed in both the -// pixel-pipeline and the blitter. - -namespace OpenVGRI { - -RI_INLINE IntegerColor intMaskOperation(RIuint32 coverage, const IntegerColor& d, VGMaskOperation maskOperation); - -RI_INLINE IntegerColor intMaskOperation(RIuint32 coverage, const IntegerColor& d, VGMaskOperation maskOperation) -{ - RIuint32 newCoverage; - switch (maskOperation) - { - case VG_SET_MASK: - // \note This should work approximately if coverage < 256 always. - // See other cases for proper conversions. - return IntegerColor(0, 0, 0, coverage); // nop. - break; - case VG_UNION_MASK: - { - RIuint32 oldCoverage = d.a; - oldCoverage += (oldCoverage >> 7); - RIuint32 im = 256 - coverage; - RIuint32 ip = 256 - oldCoverage; - newCoverage = 256 - ((im * ip) >> 8); - break; - } - case VG_INTERSECT_MASK: - { - RIuint32 oldCoverage = d.a; - oldCoverage += (oldCoverage >> 7); - newCoverage = (coverage * oldCoverage) >> 8; - break; - } - default: - { - RI_ASSERT(maskOperation == VG_SUBTRACT_MASK); - RIuint32 im = 256 - coverage; - RIuint32 oldCoverage = d.a; - oldCoverage += (oldCoverage >> 7); - newCoverage = (oldCoverage * im) >> 8; - break; - } - } - return IntegerColor(0, 0, 0, newCoverage - (newCoverage >> 8)); -} - -} - -#endif - diff -r c2ef9095503a -r 067180f57b12 hostsupport/hostopenvg/src/src/win32/riEGLOS.cpp --- a/hostsupport/hostopenvg/src/src/win32/riEGLOS.cpp Wed Oct 06 17:59:01 2010 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,382 +0,0 @@ -/*------------------------------------------------------------------------ - * - * EGL 1.3 - * ------- - * - * Copyright (c) 2007 The Khronos Group Inc. - * Portions copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and /or associated documentation files - * (the "Materials "), to deal in the Materials without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Materials, - * and to permit persons to whom the Materials are furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Materials. - * - * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR - * THE USE OR OTHER DEALINGS IN THE MATERIALS. - * - *//** - * \file - * \brief Simple implementation of EGL 1.3 - * \note caveats: - - always renders into the backbuffer and blits it to window (no single buffered rendering) - - no native Windows or Mac OS X pixmap support - - no power management events - - no support for swap interval - * \todo what happens in egl functions when eglTerminate has been called but the context and surface are still in use? - * \todo OSDeinitMutex should be called in case getEGL fails. - * \todo clarify getThread and getCurrentThread distinction. - *//*-------------------------------------------------------------------*/ - -#include "EGL/egl.h" -#include "openvg.h" -#include "riArray.h" -#include "riMath.h" -#include "riContext.h" -#include "riImage.h" - -namespace OpenVGRI -{ - -#include - -void* OSGetCurrentThreadID(void) -{ - return (void*)GetCurrentThreadId(); //TODO this is not safe -} - -static HANDLE mutex = NULL; -static int mutexRefCount = 0; -//acquired mutex cannot be deinited. -void OSDeinitMutex(void) -{ - RI_ASSERT(mutex); - RI_ASSERT(mutexRefCount == 0); - BOOL ret = CloseHandle(mutex); - RI_ASSERT(ret); - RI_UNREF(ret); -} -void OSAcquireMutex(void) -{ - if(!mutex) - { - mutex = CreateMutex(NULL, FALSE, NULL); //initially not locked - mutexRefCount = 0; - } - RI_ASSERT(mutex); - DWORD ret = WaitForSingleObject(mutex, INFINITE); - RI_ASSERT(ret != WAIT_FAILED); - RI_UNREF(ret); - mutexRefCount++; -} -void OSReleaseMutex(void) -{ - RI_ASSERT(mutex); - mutexRefCount--; - RI_ASSERT(mutexRefCount >= 0); - BOOL ret = ReleaseMutex(mutex); - RI_ASSERT(ret); - RI_UNREF(ret); -} - -static bool isBigEndian() -{ - static const RIuint32 v = 0x12345678u; - const RIuint8* p = (const RIuint8*)&v; - RI_ASSERT (*p == (RIuint8)0x12u || *p == (RIuint8)0x78u); - return (*p == (RIuint8)(0x12)) ? true : false; -} - - -#ifdef RI_USE_GLUT -# include -# define GLUT_DISABLE_ATEXIT_HACK -# include "glut.h" - -struct OSWindowContext -{ - int window; - unsigned int* tmp; - int tmpWidth; - int tmpHeight; -}; - -void* OSCreateWindowContext(EGLNativeWindowType window) -{ - try - { - OSWindowContext* ctx = RI_NEW(OSWindowContext, ()); - ctx->window = (int)window; - ctx->tmp = NULL; - ctx->tmpWidth = 0; - ctx->tmpHeight = 0; - return ctx; - } - catch(std::bad_alloc) - { - return NULL; - } -} - -void OSDestroyWindowContext(void* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - RI_DELETE_ARRAY(ctx->tmp); - RI_DELETE(ctx); - } -} - -bool OSIsWindow(const void* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - //TODO implement - return true; - } - return false; -} - -void OSGetWindowSize(const void* context, int& width, int& height) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - int currWin = glutGetWindow(); - glutSetWindow(ctx->window); - width = glutGet(GLUT_WINDOW_WIDTH); - height = glutGet(GLUT_WINDOW_HEIGHT); - glutSetWindow(currWin); - } - else - { - width = 0; - height = 0; - } -} - -void OSBlitToWindow(void* context, const Drawable* drawable) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - int w = drawable->getWidth(); - int h = drawable->getHeight(); - - int currWin = glutGetWindow(); - glutSetWindow(ctx->window); - - if(!ctx->tmp || ctx->tmpWidth != w || ctx->tmpHeight != h) - { - RI_DELETE_ARRAY(ctx->tmp); - ctx->tmp = NULL; - try - { - ctx->tmp = RI_NEW_ARRAY(unsigned int, w*h); //throws bad_alloc - ctx->tmpWidth = w; - ctx->tmpHeight = h; - } - catch(std::bad_alloc) - { - //do nothing - } - } - - if(ctx->tmp) - { - glViewport(0, 0, w, h); - glDisable(GL_DEPTH_TEST); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - //NOTE: we assume here that the display is always in sRGB color space - VGImageFormat f = VG_sXBGR_8888; - if(isBigEndian()) - f = VG_sRGBX_8888; - vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h); - glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, ctx->tmp); - } - - glutSwapBuffers(); //shows the OpenGL frame buffer - glutSetWindow(currWin); //restore the current window - } -} - -EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id) -{ - return (EGLDisplay)display_id; //just casting to (EGLDisplay) should be enough to make a unique identifier out of this -} - -#else -//Windows native -#ifndef _WINDOWS_ -# define _WIN32_WINNT 0x0400 -# define WIN32_LEAN_AND_MEAN -# include -#endif - -struct OSWindowContext -{ - HWND window; - HDC bufDC; - HBITMAP bufDIB; - unsigned int* tmp; - int tmpWidth; - int tmpHeight; -}; - -OSWindowContext* OSCreateWindowContext(EGLNativeWindowType window) -{ - OSWindowContext* ctx = NULL; - try - { - ctx = RI_NEW(OSWindowContext, ()); - } - catch(std::bad_alloc) - { - return NULL; - } - - ctx->window = (HWND)window; - HDC winDC = GetDC(ctx->window); - ctx->bufDC = CreateCompatibleDC(winDC); - ReleaseDC(ctx->window, winDC); - if(!ctx->bufDC) - { - RI_DELETE(ctx); - return NULL; - } - - ctx->bufDIB = NULL; - ctx->tmp = NULL; - ctx->tmpWidth = 0; - ctx->tmpHeight = 0; - return ctx; -} - -void OSDestroyWindowContext(OSWindowContext* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - if(ctx->bufDC) - { - SelectObject(ctx->bufDC, NULL); - DeleteDC(ctx->bufDC); - } - if(ctx->bufDIB) - DeleteObject(ctx->bufDIB); - RI_DELETE(ctx); - } -} - -bool OSIsWindow(const OSWindowContext* context) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - if(IsWindow(ctx->window)) - return true; - } - return false; -} - -void OSGetWindowSize(const OSWindowContext* context, int& width, int& height) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - RECT rect; - GetClientRect(ctx->window, &rect); - width = rect.right - rect.left; - height = rect.bottom - rect.top; - } - else - { - width = 0; - height = 0; - } -} - -void OSBlitToWindow(OSWindowContext* context, const Drawable* drawable) -{ - OSWindowContext* ctx = (OSWindowContext*)context; - if(ctx) - { - int w = drawable->getWidth(); - int h = drawable->getHeight(); - - if(!ctx->tmp || !ctx->bufDIB || ctx->tmpWidth != w || ctx->tmpHeight != h) - { - if(ctx->bufDIB) - DeleteObject(ctx->bufDIB); - ctx->tmp = NULL; - ctx->bufDIB = NULL; - - ctx->tmpWidth = w; - ctx->tmpHeight = h; - - struct - { - BITMAPINFOHEADER header; - DWORD rMask; - DWORD gMask; - DWORD bMask; - } bmi; - bmi.header.biSize = sizeof(BITMAPINFOHEADER); - bmi.header.biWidth = w; - bmi.header.biHeight = h; - bmi.header.biPlanes = 1; - bmi.header.biBitCount = (WORD)32; - bmi.header.biCompression = BI_BITFIELDS; - bmi.rMask = 0x000000ff; - bmi.gMask = 0x0000ff00; - bmi.bMask = 0x00ff0000; - ctx->bufDIB = CreateDIBSection(ctx->bufDC, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&ctx->tmp, NULL, 0); - if(!ctx->bufDIB) - { - ctx->tmp = NULL; - return; - } - } - - if(ctx->tmp) - { - //NOTE: we assume here that the display is always in sRGB color space - GdiFlush(); - VGImageFormat f = VG_sABGR_8888_PRE; - if(isBigEndian()) - f = VG_sRGBA_8888_PRE; - vgReadPixels(ctx->tmp, w*sizeof(unsigned int), f, 0, 0, w, h); - - SelectObject(ctx->bufDC, ctx->bufDIB); - HDC winDC = GetDC(ctx->window); - BitBlt(winDC, 0, 0, w, h, ctx->bufDC, 0, 0, SRCCOPY); - ReleaseDC(ctx->window, winDC); - SelectObject(ctx->bufDC, NULL); - } - } -} - -EGLDisplay OSGetDisplay(EGLNativeDisplayType display_id) -{ - RI_UNREF(display_id); - return (EGLDisplay)1; //support only a single display -} - -#endif - -} //namespace OpenVGRI